Exemple #1
0
        static void Main(string[] args)
        {
            var ravenStore   = RavenDb.Init(ConsistencyOptions.None, null);
            var ravenSession = ravenStore.OpenAsyncSession();

            var martenStore = Marten.DocumentStore.For(x =>
            {
                x.Connection("host=localhost;database=StudioHub;password=admin;username=postgres");

                x.Schema.Include <ImportRegistry>();
            });
            var martenSession = martenStore.OpenSession();

            var repo = new RavenRepository <Release>(ravenSession);

            for (int i = 200; i < 350; i++)
            {
                Console.WriteLine($"loading page {i}");
                var releases = repo.GetAll(i, 1024).GetAwaiter().GetResult();

                foreach (var release in releases)
                {
                    martenSession.Store <Release>(release);
                }

                martenSession.SaveChangesAsync().GetAwaiter().GetResult();
            }

            Console.ReadKey();
        }
Exemple #2
0
        public async Task TagListAsync()
        {
            var guild = RavenDb.GetGuild(Context.Guild.Id);
            Dictionary <string, List <string> > tags = new Dictionary <string, List <string> >();

            foreach (var tag in guild.Tags)
            {
                if (!tags.ContainsKey(tag.Category))
                {
                    tags.Add(tag.Category, new List <string>());
                }

                tags[tag.Category].Add(tag.Message);
            }

            EmbedBuilder builder = new EmbedBuilder();

            builder.Title = $"{guild.Name}'s Tags";
            foreach (var tag in tags)
            {
                builder.AddField(tag.Key, Join(",\n", tag.Value), true);
            }

            builder.Color = new Color(114, 137, 218);
            await ReplyAsync(null, false, builder.Build());
        }
        public void Momento_MarkCommentAsSpam_CorrectCommentIsMarkedAsSpamAndPersistedToDataStore()
        {
            IDocumentStore    documentStore = GetRavenDb();
            IDocumentDatabase database      = new RavenDb(documentStore);

            Momento momento     = new Momento();
            string  commentName = Guid.NewGuid().ToString();

            momento.AddComment(new Comment()
            {
                Author = commentName
            });

            database.Add(momento);
            database.Save();

            Momento momento2 = database.SingleOrDefault <Momento>(m => m.Id == momento.Id);
            Comment comment  = momento2.Comments.Where(c => c.Author == commentName).SingleOrDefault();

            momento.MarkCommentAsSpam(comment.Id);

            database.Add(momento);
            database.Save();

            Momento momento3 = database.SingleOrDefault <Momento>(m => m.Id == momento.Id);
            Comment comment2 = momento3.Comments.Where(c => c.Author == commentName).SingleOrDefault();

            Assert.AreEqual(CommentStatus.Spam, comment2.Status);
        }
        public void Momento_PeristRetrieveAddComment_TheCommentSeedIdIsMaintained()
        {
            IDocumentStore    documentStore = GetRavenDb();
            IDocumentDatabase database      = new RavenDb(documentStore);

            Momento momento     = new Momento();
            string  commentName = Guid.NewGuid().ToString();

            momento.AddComment(new Comment {
                Author = commentName
            });

            database.Add(momento);
            database.Save();

            Momento momento2 = database.SingleOrDefault <Momento>(m => m.Id == momento.Id);

            string  commentName2 = Guid.NewGuid().ToString();
            Comment comment1     = new Comment {
                Author = commentName2
            };

            momento2.AddComment(comment1);

            const int expectedAutoGeneratedId = 2;

            Assert.AreEqual(comment1.Id, expectedAutoGeneratedId);
        }
Exemple #5
0
        public async Task Kick([Remainder] SocketGuildUser user)
        {
            if (user.Hierarchy > Context.Guild.CurrentUser.Hierarchy)
            {
                await ReplyAsync("I cannot kick someone who has a higher role that me. Caw.");

                return;
            }

            RavenGuild guild = RavenDb.GetGuild(Context.Guild.Id);
            bool       sent  = false;

            if (guild.GuildSettings.CustomKickMessage != null)
            {
                if (guild.GuildSettings.CustomKickMessage.Enabled)
                {
                    await ReplyAsync(guild.GuildSettings.CustomKickMessage.Message);

                    sent = true;
                }
            }

            if (!sent)
            {
                await ReplyAsync($"Bye, {user.Nickname ?? user.Username}. You probably wont be missed.");
            }
            await user.KickAsync();
        }
Exemple #6
0
        /// <summary>Called when a change is made to a server. </summary>
        internal async Task GuildUpdateAsync(SocketGuild oldGuild, SocketGuild newGuild)
        {
            foreach (PluginInfo plugin in GlobalConfig.PluginInfo)
            {
                if (plugin.MessageReceivedAsync != null)
                {
                    if (GlobalConfig.RunPluginFunctionsAsynchronously)
                        #pragma warning disable 4014
                    {
                        plugin.GuildUpdate(oldGuild, newGuild);
                    }
                        #pragma warning restore 4014
                    else
                    {
                        await plugin.GuildUpdate(oldGuild, newGuild);
                    }
                }
            }

            RavenGuild guild = RavenDb.GetGuild(oldGuild.Id);

            // Compare changes
            if (oldGuild.Name != newGuild.Name)
            {
                guild.Name = newGuild.Name;
            }

            guild.TotalUsers = (uint)newGuild.Users.Count;
            guild.Save();
        }
Exemple #7
0
        /// <summary>Called when a user leaves the server (or is kicked). </summary>
        internal async Task GuildUserLeaveAsync(SocketGuildUser user)
        {
            foreach (PluginInfo plugin in GlobalConfig.PluginInfo)
            {
                if (plugin.MessageReceivedAsync != null)
                {
                    if (GlobalConfig.RunPluginFunctionsAsynchronously)
                        #pragma warning disable 4014
                    {
                        plugin.GuildUserLeave.Invoke(user);
                    }
                        #pragma warning restore 4014
                    else
                    {
                        await plugin.GuildUserLeave(user);
                    }
                }
            }

            // Get the guild this user is in
            RavenGuild guild = RavenDb.GetGuild(user.Guild.Id) ?? RavenDb.CreateNewGuild(user.Guild.Id, user.Guild.Name);

            // Update the total amount of users
            guild.TotalUsers = (uint)user.Guild.Users.Count;

            // Process goodbye message if one is set
            if (guild.GuildSettings.GoodbyeMessage.Enabled)
            {
                // If the targeted channel is null or no longer exists or the message itself is undefined
                if (guild.GuildSettings.GoodbyeMessage.ChannelId is null || user.Guild.GetTextChannel(guild.GuildSettings.GoodbyeMessage.ChannelId.GetValueOrDefault()) is null ||
                    string.IsNullOrWhiteSpace(guild.GuildSettings.GoodbyeMessage.Message))
                {
                    // If the logging channel is setup, exists, and is enabled
                    if (!(guild.LoggingSettings.ChannelId is null) && !(user.Guild.GetTextChannel(guild.LoggingSettings.ChannelId.GetValueOrDefault()) is null) &&
                        guild.LoggingSettings.Enabled)
                    {
                        // Log to the logging channel if it has been set
                        await user.Guild.GetTextChannel(guild.LoggingSettings.ChannelId.Value).SendMessageAsync(null, false, new EmbedBuilder()
                        {
                            Title       = "Warning!",
                            Color       = new Color(255, 128, 0), // Orange
                            Description = "Unable to send goodbye message. Channel or message are currently null. Please reconfigure it.",
                            Footer      = new EmbedFooterBuilder()
                            {
                                Text = $"{DateTime.UtcNow:ddd MMM d yyyy HH mm}"
                            }
                        }.Build());
                    }
                }

                else
                {
                    // Send the Goodbye message and repalce the server or user tags if they are present
                    await user.Guild.GetTextChannel(guild.GuildSettings.GoodbyeMessage.ChannelId.Value)
                    .SendMessageAsync(guild.GuildSettings.GoodbyeMessage.Message
                                      .Replace("%SERVER%", user.Guild.Name)
                                      .Replace("%USER%", user.Username));
                }
            }
Exemple #8
0
        public async Task ConfigAsync()
        {
            RavenGuild guild = RavenDb.GetGuild(Context.Guild.Id);

            guild.UserConfiguration[Context.User.Id] = MessageBox.BaseMenu;
            guild.Save();
            await ReplyAsync(ConfigHandler.GetCodeBlock(File.ReadAllText($"{Directory.GetCurrentDirectory()}/ConfigTextFiles/{MenuFiles.BaseMenu.ToString()}.txt")));
        }
Exemple #9
0
        public MeetingView Load(MeetingInputModel input)
        {
            using (var session = _documentStore.OpenSession())
            {
                var doc = session.Load <MeetingDocument>(RavenDb.GetId <MeetingDocument>(input.MeetingId));

                return(new MeetingView(doc.DocumentId, doc.Name, doc.WebCameraStreams));
            }
        }
Exemple #10
0
 public UserAccoutView Load(UserAccoutInputModel input)
 {
     using (var session = _documentStore.OpenSession())
     {
         var document = session.Load <UserDocument>(RavenDb.GetId <UserDocument>(input.UserId));
         return(new UserAccoutView
         {
             Email = document.Email,
             UserId = document.DocumentId,
             Nick = document.Nick,
         });
     }
 }
Exemple #11
0
        // Override the CheckPermissions method
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            // Check if this user is a Guild User, which is the only context where roles exist
            if (context.User is SocketGuildUser gUser)
            {
                RavenGuild guild = RavenDb.GetGuild(context.Guild.Id);
                return(Task.FromResult(guild.GuildSettings.BlacklistedModules.Any(x => string.Equals(x, command.Module.Name, StringComparison.CurrentCultureIgnoreCase))
                    ? PreconditionResult.FromError("This command is part of a module that has been banned/disallowed in this server.")
                    : PreconditionResult.FromSuccess()));
            }

            return(Task.FromResult(PreconditionResult.FromSuccess()));
        }
Exemple #12
0
        public void Handle(UserAssociatedWithIdentity @event)
        {
            using (var session = _documentStore.OpenSession())
            {
                var doc = session.Load <UserDocument>(RavenDb.GetId <UserDocument>(@event.AggregateId));
                doc.AccountAssociations.Add(new AccountAssociationDocument {
                    Identity = @event.Identity, Network = @event.Network
                });
                session.SaveChanges();

                _bus.PublishNotification(doc);
            }
        }
Exemple #13
0
        public async Task TagAsync(string name)
        {
            var      guild = RavenDb.GetGuild(Context.Guild.Id);
            RavenTag tag   = guild.Tags.Find(x => string.Equals(x.Tag, name, StringComparison.CurrentCultureIgnoreCase));

            if (tag is null)
            {
                await ReplyAsync("The specified tag couldn't be found.");

                return;
            }

            await ReplyAsync($"{tag.Tag} ({tag.Category}):\n{tag.Message}");
        }
Exemple #14
0
        public async Task GetProfileAsync([Remainder] string target)
        {
            RavenGuild guild = RavenDb.GetGuild(Context.Guild.Id);
            Regex      regex = new Regex(@"<@([0-9]*)>");
            Match      match = regex.Match(target);

            if (match.Success)
            {
                // See if what they gave was a real person
                ulong.TryParse(match.Groups[1].Value, out ulong id);
                if (id is 0)
                {
                    await ReplyAsync("Invalid User Mentioned.");

                    return;
                }

                RavenUser mentionedUser = guild.GetUser(id);
                if (mentionedUser is null)
                {
                    await ReplyAsync("The user specified doesn't exist within the system.");

                    return;
                }

                // Gotem.
                await ReplyAsync(null, false, DiscordEvents.GetUserProfile(id, guild));
            }

            else
            {
                RavenUser user = guild.Users.FirstOrDefault(x => x.Username.StartsWith(target));
                if (user is null)
                {
                    await ReplyAsync("Couldn't find anyone who's name was at all like that. To be fair, it's not a very indepth search.");

                    return;
                }

                await ReplyAsync(null, false, DiscordEvents.GetUserProfile(user.UserId, guild));
            }
        }
Exemple #15
0
        public void Setup()
        {
            RavenDb.InitializeStorage();

            ((RavenDbStorage)RavenDb.Storage).SessionSettings.SetStaleResultsWhait(StaleResultWhaitMode.AllNonStale);

            var repositoryFactory = Substitute.For <IRepositoryFactory>();

            repositoryFactory.CreateUserRepository().Returns(_ => _enableOutsideSession
                                                                      ? new UserRepositoryImpl(_outsideSession)
                                                                      : new UserRepositoryImpl(RavenDb.Storage));
            repositoryFactory.CreateRoleRepository().Returns(_ => _enableOutsideSession
                                                                      ? new RoleRepositoryImpl(_outsideSession)
                                                                      : new RoleRepositoryImpl(RavenDb.Storage));

            RepositoryFactory.Initialize(repositoryFactory);

            _roleProvider       = new RoleProvider();
            _membershipProvider = new MembershipProvider();
        }
Exemple #16
0
        public void Handle(CameraStreamCreated @event)
        {
            using (var session = _documentStore.OpenSession())
            {
                var doc = session.Load <MeetingDocument>(RavenDb.GetId <MeetingDocument>(@event.MeetingId));

                var stream = doc.WebCameraStreams.FirstOrDefault(cameraStream => cameraStream.OwnerUser == @event.OwnerUser);
                if (stream == null)
                {
                    doc.WebCameraStreams.Add(new WebCameraStream(@event.OwnerUser, @event.StreamSource));
                }
                else
                {
                    stream.StreamSource = @event.StreamSource;
                }

                session.SaveChanges();
                _bus.PublishNotification(doc);
            }
        }
        public void Momento_PeristRetrieveAddComment_TheCommentSeedIdIsMaintained()
        {
            IDocumentStore documentStore = GetRavenDb();
            IDocumentDatabase database = new RavenDb(documentStore);

            Momento momento = new Momento();
            string commentName = Guid.NewGuid().ToString();
            momento.AddComment(new Comment { Author = commentName });

            database.Add(momento);
            database.Save();

            Momento momento2 = database.SingleOrDefault<Momento>(m => m.Id == momento.Id);

            string commentName2 = Guid.NewGuid().ToString();
            Comment comment1 = new Comment {Author = commentName2};
            momento2.AddComment(comment1);

            const int expectedAutoGeneratedId = 2;

            Assert.AreEqual(comment1.Id, expectedAutoGeneratedId);
        }
        public void Momento_MarkCommentAsSpam_CorrectCommentIsMarkedAsSpamAndPersistedToDataStore()
        {
            IDocumentStore documentStore = GetRavenDb();
            IDocumentDatabase database = new RavenDb(documentStore);

            Momento momento = new Momento();
            string commentName = Guid.NewGuid().ToString();
            momento.AddComment(new Comment() { Author = commentName });

            database.Add(momento);
            database.Save();

            Momento momento2 = database.SingleOrDefault<Momento>(m => m.Id == momento.Id);
            Comment comment = momento2.Comments.Where(c => c.Author == commentName).SingleOrDefault();
            momento.MarkCommentAsSpam(comment.Id);

            database.Add(momento);
            database.Save();

            Momento momento3 = database.SingleOrDefault<Momento>(m => m.Id == momento.Id);
            Comment comment2 = momento3.Comments.Where(c => c.Author == commentName).SingleOrDefault();

            Assert.AreEqual(CommentStatus.Spam, comment2.Status);
        }
 public ListController()
 {
     _ravenDb = new RavenDb();
 }
Exemple #20
0
        internal async Task MessageReceivedAsync(SocketMessage s)
        {
            if (!(s is SocketUserMessage msg))
            {
                return;                                // If this is not a message (could be a TTS, Image, File, etc)
            }
            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return;                                           // Ignore messages from bot users, which includes the bot itself.
            }
            int argPos = 0;
            ShardedCommandContext context = new ShardedCommandContext(discord, msg);

            // If DM Channel, ignore all database based things.
            if (msg.Channel is IDMChannel || msg.Channel is IGroupChannel)
            {
                if (msg.HasStringPrefix(GlobalConfig.Prefix, ref argPos))
                {
                    var result = await commandService.ExecuteAsync(context, argPos, service);

                    if (!result.IsSuccess)     // If not successful, reply with the error.
                    {
                        await context.Channel.SendMessageAsync(result.ToString());
                    }
                    return;
                }
            }

            // Get the active database information for the current guild, or create it if it doesn't exist (for some reason)
            var guild = RavenDb.GetGuild(context.Guild.Id) ?? RavenDb.CreateNewGuild(context.Guild.Id, context.Guild.Name);

            if (!context.Guild.CurrentUser.GuildPermissions.Administrator && msg.HasStringPrefix(guild.GuildSettings.Prefix, ref argPos))
            {
                await context.Channel.SendMessageAsync("The bot is not currently set as an administrator." +
                                                       "Commands will be ignored until the bot is granted the Administrator permission.");

                return;
            }

            if (msg.Content.Contains("discord.gg/") && !((SocketGuildUser)context.User).GuildPermissions.ManageGuild &&
                guild.GuildSettings.AutoblockInviteLinks)
            {
                await msg.DeleteAsync();

                await context.Channel.SendMessageAsync("This server does not allow the posting of Discord server invites by non-moderators.");

                return;
            }

            // If the level settings are not disabled, we want to do our level processing.
            if (guild.GuildSettings.LevelConfig.LevelSettings != LevelSettings.Disabled)
            {
                // Get the global database entry for the user, or create it if it doesn't exist.
                var user = RavenDb.GetUser(context.User.Id) ?? RavenDb.CreateNewUser(context.User.Id,
                                                                                     context.User.Username, context.User.DiscriminatorValue);

                // Is the user ready for extra XP?
                if (user.XpLastUpdated.AddSeconds(RavenDb.GlobalLevelConfig.SecondsBetweenXpGiven) < DateTime.UtcNow)
                {
                    user.XpLastUpdated = DateTime.UtcNow;                                                                             // We are giving them XP so let's update the time stamp
                    user.Xp            = Convert.ToUInt64(new Random().Next(RavenDb.GlobalLevelConfig.MinXpGenerated,
                                                                            RavenDb.GlobalLevelConfig.MaxXpGenerated + 1)) + user.Xp; // Generate a value between our two clamps, a little RNG.
                    if (user.Xp > user.RequiredXp)                                                                                    // Are they ready for a level up?
                    {
                        user = PostLevelProcessing(user, out Embed embed);                                                            // Level them up
                        // Don't send the global message, maybe a setting in the future?
                    }
                    user.Save(); // Save the global user
                }

                // Are they allowing guild leveling?
                if (guild.GuildSettings.LevelConfig.LevelSettings == LevelSettings.GuildLeveling)
                {
                    // Get the user or create them if they don't exist.
                    RavenUser guildUser = guild.GetUser(context.User.Id) ?? guild.CreateNewUser(context.User.Id,
                                                                                                context.User.Username, context.User.DiscriminatorValue);

                    if (guildUser.UserId == 0)
                    {
                        // This is weird unintentional behaviour, but sometimes it happens
                        // Need to investigate further
                        await context.Channel.SendMessageAsync("Your user ID was 0 for some reason. Please try again.");

                        return;
                    }

                    // Check if they area ready for XP on a guild level
                    if (guildUser.XpLastUpdated.AddSeconds(guild.GuildSettings.LevelConfig.SecondsBetweenXpGiven) < DateTime.UtcNow)
                    {
                        guildUser.XpLastUpdated = DateTime.UtcNow;                                                                                        // They are so we update the timestamp
                        guildUser.Xp            = Convert.ToUInt64(new Random().Next(guild.GuildSettings.LevelConfig.MinXpGenerated,
                                                                                     guild.GuildSettings.LevelConfig.MaxXpGenerated + 1)) + guildUser.Xp; // Generate a value between our two clamps
                        if (guildUser.Xp > guildUser.RequiredXp)                                                                                          // If they are ready to level up
                        {
                            // Get the first role they are assigned that has a non-default colour
                            SocketRole role  = ((SocketGuildUser)msg.Author).Roles.FirstOrDefault(x => x.Color.ToString() != "#0");
                            Color?     color = role?.Color;                                     // Get the colour from the role, or null if we didn't find a colour.
                            guildUser = PostLevelProcessing(guildUser, out Embed embed, color); // Pass it in to get the result
                            await context.Channel.SendMessageAsync("", false, embed);           // Post it
                        }

                        int index = guild.Users.FindIndex(x => x.UserId == context.User.Id);
                        if (index != -1)                    // I don't think this should ever happend, but better safe than sorry
                        {
                            guild.Users[index] = guildUser; // Update it
                        }
                        guild.Save();                       // Save the db entry
                    }
                }
            }

            // If the mention the bot directly, tell them the prefix. If they type just the word prefix, tell them.
            if ((msg.MentionedUsers.All(x => discord.Shards.Any(y => y.CurrentUser.Id == x.Id)) && msg.MentionedUsers.Count > 0) || msg.Content == "prefix")
            {
                await context.Channel.SendMessageAsync("This guild's prefix is: " + guild.GuildSettings.Prefix);

                return;
            }

            // Ignore string prefixes if the person was currently in a menu
            else if (msg.HasStringPrefix(guild.GuildSettings.Prefix, ref argPos))
            {
                if (!guild.UserConfiguration.ContainsKey(context.User.Id))
                {
                    var result = await commandService.ExecuteAsync(context, argPos, service);

                    if (!result.IsSuccess)
                    {
                        await context.Channel.SendMessageAsync(result.ToString());
                    }
                    return;
                }

                else
                {
                    await context.Channel.SendMessageAsync("You are currently in a menu. Respond to it or type 'exit' to leave it.");
                }
            }

            // Are they currently in a menu
            if (guild.UserConfiguration.ContainsKey(context.User.Id))
            {
                string[] args = msg.Content.Split(' ');
                // They want off this wild ride
                if (msg.Content == "exit" || msg.Content.StartsWith("exit"))
                {
                    guild.UserConfiguration.Remove(context.User.Id);               // Remove their menu entry
                    guild.Save();                                                  // Save
                    await context.Channel.SendMessageAsync("Exited out of menu."); // Goodbye user

                    return;
                }

                else if (msg.Content == "back" || msg.Content.StartsWith("back"))
                {
                    switch (guild.UserConfiguration[context.User.Id])
                    {
                    case MessageBox.BaseMenu:
                        guild.UserConfiguration.Remove(context.User.Id);               // Remove their menu entry
                        guild.Save();                                                  // Save
                        await context.Channel.SendMessageAsync("Exited out of menu."); // Goodbye user

                        return;

                    case MessageBox.LsSettingSubmenu:
                        guild.UserConfiguration[context.User.Id] = MessageBox.LevelSettings;
                        break;

                    // By default we assume they are one menu deep
                    default:
                        guild.UserConfiguration[context.User.Id] = MessageBox.BaseMenu;
                        break;
                    }
                    guild.Save();
                    await ConfigHandler.SelectSubMenu(guild, context.User.Id, context.Guild.GetTextChannel(context.Channel.Id), guild.UserConfiguration[context.User.Id]);

                    return;
                }

                // Otherwise we see if they specified a valid option
                else if (int.TryParse(args[0], out int option))
                {
                    // Handle it a bit differently if it's a different route
                    if (guild.UserConfiguration[context.User.Id] is MessageBox.BaseMenu)
                    {
                        // Normally we wouldn't use IsDefined due to it's lack of scalability,
                        // But for the root menu it actually scales rather well. Just need to watch out for the 2000 character limit.
                        if (Enum.IsDefined(typeof(MessageBox), option))
                        {
                            // Literally makes no difference in preformance, just trying to keep this file clean.
                            // Using this method, they can technically, if they know the submenu values,
                            // skip the parent menus and go straight to the sub menus. I don't really see this as an issue, to be honest.
                            await ConfigHandler.SelectSubMenu(guild, context.User.Id, context.Guild.GetTextChannel(context.Channel.Id), (MessageBox)option);

                            return;
                        }

                        else // They didn't so lets give them another chance
                        {
                            await context.Channel.SendMessageAsync("The option you specified doesn't exist. The option should be"
                                                                   + " just the number of the option you are trying to pick. Try again.");

                            return;
                        }
                    }

                    else
                    {
                        await ConfigHandler.SelectOption(guild, context.User.Id, context.Guild.GetTextChannel(context.Channel.Id), args);
                    }
                }
            }
        }
Exemple #21
0
        /// <summary>Called when a user joins the server. </summary>
        internal async Task GuildUserJoinAsync(SocketGuildUser user)
        {
            foreach (PluginInfo plugin in GlobalConfig.PluginInfo)
            {
                if (plugin.MessageReceivedAsync != null)
                {
                    if (GlobalConfig.RunPluginFunctionsAsynchronously)
                        #pragma warning disable 4014
                    {
                        plugin.GuildUserLeave.Invoke(user);
                    }
                        #pragma warning restore 4014
                    else
                    {
                        await plugin.GuildUserLeave(user);
                    }
                }
            }

            // Add it to the global database if they don't exist
            if (RavenDb.GetUser(user.Id) is null)
            {
                RavenDb.CreateNewUser(user.Id, user.Username, user.DiscriminatorValue, user.GetAvatarUrl() ?? user.GetDefaultAvatarUrl());
            }

            // Get the guild this user is in
            RavenGuild guild = RavenDb.GetGuild(user.Guild.Id) ?? RavenDb.CreateNewGuild(user.Guild.Id, user.Guild.Name);

            // Update the total amount of users
            guild.TotalUsers = (uint)user.Guild.Users.Count;

            // If they rejoined, we'll store their old name to log
            bool   rejoined = false;
            string username = string.Empty;

            // Get the user from that guild
            RavenUser guildUser = guild.GetUser(user.Id);
            if (guildUser is null) // if they don't exist, we'll need to create them
            {
                guild.CreateNewUser(user.Id, user.Username, user.DiscriminatorValue, user.GetAvatarUrl() ?? user.GetDefaultAvatarUrl());
            }

            else
            {
                // They rejoined, update their name in case/discrim in case it changed
                rejoined                = true;
                username                = guildUser.Username + "#" + guildUser.Discriminator;
                guildUser.Username      = user.Username;
                guildUser.Discriminator = user.DiscriminatorValue;
                guild.Save(); // Save the updated information, while storing the old one for logging purposes
            }

            // Process welcome message if one is set
            if (guild.GuildSettings.WelcomeMessage.Enabled)
            {
                // If the targeted channel is null or no longer exists or the message itself is undefined
                if (guild.GuildSettings.WelcomeMessage.ChannelId is null || user.Guild.GetTextChannel(guild.GuildSettings.WelcomeMessage.ChannelId.GetValueOrDefault()) is null ||
                    string.IsNullOrWhiteSpace(guild.GuildSettings.WelcomeMessage.Message))
                {
                    // If the logging channel is setup, exists, and is enabled
                    if (!(guild.LoggingSettings.ChannelId is null) && !(user.Guild.GetTextChannel(guild.LoggingSettings.ChannelId.GetValueOrDefault()) is null) &&
                        guild.LoggingSettings.Enabled)
                    {
                        // Log to the logging channel if it has been set
                        await user.Guild.GetTextChannel(guild.LoggingSettings.ChannelId.Value).SendMessageAsync(null, false, new EmbedBuilder()
                        {
                            Title       = "Warning!",
                            Color       = new Color(255, 128, 0), // Orange
                            Description = "Unable to send welcome message. Channel or message are currently null. Please reconfigure it.",
                            Footer      = new EmbedFooterBuilder()
                            {
                                Text = $"{DateTime.UtcNow:ddd MMM d yyyy HH mm}"
                            }
                        }.Build());
                    }
                }

                else
                {
                    // Send the welcome message and repalce the server or user tags if they are present
                    await user.Guild.GetTextChannel(guild.GuildSettings.WelcomeMessage.ChannelId.Value)
                    .SendMessageAsync(guild.GuildSettings.WelcomeMessage.Message
                                      .Replace("%SERVER%", user.Guild.Name)
                                      .Replace("%USER%", user.Username));
                }
            }
Exemple #22
0
 public async Task GetOwnProfileAsync() => await ReplyAsync(null, false, DiscordEvents.GetUserProfile(Context.User.Id, RavenDb.GetGuild(Context.Guild.Id)));
Exemple #23
0
        internal async Task MessageReceivedAsync(SocketMessage s)
        {
            foreach (PluginInfo plugin in GlobalConfig.PluginInfo)
            {
                if (plugin.MessageReceivedAsync != null)
                {
                    if (GlobalConfig.RunPluginFunctionsAsynchronously)
                        #pragma warning disable 4014
                    {
                        plugin.MessageReceivedAsync.Invoke(s);
                    }
                        #pragma warning restore 4014
                    else
                    {
                        await plugin.MessageReceivedAsync(s);
                    }
                }
            }

            if (!(s is SocketUserMessage msg))
            {
                return;                                // If this is not a message (could be a TTS, Image, File, etc)
            }
            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return;                                           // Ignore messages from bot users, which includes the bot itself.
            }
            int argPos = 0;
            ShardedCommandContext context = new ShardedCommandContext(discord, msg);

            // If DM Channel, ignore all database based things.
            if (msg.Channel is IDMChannel || msg.Channel is IGroupChannel)
            {
                if (msg.HasStringPrefix(GlobalConfig.Prefix, ref argPos))
                {
                    var result = await commandService.ExecuteAsync(context, argPos, service);

                    if (!result.IsSuccess)     // If not successful, reply with the error.
                    {
                        await context.Channel.SendMessageAsync(result.ToString());
                    }
                    return;
                }
            }

            // Get the active database information for the current guild, or create it if it doesn't exist (for some reason)
            var guild = RavenDb.GetGuild(context.Guild.Id) ?? RavenDb.CreateNewGuild(context.Guild.Id, context.Guild.Name);
            guild.TotalMessages++;
            if (msg.Attachments.Count > 0)
            {
                foreach (var x in msg.Attachments)
                {
                    if (x.Height != null)
                    {
                        guild.TotalImages++;
                    }
                }
            }
            guild.Save();

            if (!context.Guild.CurrentUser.GuildPermissions.Administrator && msg.HasStringPrefix(guild.GuildSettings.Prefix, ref argPos))
            {
                await context.Channel.SendMessageAsync("The bot is not currently set as an administrator." +
                                                       "Commands will be ignored until the bot is granted the Administrator permission.");

                return;
            }

            if (msg.Content.Contains("discord.gg/") && !((SocketGuildUser)context.User).GuildPermissions.ManageGuild &&
                guild.GuildSettings.AutoblockInviteLinks)
            {
                await msg.DeleteAsync();

                await context.Channel.SendMessageAsync("This server does not allow the posting of Discord server invites by non-moderators.");

                return;
            }

            // If the level settings are not disabled, we want to do our level processing.
            if (guild.GuildSettings.LevelConfig.LevelSettings != LevelSettings.Disabled)
            {
                // Get the global database entry for the user, or create it if it doesn't exist.
                var user = RavenDb.GetUser(context.User.Id) ?? RavenDb.CreateNewUser(context.User.Id,
                                                                                     context.User.Username, context.User.DiscriminatorValue, context.User.GetAvatarUrl() ?? context.User.GetDefaultAvatarUrl());

                // Is the user ready for extra XP?
                if (user.XpLastUpdated.AddSeconds(RavenDb.GlobalLevelConfig.SecondsBetweenXpGiven) < DateTime.UtcNow)
                {
                    user.XpLastUpdated = DateTime.UtcNow;                                                                             // We are giving them XP so let's update the time stamp
                    user.Xp            = Convert.ToUInt64(new Random().Next(RavenDb.GlobalLevelConfig.MinXpGenerated,
                                                                            RavenDb.GlobalLevelConfig.MaxXpGenerated + 1)) + user.Xp; // Generate a value between our two clamps, a little RNG.
                    if (user.Xp > user.RequiredXp)                                                                                    // Are they ready for a level up?
                    {
                        user = PostLevelProcessing(user, out Embed embed);                                                            // Level them up
                        // Don't send the global message, maybe a setting in the future?
                    }
                    user.Save(); // Save the global user
                }

                // Are they allowing guild leveling?
                if (guild.GuildSettings.LevelConfig.LevelSettings == LevelSettings.GuildLeveling)
                {
                    // Get the user or create them if they don't exist.
                    RavenUser guildUser = guild.GetUser(context.User.Id) ?? guild.CreateNewUser(context.User.Id,
                                                                                                context.User.Username, context.User.DiscriminatorValue, context.User.GetAvatarUrl() ?? context.User.GetDefaultAvatarUrl());

                    if (guildUser.UserId == 0)
                    {
                        // This is weird unintentional behaviour, but sometimes it happens
                        // Need to investigate further
                        await context.Channel.SendMessageAsync("Your user ID was 0 for some reason. Please try again.");

                        return;
                    }

                    // Check if they area ready for XP on a guild level
                    if (guildUser.XpLastUpdated.AddSeconds(guild.GuildSettings.LevelConfig.SecondsBetweenXpGiven) < DateTime.UtcNow)
                    {
                        guildUser.XpLastUpdated = DateTime.UtcNow;                                                                                        // They are so we update the timestamp
                        guildUser.Xp            = Convert.ToUInt64(new Random().Next(guild.GuildSettings.LevelConfig.MinXpGenerated,
                                                                                     guild.GuildSettings.LevelConfig.MaxXpGenerated + 1)) + guildUser.Xp; // Generate a value between our two clamps
                        if (guildUser.Xp >= guildUser.RequiredXp)                                                                                         // If they are ready to level up
                        {
                            // Get the first role they are assigned that has a non-default colour
                            SocketRole role  = ((SocketGuildUser)msg.Author).Roles.FirstOrDefault(x => x.Color.ToString() != "#0");
                            Color?     color = role?.Color;                                            // Get the colour from the role, or null if we didn't find a colour.
                            guildUser = PostLevelProcessing(guildUser, out Embed embed, color, guild); // Pass it in to get the result
                            await context.Channel.SendMessageAsync("", false, embed);                  // Post it
                        }

                        int index = guild.Users.FindIndex(x => x.UserId == context.User.Id);
                        if (index != -1)                    // I don't think this should ever happend, but better safe than sorry
                        {
                            guild.Users[index] = guildUser; // Update it
                        }
                        guild.Save();                       // Save the db entry
                    }
                }
            }

            // If the mention the bot directly, tell them the prefix. If they type just the word prefix, tell them.
            if ((msg.MentionedUsers.All(x => discord.Shards.Any(y => y.CurrentUser.Id == x.Id)) &&
                 MentionUtils.TryParseUser(msg.Content, out ulong a)) || msg.Content.ToLower() == "prefix")
            {
                await context.Channel.SendMessageAsync("This guild's prefix is: " + guild.GuildSettings.Prefix);

                return;
            }