Example #1
0
        public async Task Command()
        {
            List <User> top50 = (await DatabaseQueries.GetLimitAsync <User>(50, x => x.Experience > 0,
                                                                            x => x.Experience, true)).Where(x => !x.IsBlacklisted).ToList();

            int i = 1;

            var embed = new KaguyaEmbedBuilder
            {
                Fields = new List <EmbedFieldBuilder>()
            };

            foreach (User user in top50)
            {
                if (i > 10)
                {
                    break;
                }

                SocketUser socketUser = Client.GetUser(user.UserId);

                embed.Fields.Add(new EmbedFieldBuilder
                {
                    IsInline = false,
                    Name     = $"{i}. {socketUser?.ToString().Split('#').First() ?? $"[Unknown User: {user.UserId}]"}",
                    Value    = $"Level: {user.GlobalLevel():N0} ({user.PercentToNextLevel() * 100:N0}% {Centvrio.Emoji.Arrow.Right}" +
                               $" Lvl {user.GlobalLevel() + 1:N0}) " +
                               $"- Exp: {user.Experience:N0}"
                });

                i++;
            }

            await SendEmbedAsync(embed);
        }
Example #2
0
        public async Task Command(SocketGuildUser user, [Remainder] string reason = null)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            IRole role = Context.Guild.Roles.FirstOrDefault(x => x.Name == SB_ROLE);

            if (role == null)
            {
                await SendBasicErrorEmbedAsync($"The role `{SB_ROLE}` does not exist, therefore there are no active shadowbans.");

                return;
            }

            if (!user.Roles.Contains(role))
            {
                await SendBasicErrorEmbedAsync($"{user.Mention} is not shadowbanned.");

                return;
            }

            reason ??= "<No reason provided>";

            await user.RemoveRoleAsync(role);

            await ReplyAsync($"{Context.User.Mention} Successfully unshadowbanned `{user}`.");

            KaguyaEvents.TriggerUnshadowban(new ModeratorEventArgs(server, Context.Guild, user, (SocketGuildUser)Context.User, reason, null));
        }
Example #3
0
        public async Task SetPrefix(string prefix)
        {
            var embed = new KaguyaEmbedBuilder();

            if (prefix.Length > 5)
            {
                await ConsoleLogger.LogAsync("Command prefix was too long. Not set.", DataStorage.JsonStorage.LogLvl.DEBUG);

                embed.WithDescription("Your command prefix may not be longer than 5 characters.");
                embed.SetColor(EmbedColor.RED);
                await ReplyAsync(embed : embed.Build());

                return;
            }

            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            server.CommandPrefix = prefix;
            await DatabaseQueries.UpdateAsync(server);

            embed.WithDescription($"Command prefix has been changed to `{prefix}`.");
            embed.WithFooter($"Use this command again without specifying a prefix to reset it.");
            embed.SetColor(EmbedColor.VIOLET);

            await ReplyAsync(embed : embed.Build());
        }
Example #4
0
        public async Task OsuSetCommand([Remainder] string username)
        {
            KaguyaEmbedBuilder embed;
            User playerObject = username.AsUlong(false) == 0
                ? await OsuBase.Client.GetUserByUsernameAsync(username, GameMode.Standard)
                : await OsuBase.Client.GetUserByUserIdAsync((long)username.AsUlong(), GameMode.Standard);

            if (playerObject == null)
            {
                await SendBasicErrorEmbedAsync($"The username you provided doesn't match an existing osu! player.");

                return;
            }

            //Getting user profile database object and updating it.
            DataStorage.DbData.Models.User user = await DatabaseQueries.GetOrCreateUserAsync(Context.User.Id);

            user.OsuId = (int)playerObject.UserId;
            await DatabaseQueries.UpdateAsync(user);

            embed = new KaguyaEmbedBuilder
            {
                Title       = "osu! Username",
                Description = $"Your osu! username has been set to `{playerObject.Username}`."
            };

            await ReplyAsync(embed : embed.Build());
        }
Example #5
0
 private void GetData()
 {
     FailedTrials      = DatabaseQueries.GetPlaybookReport("Failed Trials", (DateTime)FirstMonth, (DateTime)LastMonth);
     ImportantProjects = DatabaseQueries.GetPlaybookReport("Important Projects", (DateTime)FirstMonth, (DateTime)LastMonth);
     ScheduledTrials   = DatabaseQueries.GetPlaybookReport("Scheduled Trials", (DateTime)FirstMonth, (DateTime)LastMonth);
     NewSales          = DatabaseQueries.GetPlaybookReport("New Sales", (DateTime)FirstMonth, (DateTime)LastMonth);
 }
Example #6
0
 public string AddPrice([Bind(Include = "PriceControllerId,ShwarmaId,Price,SellingPointId,Comment")] PriceController priceController)
 {
     return(DatabaseQueries.AddPrice(Request.Form["SellingPointTitle"], Request.Form["ShawarmaName"],
                                     priceController.Price, priceController.Comment)
         ? "Success"
         : "Error");
 }
Example #7
0
 public string AddIngredient([Bind(Include = "IngradientName,TotalWeight")] Ingradient ingradient)
 {
     return(DatabaseQueries.AddIngredient(ingradient.IngradientName, ingradient.TotalWeight,
                                          Request.Form["CategoryName"])
         ? "Success"
         : "Error");
 }
Example #8
0
        public async Task Command(int trackNum)
        {
            User user = await DatabaseQueries.GetOrCreateUserAsync(Context.User.Id);

            List <FavoriteTrack> userFavorites = await DatabaseQueries.GetAllForUserAsync <FavoriteTrack>(user.UserId);

            if (!userFavorites.Any())
            {
                await SendBasicErrorEmbedAsync("You have not favorited any tracks. Use the `h favorite` and " +
                                               "`h favls` commands for more information on how to use this system.");

                return;
            }

            int           trackIndex = trackNum - 1;
            FavoriteTrack trackMatch;

            try
            {
                trackMatch = userFavorites[trackIndex];
            }
            catch (Exception)
            {
                await SendBasicErrorEmbedAsync($"The track number you provided doesn't match a track in " +
                                               $"your playlist.");

                return;
            }

            var s = new Search();
            await s.SearchAndPlayAsync(Context, trackMatch.TrackId, true);
        }
Example #9
0
        public string LoadSourceData(SourceData sourceData)
        {
            string result = string.Empty;

            try
            {
                DatabaseQueries queries = Queries.GetQueries();

                var records = sourceData.Records;

                //Load Master data
                foreach (var subquery in queries.MasterInfo.SqlQuery)
                {
                    if (!string.IsNullOrWhiteSpace(subquery.TableName) && !string.IsNullOrWhiteSpace(subquery.Query))
                    {
                        var sql = ReplaceStrings(subquery.Query, null);
                        var dt  = db.ExecuteSelectCommandMultipleResultDataSet(sql, subquery.TableName).Tables[0];
                        sourceData.SourceMastInfo.Tables.Add(dt.Copy());
                    }
                }

                // Load Records Data
                foreach (Record record in records)
                {
                    result        = GetRecordsRmsData(queries, record);
                    record.Source = result;
                }
            }
            catch (Exception ex)
            {
                ExceptionDispatchInfo.Capture(ex).Throw();
            }

            return(result);
        }
Example #10
0
        private static async Task _client_MessageDeleted(Cacheable <IMessage, ulong> arg1, ISocketMessageChannel arg2)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(((SocketGuildChannel)arg2).Guild.Id);

            if (server.LogDeletedMessages == 0)
            {
                return;
            }

            if (server.IsCurrentlyPurgingMessages)
            {
                return;
            }

            IMessage message = arg1.Value;

            if (message is null || message.Author.IsBot)
            {
                return;
            }

            string content = string.IsNullOrEmpty(message.Content)
                ? "<Message contained no text>"
                : $"{message.Content}";

            var sb = new StringBuilder($"🗑️ `[{GetFormattedTimestamp()}]` `ID: {message.Author.Id}` ");

            sb.Append($"Message deleted. Author: **{message.Author}**. Channel: **{((SocketTextChannel) message.Channel).Mention}**.");

            // Premium servers get more content in the log.
            if (server.IsPremium)
            {
                sb.Append($"\nContent: \"**{content}**\"");

                if (message.Attachments.Count > 0)
                {
                    sb.Append($" Attachments: **{message.Attachments.Count}**.");
                    foreach (IAttachment a in message.Attachments)
                    {
                        sb.Append($" URL: **<{a.ProxyUrl}>**");
                    }
                }
            }

            string msg = sb.ToString();

            try
            {
                await _client.GetGuild(server.ServerId).GetTextChannel(server.LogDeletedMessages).SendMessageAsync(msg);
            }
            catch (Exception)
            {
                await ConsoleLogger.LogAsync($"Failed to send message deleted log to channel {server.LogDeletedMessages} " +
                                             $"in guild {server.ServerId}. Resetting this log channel to 0 so it " +
                                             "doesn't happen again!", LogLvl.WARN);

                server.LogDeletedMessages = 0;
                await DatabaseQueries.UpdateAsync(server);
            }
        }
        private static MapLocation SearchGoogleMaps(int cragId, string cragName, CragLocationContext context)
        {
            var queries            = new DatabaseQueries(context);
            var searchableCragName = SearchableString(cragName);

            var request = WebRequest.Create(
                $"https://maps.googleapis.com/maps/api/place/textsearch/json?query={searchableCragName}&key={GoogleApikey}");

            request.Method = "GET";

            var response = request.GetResponse();

            var content = string.Empty;

            using (var stream = response.GetResponseStream())
            {
                using (var streamReader = new StreamReader(stream))
                {
                    content = streamReader.ReadToEnd();
                }
            }

            var result = JsonConvert.DeserializeObject <RootObject>(content);

            var location = result.results[0].geometry.location;

            queries.AddCragToDatabase(cragId, cragName, (decimal)location.lat, (decimal)location.lng, true);

            return(new MapLocation((decimal)location.lat, (decimal)location.lng));
        }
Example #12
0
        private static async Task _client_UserUnbanned(SocketUser arg1, SocketGuild arg2)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(arg2.Id);

            if (server.LogUnbans == 0)
            {
                return;
            }

            string msg = $"♻ `[{GetFormattedTimestamp()}]` `ID: {arg1.Id}` **{arg1}** has been unbanned.";

            try
            {
                await arg2.GetTextChannel(server.LogUnbans).SendMessageAsync(msg);
            }
            catch (Exception)
            {
                await ConsoleLogger.LogAsync($"Failed to send unban log to channel {server.LogUnbans} " +
                                             $"in guild {server.ServerId}. Resetting this log channel to 0 so it " +
                                             "doesn't happen again!", LogLvl.WARN);

                server.LogUnbans = 0;
                await DatabaseQueries.UpdateAsync(server);
            }
        }
Example #13
0
        private static async Task _client_UserLeft(SocketGuildUser arg)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(arg.Guild.Id);

            if (server.LogUserLeaves == 0)
            {
                return;
            }

            const string X_CROSS = "<:RedCross:776513248312295484>";
            string       msg     = $"{X_CROSS} `[{GetFormattedTimestamp()}]` `ID: {arg.Id}` **{arg}** left the server or was kicked. " +
                                   $"Member Count: **{arg.Guild.MemberCount:N0}**";

            try
            {
                await _client.GetGuild(server.ServerId).GetTextChannel(server.LogUserLeaves).SendMessageAsync(msg);
            }
            catch (Exception)
            {
                await ConsoleLogger.LogAsync($"Failed to send user leave log to channel {server.LogUserLeaves} " +
                                             $"in guild {server.ServerId}. Resetting this log channel to 0 so it " +
                                             "doesn't happen again!", LogLvl.WARN);

                server.LogUserLeaves = 0;
                await DatabaseQueries.UpdateAsync(server);
            }
        }
Example #14
0
        private static async Task _client_UserJoined(SocketGuildUser arg)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(arg.Guild.Id);

            if (server.LogUserJoins == 0)
            {
                return;
            }

            string msg = $"✅ `[{GetFormattedTimestamp()}]` `ID: {arg.Id}` **{arg}** joined the server. Member Count: **{arg.Guild.MemberCount:N0}**";

            try
            {
                await _client.GetGuild(server.ServerId).GetTextChannel(server.LogUserJoins).SendMessageAsync(msg);
            }
            catch (Exception)
            {
                await ConsoleLogger.LogAsync($"Failed to send user join log to channel {server.LogUserJoins} " +
                                             $"in guild {server.ServerId}. Resetting this log channel to 0 so it " +
                                             "doesn't happen again!", LogLvl.WARN);

                server.LogUserJoins = 0;
                await DatabaseQueries.UpdateAsync(server);
            }
        }
Example #15
0
        //private IProgressReporterService ProgressReporter
        //{
        //    get
        //    {
        //        return (IProgressReporterService)GetService(typeof(IProgressReporterService));
        //    }
        //}

        //public ILoggingService LoggingService
        //{
        //    get
        //    {
        //        return (ILoggingService)GetService(typeof(ILoggingService));
        //    }
        //}
        #endregion

        #region Constructors
        public dloDataApplication()
        {
            //Create a new instance of our service container
            ServiceContainer = new System.ComponentModel.Design.ServiceContainer();

            IsLoaded = false;

            //  AuthTypes = RuntimeAuthTypes.None;

            SyncStatus = Data.SyncStatus.Unknown;

            DbInfo = new dloDbInfo(this);

            Configuration = new Configuration();

            _users   = new dloUsers(this);
            _groups  = new dloUserGroups(this);
            _devices = new dloDevices(this);

            Queries = new DatabaseQueries();
            //CurrentUser = new dloUser(_users);

            //_currentDevice = new dloDevice(this);

            //DoHouseKeeping();

            //Register services
        }
Example #16
0
        private void OnCreate(object sender, EventArgs e)
        {
            if (cbLogins.SelectedIndex == -1)
            {
                MessageBox.Show("You must select a login name.", "Create User Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (String.IsNullOrWhiteSpace(tbUser.Text))
            {
                MessageBox.Show("You must specify a user name.", "Create User Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                DatabaseQueries.CreateUser(LoginInformation.Server, CurrentDatabase, LoginInformation.User, LoginInformation.Password, tbUser.Text, ((Login)cbLogins.SelectedItem).Name);

                foreach (var item in clbRoles.CheckedItems)
                {
                    DatabaseQueries.GrantRole(LoginInformation.Server, CurrentDatabase, LoginInformation.User, LoginInformation.Password, tbUser.Text, (string)item);
                }

                UserName          = tbUser.Text;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Create User Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #17
0
        public async Task Command(params string[] args)
        {
            User user = await DatabaseQueries.GetOrCreateUserAsync(Context.User.Id);

            long   fishId   = 0;
            string fishType = null;

            if (args.Length == 0 || args.Length > 3)
            {
                await SendBasicErrorEmbedAsync($"Please specify either a fish ID or a " +
                                               $"type of fish you want to sell.");

                return;
            }

            if (long.TryParse(args[0], out long id))
            {
                fishId = id;
            }
            else
            {
                switch (args.Length)
                {
                case 3:
                    fishType = $"{args[0].ToUpper()}_{args[1].ToUpper()}_{args[2].ToUpper()}";

                    break;

                case 2:
                    fishType = $"{args[0].ToUpper()}_{args[1].ToUpper()}";

                    break;

                case 1 when args[0].ToLower() == "all":
Example #18
0
        public async Task Command()
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            LavaNode   node   = ConfigProperties.LavaNode;
            LavaPlayer player = node.GetPlayer(Context.Guild);

            if (player == null)
            {
                await SendBasicErrorEmbedAsync($"There needs to be an active music player in the " +
                                               $"server for this command to work. Start one " +
                                               $"by using `{server.CommandPrefix}play <song>`!");

                return;
            }

            if (player.PlayerState == PlayerState.Playing)
            {
                await player.PauseAsync();
                await SendBasicSuccessEmbedAsync($"Successfully paused the player.");
            }
            else
            {
                await SendBasicErrorEmbedAsync($"There is no song currently playing, therefore I have nothing to pause. If " +
                                               $"you have previously used the `{server.CommandPrefix}pause` command, " +
                                               $"use the `{server.CommandPrefix}resume` command to resume the player.");
            }
        }
Example #19
0
 public string AddSellingPoint([Bind(Include = "Address,ShawarmaTitle")] SellingPoint sellingPoint)
 {
     return(DatabaseQueries.AddSellingPoint(sellingPoint.ShawarmaTitle, sellingPoint.Address,
                                            Request.Form["SellingPointCategory"])
         ? "Success"
         : "Error");
 }
Example #20
0
        public async Task Command()
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            string logSettingString = "";

            foreach (PropertyInfo prop in server.GetType().GetProperties()
                     .Where(x => x.PropertyType == typeof(ulong) && x.Name.Contains("Log")))
            {
                string   n        = prop.Name.ToLower();
                string[] premLogs = { "warn", "unwarn", "mute", "unmute", "shadowban", "unshadowban" };

                if (!server.IsPremium && premLogs.Any(x => n.Contains(x)))
                {
                    continue;
                }

                ulong matchChannel = (ulong)prop.GetValue(server);

                SocketTextChannel channel = Client.GetGuild(Context.Guild.Id).GetTextChannel(matchChannel);
                bool deletedChannel       = channel == null && matchChannel != 0;

                // wtf is this shit...
                // todo: Add 'Kaguya Premium Only' tags to warn, unwarn, shadowban, unshadowban, mute, and unmute logs.
                logSettingString +=
                    $"**{(prop.Name == "ModLog" ? "ModLog (Kaguya Premium Only)" : prop.Name.Replace("Log", ""))}** - {(channel == null && !deletedChannel ? "`Not assigned.`" : " ")} " +
                    $"{(deletedChannel ? $"*`Deleted Channel`*" : $"{(channel == null ? null : $"`#{channel.Name}`")}")}\n";
            }
Example #21
0
 public string AddRecipeShawarma([Bind(Include = "ShawarmaName,CookingTime")] Shawarma shawarma)
 {
     return(DatabaseQueries.AddRecipe(shawarma.ShawarmaName,
                                      (Session["ShawarmaRecipes"] as IEnumerable <IngradientWeight>)?.ToArray(), shawarma.CookingTime)
         ? "Success"
         : "Error");
 }
Example #22
0
        /// <summary>
        /// Returns a <see cref="Tuple"/> containing two integers. The first integer is the user's Xp Rank
        /// out of all users in the database. The second is how many total users there are in the database.
        /// </summary>
        /// <param name="user">The user of whom we are finding the Xp rank of.</param>
        /// <returns></returns>
        public static async Task <(int, int)> GetGlobalXpRankAsync(this User user)
        {
            List <User> allExp = (await DatabaseQueries.GetAllAsync <User>()).OrderByDescending(x => x.Experience).ToList();
            int         rank   = allExp.IndexOf(allExp.First(x => x.UserId == user.UserId)) + 1;

            return(rank, allExp.Count);
        }
Example #23
0
        public async Task Command()
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            IEnumerable <Quote> quotes = server.Quotes;
            int quoteCount             = quotes.Count();

            if (quoteCount == 0)
            {
                await SendBasicErrorEmbedAsync($"This server's quote collection is empty.\nCreate some with `{server.CommandPrefix}addquote`.");

                return;
            }

            if (quoteCount <= 5)
            {
                var embed = new KaguyaEmbedBuilder
                {
                    Title = $"Quotes for {Context.Guild}"
                };

                foreach (Quote quote in quotes)
                {
                    embed.AddField($"Quote #{quote.Id}", QuoteString(quote));
                }

                await SendEmbedAsync(embed);

                return;
            }

            DateTime n = DateTime.Now;

            using (var s = new MemoryStream())
            {
                var sw = new StreamWriter(s);
                await sw.WriteLineAsync($"### Quotes for: {Context.Guild.Name} ###");

                foreach (Quote quote in quotes)
                {
                    await sw.WriteLineAsync(QuoteString(quote, true));
                }

                await sw.FlushAsync();

                s.Seek(0, SeekOrigin.Begin);

                try
                {
                    await Context.User.SendFileAsync(s,
                                                     $"Quotes_{Context.Guild.Name}-{n.Day}-{n.Month}-{n.Year}--{n.Hour:00}-{n.Minute:00}-{n.Second:00}.txt");
                }
                catch (Exception)
                {
                    throw new KaguyaSupportException("Failed to DM you the quotes. Do you allow DMs from me/bots?");
                }
            }

            await SendBasicSuccessEmbedAsync("All quotes have been sent to your DM.");
        }
Example #24
0
        public static int ServerExp(this User user, Server server)
        {
            if (server.ServerExp?.Count() != null || server.ServerExp?.Count() != 0)
            {
                try
                {
                    return(server.ServerExp?.First(x => x?.UserId == user.UserId)?.Exp ?? 0);
                }
                catch (InvalidOperationException)
                {
                    var exp = new ServerExp
                    {
                        ServerId  = server.ServerId,
                        UserId    = user.UserId,
                        Exp       = 0,
                        LatestExp = 0,
                        User      = user
                    };

                    if (server.ServerExp != null && server.ServerExp.Any(x => x.UserId == exp.UserId))
                    {
                        DatabaseQueries.InsertOrReplaceAsync(exp);
                    }

                    ConsoleLogger.LogAsync($"User {user.UserId} in {server.ServerId} was not present " +
                                           $"in the guild's ServerExp list when attempting to load this value. " +
                                           $"They have now been added into the database under the ServerExp table.", LogLvl.DEBUG);

                    return(0);
                }
            }

            return(0);
        }
Example #25
0
        public async Task Command(ulong?id = null)
        {
            id ??= Context.User.Id;

            User user = await DatabaseQueries.GetOrCreateUserAsync(Context.User.Id);

            if (id != Context.User.Id && !user.IsBotOwner)
            {
                await SendBasicErrorEmbedAsync("Only bot owners can display other people's profiles. Please " +
                                               "use this command without a parameter.");

                return;
            }

            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            if (id != Context.User.Id)
            {
                user = await DatabaseQueries.GetOrCreateUserAsync(id.Value);
            }

            using (Context.Channel.EnterTypingState())
            {
                var    p     = new ProfileImage();
                Stream image = await p.GenerateProfileImageStream(user, server, Context.Guild.GetUser(id.Value));

                await Context.Channel.SendFileAsync(image, "Kaguya_Profile_" +
                                                    $"{Context.User.Username}_{DateTime.Now.Month}_" +
                                                    $"{DateTime.Now.Day}_{DateTime.Now.Year}.png");
            }
        }
Example #26
0
        private async Task ReactionReply(SocketGuildUser user,
                                         IReadOnlyCollection <WarnedUser> warnings,
                                         Embed embed,
                                         int warnCount,
                                         Server server,
                                         string reason)
        {
            Emoji[] emojis = GlobalProperties.EmojisOneThroughNine();

            var data      = new ReactionCallbackData("", embed, false, false, TimeSpan.FromSeconds(300));
            var callbacks = new List <(IEmote, Func <SocketCommandContext, SocketReaction, Task>)>();

            for (int j = 0; j < warnCount; j++)
            {
                int j1 = j;
                callbacks.Add((emojis[j], async(c, r) =>
                {
                    var uwArgs = new ModeratorEventArgs(server, Context.Guild, user, (SocketGuildUser)Context.User, reason, null);
                    KaguyaEvents.TriggerUnwarn(uwArgs);

                    await DatabaseQueries.DeleteAsync(warnings.ElementAt(j1));
                    await c.Channel.SendMessageAsync($"{r.User.Value.Mention} " +
                                                     $"`Successfully removed warning #{j1 + 1}`");
                }));
            }

            data.SetCallbacks(callbacks);
            await InlineReactionReplyAsync(data);
        }
Example #27
0
        private void ExecuteDelete(object parameter)
        {
            int _id = ((Models.StatusModel)parameter).ID;

            if (_id != 0)
            {
                int ctr = DatabaseQueries.CountUsedID(CountSPName.CountUsedStatusID, _id);
                IMessageBoxService _msgbox = new MessageBoxService();

                if (ctr > 0)
                {
                    _msgbox.ShowMessage(((Models.StatusModel)parameter).Status + " is assigned to an Asset and cannot be deleted", "Cannot Delete", GenericMessageBoxButton.OK, GenericMessageBoxIcon.Asterisk);
                    //        _canexecutedelete = false;
                }
                else
                if (_msgbox.ShowMessage("Do you want to delete " + ((Models.StatusModel)parameter).Status + "?", "Delete Asset Status", GenericMessageBoxButton.OKCancel, GenericMessageBoxIcon.Question) == GenericMessageBoxResult.OK)
                {
                    AssetStatuses.Remove((Models.StatusModel)parameter);
                    DatabaseQueries.DeleteItem(_id, DeleteSPName.DeleteAssetStatus);
                }
                _msgbox = null;
            }
            else
            {
                AssetStatuses.Remove((Models.StatusModel)parameter);
            }
        }
Example #28
0
        public static async Task Trigger(SocketGuildUser u)
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(u.Guild.Id);

            if (!server.CustomGreetingIsEnabled)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(server.CustomGreeting))
            {
                return;
            }

            SocketTextChannel channel = u.Guild.GetTextChannel(server.LogGreetings);

            string greetingMsg = server.CustomGreeting;

            greetingMsg = greetingMsg.Replace("{USERNAME}", u.Username);
            greetingMsg = greetingMsg.Replace("{USERMENTION}", u.Mention);
            greetingMsg = greetingMsg.Replace("{SERVER}", u.Guild.Name);
            greetingMsg = greetingMsg.Replace("{MEMBERCOUNT}", $"{u.Guild.MemberCount.Ordinalize()}");

            await channel.SendMessageAsync(greetingMsg);
        }
Example #29
0
        public async Task Command()
        {
            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            LavaNode   node   = ConfigProperties.LavaNode;
            LavaPlayer player = node.GetPlayer(Context.Guild);

            if (player == null)
            {
                await SendBasicErrorEmbedAsync($"There needs to be an active music player in the " +
                                               $"server for this command to work. Start one " +
                                               $"by using `{server.CommandPrefix}play <song>`!");

                return;
            }

            if (player.PlayerState == PlayerState.Paused)
            {
                await player.ResumeAsync();
                await SendBasicSuccessEmbedAsync($"Successfully resumed the player.");
            }
            else
            {
                await SendBasicErrorEmbedAsync($"The player is already actively playing.");
            }
        }
Example #30
0
        private async Task InsertQuote(ICommandContext context, Server server, string text)
        {
            var quote = new Quote
            {
                UserId    = context.User.Id,
                ServerId  = context.Guild.Id,
                Text      = text,
                TimeStamp = DateTime.Now.ToOADate()
            };

            int quoteId = await DatabaseQueries.SafeAddQuoteAsync(server, quote);

            var embed = new KaguyaEmbedBuilder
            {
                Fields = new List <EmbedFieldBuilder>
                {
                    new EmbedFieldBuilder
                    {
                        Name  = $"Quote #{quoteId}",
                        Value = $"Successfully added the quote!\nQuote: `{text}`"
                    }
                }
            };

            await SendEmbedAsync(embed);

            server.NextQuoteId += 1;
            await DatabaseQueries.UpdateAsync(server);
        }