Пример #1
0
        private static Embed CreateMultipleEquipEmbedOutput(List <string> equipNames)
        {
            EmbedBuilder      builder      = new EmbedBuilder();
            EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder();

            if (equipNames.Count <= 5)
            {
                fieldBuilder.WithName("Found multiple matching equipment:");
                string value = string.Empty;
                for (int i = 0; i < 5 && i < equipNames.Count; i++)
                {
                    value += equipNames[i] + "\n";
                }
                fieldBuilder.WithValue(value);
                fieldBuilder.WithIsInline(false);
                builder.AddField(fieldBuilder);
            }
            else
            {
                fieldBuilder.WithName("Found multiple matching equipment:");
                string value = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    value += equipNames[i] + "\n";
                }
                if (equipNames.Count > 10)
                {
                    value += string.Format("\n*and {0} more matches*", equipNames.Count - 5);
                }

                fieldBuilder.WithValue(value);
                fieldBuilder.WithIsInline(true);
                builder.AddField(fieldBuilder);

                fieldBuilder = new EmbedFieldBuilder();
                fieldBuilder.WithName("\u200b");
                value = string.Empty;
                for (int i = 5; i < 10 && i < equipNames.Count; i++)
                {
                    value += equipNames[i] + "\n";
                }
                fieldBuilder.WithValue(value);
                fieldBuilder.WithIsInline(true);
                builder.AddField(fieldBuilder);
            }

            return(builder.WithColor(new Color(112, 141, 241)).Build());
        }
Пример #2
0
        public static EmbedBuilder WithField(this EmbedBuilder builder, string title, object value, bool inline = true)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                return(builder);
            }

            if (value == null)
            {
                return(builder);
            }
            string val = value.ToString();

            if (string.IsNullOrWhiteSpace(val))
            {
                return(builder);
            }

            EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder();

            fieldBuilder
            .WithIsInline(inline)
            .WithName(title)
            .WithValue(val.Length > 1024 ? $"{val.Substring(0, 1021)}..." : val);

            return(builder.WithFields(fieldBuilder));
        }
Пример #3
0
        public static Embed BuildEmbed(string sBranch, double iDays, string sVersion)
        {
            //Build the embed
            EmbedBuilder MyEmbedBuilder = new EmbedBuilder();

            MyEmbedBuilder.WithColor(new Color(43, 234, 152));
            MyEmbedBuilder.WithTitle("New DCS Update released!");
            MyEmbedBuilder.WithDescription("[DCS Update Page](http://updates.digitalcombatsimulator.com)");
            MyEmbedBuilder.WithThumbnailUrl("http://is1.mzstatic.com/image/thumb/Purple49/v4/71/b8/bc/71b8bca9-dfc5-e040-4e0f-54488d6a913b/source/175x175bb.jpg");

            EmbedFooterBuilder MyFooterBuilder = new EmbedFooterBuilder();

            MyFooterBuilder.WithText("Days since last update: " + iDays);
            MyFooterBuilder.WithIconUrl("https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-512.png");
            MyEmbedBuilder.WithFooter(MyFooterBuilder);

            EmbedFieldBuilder MyEmbedField = new EmbedFieldBuilder();

            MyEmbedField.WithIsInline(true);
            MyEmbedField.WithName("New " + sBranch + " release!");
            MyEmbedField.WithValue("Version: " + sVersion);

            MyEmbedBuilder.AddField(MyEmbedField);

            return(MyEmbedBuilder);
        }
Пример #4
0
        Embed CreateKeepStarEmebed(KeepStarProgress progress)
        {
            EmbedBuilder embedBuilder = new EmbedBuilder();

            embedBuilder.WithColor(Color.Gold);
            embedBuilder.WithThumbnailUrl("https://imageserver.eveonline.com/Render/35834_128.png");
            embedBuilder.WithAuthor($"Operation Golden Throne - {progress.Complete * 100}%",
                                    "https://imageserver.eveonline.com/Corporation/98270640_128.png",
                                    "https://goonfleet.com/index.php/topic/269069-operation-golden-throne/");
            embedBuilder.WithFooter("Dontations can be made at 1DQ1-A, B-7DFU or JITA 4-4.");

            double totalAssets = Math.Round(progress.AssetHistory[0].Item1 / 1000000000, 1);
            double escrow      = Math.Round(progress.BuyOrdersEscrow / 1000000000, 1);

            EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder();

            fieldBuilder.WithName($"Total Assets: {totalAssets.ToString("N1")}b ISK");
            fieldBuilder.WithValue($"Buy orders in escrow: {escrow.ToString("N1")}b ISK");
            embedBuilder.AddField(fieldBuilder);

            fieldBuilder = new EmbedFieldBuilder();
            fieldBuilder.WithName("Currently needed: PI");
            fieldBuilder.WithValue("P2: Viral Agent, Rocket Fuel, Polyaramids...\n⌴");
            embedBuilder.AddField(fieldBuilder);

            double totalPI = Math.Round(progress.TotalPI / 1000000000, 1);
            double p1      = Math.Round(progress.P1 / 1000000000, 1);
            double p2      = Math.Round(progress.P2 / 1000000000, 1);
            double p3      = Math.Round(progress.P3 / 1000000000, 1);
            double p4      = Math.Round(progress.P4 / 1000000000, 1);

            fieldBuilder = new EmbedFieldBuilder();
            fieldBuilder.WithName($"PI: {totalPI.ToString("N1")}b ISK");
            fieldBuilder.WithIsInline(true);
            fieldBuilder.WithValue($"P1: {p1.ToString("N1")}b ISK\n" +
                                   $"P2: {p2.ToString("N1")}b ISK\n" +
                                   $"P3: {p3.ToString("N1")}b ISK\n" +
                                   $"P4: {p4.ToString("N1")}b ISK\n");
            embedBuilder.AddField(fieldBuilder);

            double wallet = Math.Round(progress.Wallet / 1000000000, 1);

            fieldBuilder = new EmbedFieldBuilder();
            fieldBuilder.WithName($"Wallet: {wallet.ToString("N1")}b ISK");
            fieldBuilder.WithIsInline(true);

            string output = "";

            for (int i = 0; i < progress.AssetHistory.Count; i++)
            {
                float  walletHistory = progress.AssetHistory[i].Item1;
                double formated      = Math.Round(walletHistory / 1000000000, 1);

                output += $"{progress.AssetHistory[i].Item2}: {formated.ToString("N1")}b ISK\n";
            }
            fieldBuilder.WithValue(output);
            embedBuilder.AddField(fieldBuilder);

            return(embedBuilder.Build());
        }
        public GeobieBandsModule(GeobieBands bands, DiscordSocketClient client)
        {
            _bands  = bands;
            _client = client;

            EmbedFieldBuilder GeobieHelpCommandField = new EmbedFieldBuilder();

            GeobieHelpCommandField.Name  = "Goebiebands Commands";
            GeobieHelpCommandField.Value = "`-s <world> <type> <user>`\n`-dead <world>`\n`-removeworld <world>`";
            GeobieHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder GeobieHelpDescriptionField = new EmbedFieldBuilder();

            GeobieHelpDescriptionField.Name     = "Description";
            GeobieHelpDescriptionField.IsInline = true;
            GeobieHelpDescriptionField.Value    = "Registers a scout. Types: a, f, w.\nMark a world dead.\nRemoves a world from the list.";
            EmbedFieldBuilder worlds = new EmbedFieldBuilder();

            worlds.Name  = "World Information";
            worlds.Value = "Early spawn worlds: 12, 14, 15, 30, 37, 49, 50, 51, 65, 83, 84\n" +
                           "Early spawn worlds spawn at: 02 and die at: 22\n" +
                           "All other worlds spawn at: 05 and die at: 25";


            eb1.AddField(GeobieHelpCommandField);
            eb1.AddField(GeobieHelpDescriptionField);
            eb1.AddField(worlds);
        }
        private static Embed CreateMultipleShardsCardEmbedOutput(List <ShardsCard> cards)
        {
            EmbedBuilder      builder      = new EmbedBuilder();
            EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder();

            if (cards.Count <= 5)
            {
                fieldBuilder.WithName("Found multiple matching cards:");
                string value = string.Empty;
                for (int i = 0; i < 5 && i < cards.Count; i++)
                {
                    value += cards[i].Name + "\n";
                }
                fieldBuilder.WithValue(value);
                fieldBuilder.WithIsInline(false);
                builder.AddField(fieldBuilder);
            }
            else
            {
                fieldBuilder.WithName("Found multiple matching cards:");
                string value = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    value += cards[i].Name + "\n";
                }
                if (cards.Count > 10)
                {
                    value += string.Format("\n*and {0} more matches*", cards.Count - 10);
                }

                fieldBuilder.WithValue(value);
                fieldBuilder.WithIsInline(true);
                builder.AddField(fieldBuilder);

                fieldBuilder = new EmbedFieldBuilder();
                fieldBuilder.WithName("\u200b");
                value = string.Empty;
                for (int i = 5; i < 10 && i < cards.Count; i++)
                {
                    value += cards[i].Name + "\n";
                }
                fieldBuilder.WithValue(value);
                fieldBuilder.WithIsInline(true);
                builder.AddField(fieldBuilder);
            }
            return(builder.WithColor(new Color(112, 141, 241)).Build());
        }
Пример #7
0
        private static EmbedFieldBuilder CreateEmbedField(bool inline, string name, object value)
        {
            EmbedFieldBuilder FieldBuilder = new EmbedFieldBuilder();

            FieldBuilder.WithIsInline(inline);
            FieldBuilder.WithName(name);
            FieldBuilder.WithValue(value);
            return(FieldBuilder);
        }
Пример #8
0
        public static EmbedFieldBuilder CreateEmbedField(string title, string discription, bool inline)
        {
            EmbedFieldBuilder ebf = new EmbedFieldBuilder();

            ebf.WithName(title);
            ebf.WithValue(discription);
            ebf.WithIsInline(inline);
            return(ebf);
        }
Пример #9
0
        public static EmbedFieldBuilder SetField(String name, String value, Boolean inline = false)
        {
            EmbedFieldBuilder field = new EmbedFieldBuilder();

            field.WithName(name);
            field.WithValue(value);
            field.WithIsInline(inline);
            return(field);
        }
Пример #10
0
        public async Task Say10()
        {
            if (119019602574442497 != Context.User.Id)
            {
                // Secrurity check
                await ReplyAsync("This is a debug command, you cannot use it!");

                return;
            }
            EmbedBuilder MyEmbedBuilder = new EmbedBuilder();

            MyEmbedBuilder.WithColor(new Color(43, 234, 152));
            MyEmbedBuilder.WithTitle("Your title");

            MyEmbedBuilder.WithUrl("http://www.google.com");
            //MyEmbedBuilder.WithDescription("My description");
            MyEmbedBuilder.WithDescription("[Google](http://www.google.com)");

            MyEmbedBuilder.WithThumbnailUrl("https://forum.codingwithstorm.com/Themes/Modern/images/vertex_image/social_twitter_icon.png");
            MyEmbedBuilder.WithImageUrl("https://forum.codingwithstorm.com/Themes/Modern/images/vertex_image/social_facebook_icon.png");

            //Footer
            EmbedFooterBuilder MyFooterBuilder = new EmbedFooterBuilder();

            MyFooterBuilder.WithText("Your text");
            MyFooterBuilder.WithIconUrl("https://forum.codingwithstorm.com/Smileys/Koloboks/wink3.gif");
            MyEmbedBuilder.WithFooter(MyFooterBuilder);

            //Author
            EmbedAuthorBuilder MyAuthorBuilder = new EmbedAuthorBuilder();

            MyAuthorBuilder.WithName("Your Name");
            MyAuthorBuilder.WithUrl("http://www.google.com");
            MyEmbedBuilder.WithAuthor(MyAuthorBuilder);

            //EmbedField
            EmbedFieldBuilder MyEmbedField = new EmbedFieldBuilder();

            MyEmbedField.WithIsInline(true);
            MyEmbedField.WithName("Your Field Name");
            MyEmbedField.WithValue("Your value");
            MyEmbedField.WithValue("[Youtube](http://www.youtube.com)");

            MyEmbedBuilder.AddField(MyEmbedField);
            MyEmbedBuilder.AddField(MyEmbedField);
            MyEmbedBuilder.AddField(MyEmbedField);
            MyEmbedBuilder.AddField(MyEmbedField);
            MyEmbedBuilder.AddField(MyEmbedField);
            MyEmbedBuilder.AddField(MyEmbedField);
            MyEmbedBuilder.AddField(MyEmbedField);

            await ReplyAsync("Swaaaag:", false, MyEmbedBuilder);
        }
Пример #11
0
        /// <summary>
        /// Generates a Discord Embed for the given <paramref name="stream"/>
        /// </summary>
        /// <param name="stream"></param>
        /// <returns>Discord Embed with Stream Information</returns>
        public static Embed GetStreamEmbed(ILiveBotStream stream, ILiveBotUser user, ILiveBotGame game)
        {
            // Build the Author of the Embed
            EmbedAuthorBuilder authorBuilder = new EmbedAuthorBuilder();

            authorBuilder.WithName(user.DisplayName);
            authorBuilder.WithIconUrl(user.AvatarURL);
            authorBuilder.WithUrl(user.ProfileURL);

            // Build the Footer of the Embed
            EmbedFooterBuilder footerBuilder = new EmbedFooterBuilder();

            footerBuilder.WithText("Stream start time");

            // Add Basic information to EmbedBuilder
            EmbedBuilder builder = new EmbedBuilder();

            builder.WithColor(Color.DarkPurple);

            builder.WithAuthor(authorBuilder);
            builder.WithFooter(footerBuilder);

            builder.WithTimestamp(stream.StartTime);
            builder.WithDescription(stream.Title);
            builder.WithUrl(stream.StreamURL);
            builder.WithThumbnailUrl(user.AvatarURL);

            // Add Status Field
            //EmbedFieldBuilder statusBuilder = new EmbedFieldBuilder();
            //statusBuilder.WithIsInline(false);
            //statusBuilder.WithName("Status");
            //statusBuilder.WithValue("");
            //builder.AddField(statusBuilder);

            // Add Game field
            EmbedFieldBuilder gameBuilder = new EmbedFieldBuilder();

            gameBuilder.WithIsInline(true);
            gameBuilder.WithName("Game");
            gameBuilder.WithValue(game.Name);
            builder.AddField(gameBuilder);

            // Add Stream URL field
            EmbedFieldBuilder streamURLField = new EmbedFieldBuilder();

            streamURLField.WithIsInline(true);
            streamURLField.WithName("Stream");
            streamURLField.WithValue(stream.StreamURL);
            builder.AddField(streamURLField);

            return(builder.Build());
        }
Пример #12
0
        private static async Task <Embed> CreateEquipEmbedOutput(string equipName)
        {
            EmbedBuilder      builder      = new EmbedBuilder();
            EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder();

            builder.WithImageUrl(CreateEquipLink(equipName));
            fieldBuilder.WithIsInline(false);
            fieldBuilder.WithName(string.Format("{0}(Equipment)", equipName));

            // get ah prices from the hexprice api
            SearchRequest searchQuery = new SearchRequest()
            {
                SearchQuery = equipName,
            };
            HttpResponseMessage response = await Program.httpClient.PostAsJsonAsync("items/search", searchQuery);

            if (response.IsSuccessStatusCode)
            {
                SearchResult[] resultList = await response.Content.ReadAsAsync <SearchResult[]>();

                int  resultIndex;
                bool foundExactMatch = false;
                for (resultIndex = 0; resultIndex < resultList.Length; resultIndex++)
                {
                    if (resultList[resultIndex].Item.LinkName.Equals(equipName, StringComparison.OrdinalIgnoreCase))
                    {
                        foundExactMatch = true;
                        break;
                    }
                }

                if (foundExactMatch)
                {
                    int platBuyout = resultList[resultIndex].CurrentCheapestPlat;
                    int goldBuyout = resultList[resultIndex].CurrentCheapestGold;

                    fieldBuilder.WithValue(string.Format("Lowest Buyout: [{0} | {1}]({2})", platBuyout == -1 ? "none" : string.Format("{0}p", platBuyout), goldBuyout == -1 ? "none" : string.Format("{0}g", goldBuyout), CreateHexPriceLink(resultList[resultIndex])));
                }
                else
                {
                    fieldBuilder.WithValue("Couldn't find AH data.");
                }
            }
            else
            {
                fieldBuilder.WithValue("Couldn't connect to hexprice.com.");
            }

            builder.AddField(fieldBuilder);
            return(builder.WithColor(new Color(112, 141, 241)).Build());
        }
Пример #13
0
        public async Task Draw()
        {
            GameContext context = GameContexts.getContext(Context.Guild.Id);

            foreach (IUser user in context.Players)
            {
                EmbedBuilder embed = new EmbedBuilder();
                embed.WithTitle("Superfight Round");
                embed.WithDescription("Respond with \'number, number\' to play cards. E.g. \'2, 1\' \n First number chooses character and second number chooses attribute");

                List <EmbedFieldBuilder> fields = new List <EmbedFieldBuilder>();

                EmbedFieldBuilder characterField = new EmbedFieldBuilder();
                characterField.WithName("Characters");
                characterField.WithIsInline(true);
                Card[] characters = new Card[3];
                for (int i = 0; i < 3; i++)
                {
                    characters[i] = context.Deck.DrawCharacter();
                }
                characterField.WithValue(string.Format("1: {1} {0} 2: {2} {0} 3: {3}", Environment.NewLine, characters[0], characters[1], characters[2]));

                embed.AddField(characterField);

                EmbedFieldBuilder attributeField = new EmbedFieldBuilder();
                attributeField.WithName("Attributes");
                attributeField.WithIsInline(true);
                Card[] attributes = new Card[3];
                for (int i = 0; i < 3; i++)
                {
                    attributes[i] = context.Deck.DrawAttribute();
                }
                attributeField.WithValue(string.Format("1: {1} {0} 2: {2} {0} 3: {3}", Environment.NewLine, attributes[0], attributes[1], attributes[2]));

                embed.AddField(attributeField);

                IDMChannel channel = await user.GetOrCreateDMChannelAsync();

                await channel.SendMessageAsync("", false, embed.Build());

                MessageUser(user, channel, Context.Channel, characters, attributes, context.Deck.DrawAttribute());
            }
        }
Пример #14
0
        public WarbandsModule(Warbands bands, DiscordSocketClient client)
        {
            _bands  = bands;
            _client = client;

            EmbedFieldBuilder WarbandsHelpCommandField = new EmbedFieldBuilder();

            WarbandsHelpCommandField.Name  = "Warbands Commands";
            WarbandsHelpCommandField.Value = "`-w <world> <type>`\n`-ClearWarbands`";
            WarbandsHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder WarbandsHelpDescriptionField = new EmbedFieldBuilder();

            WarbandsHelpDescriptionField.Name     = "Description";
            WarbandsHelpDescriptionField.IsInline = true;
            WarbandsHelpDescriptionField.Value    = "Adds or edits a world, values: dwf, elm, rdi, broken, dead.\nClears the current list.";

            eb.AddField(WarbandsHelpCommandField);
            eb.AddField(WarbandsHelpDescriptionField);
        }
Пример #15
0
        public async Task Error(string type, string erronious)
        {
            var    activeuser   = Context.User;
            string errorType    = "";
            string errorMessage = "";
            string normalError  = "";

            //Color rarity = new Color(218, 40, 176);

            if (type == "dice")
            {
                errorType    = "teambuildergif";
                errorMessage = "*hmmm*.  " + Context.User.Username + " How about trying one of the following 4 options. Dice or die for the dice quantites, or nodice or nodie for images without quantites?";
                normalError  = "the quantiy graphic variable";
            }
            else
            {
                errorType    = "???";
                errorMessage = "???";
            }

            EmbedBuilder EmbeddedError = new EmbedBuilder();

            EmbeddedError.WithColor(218, 40, 176);
            EmbeddedError.WithTitle("__ERROR!__");
            EmbeddedError.WithDescription(errorType);
            EmbeddedError.WithImageUrl("https://i.imgur.com/8oLeQiY.jpg");

            EmbedFieldBuilder ErrorMessageField = new EmbedFieldBuilder();

            ErrorMessageField.WithIsInline(true);
            ErrorMessageField.WithName("A Message from The Collector");
            ErrorMessageField.WithValue(errorMessage);
            EmbeddedError.AddField(ErrorMessageField);

            await Context.Channel.SendMessageAsync("I have detected an error with " + normalError + ". I have PM'ed you more details.");

            await activeuser.SendMessageAsync("", false, EmbeddedError.Build());
        }
Пример #16
0
        //constructor - when the object is created this is called
        public CastleWarsModule(DiscordSocketClient client, CastleWarsGame game)
        {
            //pulls needed info from the serviceCollection in the main program
            _game   = game;
            _client = client;

            EmbedFieldBuilder CoordHelpCommandField = new EmbedFieldBuilder();

            CoordHelpCommandField.Name  = "Coordination Commands";
            CoordHelpCommandField.Value = "`-StartGames`\n`-ChangeCoord <user#1111>`\n`-AddP <s, z> <username>`\n" +
                                          "`-AddR <username>`\n`-Remove <username>`\n`-NewRound`\n`-StopGames`";
            CoordHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder CoordHelpDescriptionField = new EmbedFieldBuilder();

            CoordHelpDescriptionField.Name     = "Description";
            CoordHelpDescriptionField.IsInline = true;
            CoordHelpDescriptionField.Value    = "Starts games of Castle Wars.\nChanges the coordinator of the game.\n" +
                                                 "Adds a perm member to either team.\nAdds a rotating member to available team.\nRemoves a user from the games.\n" +
                                                 "Use this at the start of each round to switch teams.\nThis closes the games.";

            eb.AddField(CoordHelpCommandField);
            eb.AddField(CoordHelpDescriptionField);
        }
Пример #17
0
        public List <Command> Init(IBotwinderClient iClient)
        {
            this.Client = iClient as BotwinderClient;
            List <Command> commands = new List <Command>();

// !tempChannel
            Command newCommand = new Command("tempChannel");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Creates a temporary voice channel. This channel will be destroyed when it becomes empty, with grace period of three minutes since it's creation.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (e.Server.Config.TempChannelCategoryId == 0)
                {
                    await e.SendReplySafe("This command has to be configured on the config page (social) <https://valkyrja.app/config>");

                    return;
                }

                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}tempChannel <name>` or `{e.Server.Config.CommandPrefix}tempChannel [userLimit] <name>`");

                    return;
                }

                int           limit   = 0;
                bool          limited = int.TryParse(e.MessageArgs[0], out limit);
                StringBuilder name    = new StringBuilder();
                for (int i = limited ? 1 : 0; i < e.MessageArgs.Length; i++)
                {
                    name.Append(e.MessageArgs[i]);
                    name.Append(" ");
                }
                string responseString = string.Format(TempChannelConfirmString, name.ToString());

                try
                {
                    RestVoiceChannel tempChannel = null;
                    if (limited)
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => {
                            c.CategoryId = e.Server.Config.TempChannelCategoryId;
                            c.UserLimit  = limit;
                        });
                    }
                    else
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => c.CategoryId = e.Server.Config.TempChannelCategoryId);
                    }

                    ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    ChannelConfig channel   = dbContext.Channels.FirstOrDefault(c => c.ServerId == e.Server.Id && c.ChannelId == tempChannel.Id);
                    if (channel == null)
                    {
                        channel = new ChannelConfig {
                            ServerId  = e.Server.Id,
                            ChannelId = tempChannel.Id
                        };

                        dbContext.Channels.Add(channel);
                    }

                    channel.Temporary = true;
                    dbContext.SaveChanges();
                    dbContext.Dispose();
                }
                catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    responseString = string.Format(ErrorUnknownString, this.Client.GlobalConfig.AdminUserId);
                }
                await e.SendReplySafe(responseString);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("tmp"));
            commands.Add(newCommand.CreateAlias("tc"));

// !mentionRole
            newCommand                     = new Command("mentionRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Mention a role with a message. Use with the name of the role as the first parameter and the message will be the rest.";
            newCommand.DeleteRequest       = true;
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplyUnsafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <roleName> <message text>`");

                    return;
                }

                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = e.Server.Guild.Roles.Where(r => r.Name == e.MessageArgs[0])).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower() == e.MessageArgs[0].ToLower())).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.MessageArgs[0].ToLower()))).Any())
                {
                    await e.SendReplyUnsafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplyUnsafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role    = foundRoles.First();
                string     message = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[1]));

                await role.ModifyAsync(r => r.Mentionable = true);

                await Task.Delay(100);

                await e.SendReplySafe($"{role.Mention} {message}");

                await Task.Delay(100);

                await role.ModifyAsync(r => r.Mentionable = false);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("announce"));

// !cheatsheet
            newCommand                     = new Command("cheatsheet");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send an embed cheatsheet with various moderation commands.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation commands").WithColor(16711816).WithFields(
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}op`").WithValue("Distinguish yourself as a moderator when addressing people, and allow the use of `!mute`, `!kick` & `!ban` commands."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}mute @user(s) duration`").WithValue("Mute mentioned user(s) for `duration` (use `m`, `h` and `d`, e.g. 1h15m. This will effectively move them to the `#chill-zone` channel."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}kick @user(s) reason`").WithValue("Kick mentioned `@users` (or IDs) with specific `reason`."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}ban @user(s) duration reason`").WithValue("Ban mentioned `@users` (or IDs) for `duration` (use `h` and `d`, e.g. 1d12h, or zero `0d` for permanent) with specific `reason`."),
                    new EmbedFieldBuilder().WithName("`reason`").WithValue("Reason parameter of the above `kick` and `ban` commands is stored in the database as a _warning_ and also PMed to the user. Please provide proper descriptions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}issueWarning @user(s) message`").WithValue("The same as `addWarning`, but also PM this message to the user(s)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}addWarning @user(s) message`").WithValue("Add a `message` to the database, taking notes of peoples naughty actions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}removeWarning @user`").WithValue("Remove the last added warning from the `@user` (or ID)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}whois @user`").WithValue("Search for a `@user` (or ID, or name) who is present on the server."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}find expression`").WithValue("Search for a user using more complex search through all the past nicknames, etc... This will also go through people who are not on the server anymore."),
                    new EmbedFieldBuilder().WithName($"`whois/find`").WithValue("Both whois and find commands will return information about the user, when was their account created, when did they join, their past names and nicknames, and all the previous warnings and bans.")
                    );

                RestUserMessage msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();

                embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation guidelines").WithColor(16711816).WithDescription("for implementing the [theory](http://rhea-ayase.eu/articles/2017-04/Moderation-guidelines) in real situations.\n")
                .WithFields(
                    new EmbedFieldBuilder().WithName("__Talking to people__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Don't use threats.").WithValue("a) **Imposed consequences** - what you can do with your power (kick, ban,...) These are direct threats, avoid them.\nb) **Natural consequences** - implied effects of members actions. These can include \"the community is growing to dislike you,\" or \"see you as racist,\" etc..."),
                    new EmbedFieldBuilder().WithName("Identify what is the underlying problem.").WithValue("a) **Motivation problem** - the member is not motivated to behave in acceptable manner - is a troll or otherwise enjoys being mean to people.\nb) **Ability problem** - the member may be direct without \"filters\" and their conversation often comes off as offensive while they just state things the way they see them: http://www.mit.edu/~jcb/tact.html"),
                    new EmbedFieldBuilder().WithName("Conversation should follow:").WithValue("1) **Explain** the current situation / problem.\n2) **Establish safety** - you're not trying to ban them or discourage them from participating.\n3) **Call to action** - make sure to end the conversation with an agreement about what steps will be taken towards improvement.\n"),
                    new EmbedFieldBuilder().WithName("__Taking action__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Always log every action").WithValue("with `warnings`, and always check every member and their history."),
                    new EmbedFieldBuilder().WithName("Contents of our channels should not be disrespectful towards anyone, think about minorities.").WithValue("a) Discussion topic going wild, the use of racial/homophobic or other improper language should be pointed out with an explanation that it is not cool towards minorities within our community.\nb) A member being plain disrespectful on purpose... Mute them, see their reaction to moderation talk and act on it."),
                    new EmbedFieldBuilder().WithName("Posting or even spamming inappropriate content").WithValue("should result in immediate mute and only then followed by explaining correct behavior based on all of the above points."),
                    new EmbedFieldBuilder().WithName("Repeated offense").WithValue("a) 1d ban, 3d ban, 7d ban - are your options depending on how severe it is.\nb) Permanent ban should be brought up for discussion with the rest of the team."),
                    new EmbedFieldBuilder().WithName("Member is disrespectful to the authority.").WithValue("If you get into conflict yourself, someone is disrespectful to you as a moderator, trolling and challenging your authority - step back and ask for help, mention `@Staff` in the mod channel, and let 3rd party deal with it.")
                    );

                msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();
            };
            commands.Add(newCommand);

// !embed
            newCommand                     = new Command("embed");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Build an embed. Use without arguments for help.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage) || e.TrimmedMessage == "-h" || e.TrimmedMessage == "--help")
                {
                    await e.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
                                          "[ --channel     ] Channel where to send the embed.\n" +
                                          "[ --title       ] Short title\n" +
                                          "[ --description ] Short description\n" +
                                          "[ --color       ] #rrggbb hex color used for the embed stripe.\n" +
                                          "[ --image       ] URL of a Hjuge image in the bottom.\n" +
                                          "[ --thumbnail   ] URL of a smol image on the side.\n" +
                                          "[ --fieldName   ] Create a new field with specified name.\n" +
                                          "[ --fieldValue  ] Text value of a field - has to follow a name.\n" +
                                          "[ --fieldInline ] Use to set the field as inline.\n" +
                                          "Where you can repeat the field* options multiple times.\n```"
                                          );

                    return;
                }

                bool debug = false;
                SocketTextChannel channel      = e.Channel;
                EmbedFieldBuilder currentField = null;
                EmbedBuilder      embedBuilder = new EmbedBuilder();

                foreach (Match match in this.EmbedParamRegex.Matches(e.TrimmedMessage))
                {
                    string optionString = this.EmbedOptionRegex.Match(match.Value).Value;

                    if (optionString == "--debug")
                    {
                        if (this.Client.IsGlobalAdmin(e.Message.Author.Id) || this.Client.IsSupportTeam(e.Message.Author.Id))
                        {
                            debug = true;
                        }
                        continue;
                    }

                    if (optionString == "--fieldInline")
                    {
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldInline` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithIsInline(true);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting inline for field `{currentField.Name}`");
                        }
                        continue;
                    }

                    string value;
                    if (match.Value.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = match.Value.Substring(optionString.Length + 1).Trim()))
                    {
                        await e.SendReplySafe($"Invalid value for `{optionString}`");

                        return;
                    }

                    if (value.Length >= UserProfileOption.ValueCharacterLimit)
                    {
                        await e.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                        return;
                    }

                    switch (optionString)
                    {
                    case "--channel":
                        if (!guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = e.Server.Guild.GetTextChannel(id)) == null)
                        {
                            await e.SendReplySafe($"Channel {value} not found.");

                            return;
                        }
                        if (debug)
                        {
                            await e.SendReplySafe($"Channel set: `{channel.Name}`");
                        }

                        break;

                    case "--title":
                        embedBuilder.WithTitle(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Title set: `{value}`");
                        }

                        break;

                    case "--description":
                        embedBuilder.WithDescription(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Description set: `{value}`");
                        }

                        break;

                    case "--image":
                        embedBuilder.WithImageUrl(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Image URL set: `{value}`");
                        }

                        break;

                    case "--thumbnail":
                        embedBuilder.WithThumbnailUrl(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Thumbnail URL set: `{value}`");
                        }

                        break;

                    case "--color":
                        uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                        embedBuilder.WithColor(color);
                        if (debug)
                        {
                            await e.SendReplySafe($"Color `{value}` set.");
                        }

                        break;

                    case "--fieldName":
                        if (currentField != null && currentField.Value == null)
                        {
                            await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                            return;
                        }

                        embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
                        if (debug)
                        {
                            await e.SendReplySafe($"Creating new field `{currentField.Name}`");
                        }

                        break;

                    case "--fieldValue":
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldValue` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithValue(value);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
                        }

                        break;

                    default:
                        await e.SendReplySafe($"Unknown option: `{optionString}`");

                        return;
                    }
                }

                if (currentField != null && currentField.Value == null)
                {
                    await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                    return;
                }

                await channel.SendMessageAsync(embed : embedBuilder.Build());
            };
            commands.Add(newCommand);

            return(commands);
        }
Пример #18
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient <BaseConfig>;
            List <Command> commands = new List <Command>();

// !embed
            Command newCommand = new Command("embed");

            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Build an embed. Use without arguments for help.";
            newCommand.ManPage     = new ManPage("<options>", "Use any combination of:\n" +
                                                 "`--channel     ` - Channel where to send the embed.\n" +
                                                 "`--edit <msgId>` - Replace a MessageId with a new embed (use after --channel)\n" +
                                                 "`--title       ` - Title\n" +
                                                 "`--description ` - Description\n" +
                                                 "`--footer      ` - Footer\n" +
                                                 "`--color       ` - #rrggbb hex color used for the embed stripe.\n" +
                                                 "`--image       ` - URL of a Hjuge image in the bottom.\n" +
                                                 "`--thumbnail   ` - URL of a smol image on the side.\n" +
                                                 "`--fieldName   ` - Create a new field with specified name.\n" +
                                                 "`--fieldValue  ` - Text value of a field - has to follow a name.\n" +
                                                 "`--fieldInline ` - Use to set the field as inline.\n" +
                                                 "Where you can repeat the field* options multiple times.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage) || e.TrimmedMessage == "-h" || e.TrimmedMessage == "--help")
                {
                    await e.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
                                          "[ --channel     ] Channel where to send the embed.\n" +
                                          "[ --edit <msgId>] Replace a MessageId with a new embed (use after --channel)\n" +
                                          "[ --title       ] Title\n" +
                                          "[ --description ] Description\n" +
                                          "[ --footer      ] Footer\n" +
                                          "[ --color       ] #rrggbb hex color used for the embed stripe.\n" +
                                          "[ --image       ] URL of a Hjuge image in the bottom.\n" +
                                          "[ --thumbnail   ] URL of a smol image on the side.\n" +
                                          "[ --fieldName   ] Create a new field with specified name.\n" +
                                          "[ --fieldValue  ] Text value of a field - has to follow a name.\n" +
                                          "[ --fieldInline ] Use to set the field as inline.\n" +
                                          "Where you can repeat the field* options multiple times.\n```"
                                          );

                    return;
                }

                bool              debug        = false;
                IMessage          msg          = null;
                SocketTextChannel channel      = null;
                EmbedFieldBuilder currentField = null;
                EmbedBuilder      embedBuilder = new EmbedBuilder();

                foreach (Match match in this.EmbedParamRegex.Matches(e.TrimmedMessage))
                {
                    string optionString = this.EmbedOptionRegex.Match(match.Value).Value;

                    if (optionString == "--fieldInline")
                    {
                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldInline` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithIsInline(true);
                        if (debug)
                        {
                            await e.SendReplySafe($"Setting inline for field `{currentField.Name}`");
                        }
                        continue;
                    }

                    string value;
                    if (match.Value.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = match.Value.Substring(optionString.Length + 1).Trim()))
                    {
                        await e.SendReplySafe($"Invalid value for `{optionString}`");

                        return;
                    }

                    if (value.Length >= BaseConfig.EmbedValueCharacterLimit)
                    {
                        await e.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {BaseConfig.EmbedValueCharacterLimit})");

                        return;
                    }

                    switch (optionString)
                    {
                    case "--channel":
                        if (!guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = e.Server.Guild.GetTextChannel(id)) == null)
                        {
                            await e.SendReplySafe($"Channel {value} not found.");

                            return;
                        }
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Channel set: `{channel.Name}`");
                        }

                        break;

                    case "--title":
                        if (value.Length > 256)
                        {
                            await e.SendReplySafe($"`--title` is too long (`{value.Length} > 256`)");

                            return;
                        }

                        embedBuilder.WithTitle(value);
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Title set: `{value}`");
                        }

                        break;

                    case "--description":
                        if (value.Length > 2048)
                        {
                            await e.SendReplySafe($"`--description` is too long (`{value.Length} > 2048`)");

                            return;
                        }

                        embedBuilder.WithDescription(value);
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Description set: `{value}`");
                        }

                        break;

                    case "--footer":
                        if (value.Length > 2048)
                        {
                            await e.SendReplySafe($"`--footer` is too long (`{value.Length} > 2048`)");

                            return;
                        }

                        embedBuilder.WithFooter(value);
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Description set: `{value}`");
                        }

                        break;

                    case "--image":
                        try
                        {
                            embedBuilder.WithImageUrl(value.Trim('<', '>'));
                        }
                        catch (Exception)
                        {
                            await e.SendReplySafe($"`--image` is invalid url");

                            return;
                        }

                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Image URL set: `{value}`");
                        }

                        break;

                    case "--thumbnail":
                        try
                        {
                            embedBuilder.WithThumbnailUrl(value.Trim('<', '>'));
                        }
                        catch (Exception)
                        {
                            await e.SendReplySafe($"`--thumbnail` is invalid url");

                            return;
                        }

                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Thumbnail URL set: `{value}`");
                        }

                        break;

                    case "--color":
                        uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                        if (color > uint.Parse("FFFFFF", System.Globalization.NumberStyles.AllowHexSpecifier))
                        {
                            await e.SendReplySafe("Color out of range.");

                            return;
                        }

                        embedBuilder.WithColor(color);
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Color `{value}` set.");
                        }

                        break;

                    case "--fieldName":
                        if (value.Length > 256)
                        {
                            await e.SendReplySafe($"`--fieldName` is too long (`{value.Length} > 256`)\n```\n{value}\n```");

                            return;
                        }

                        if (currentField != null && currentField.Value == null)
                        {
                            await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                            return;
                        }

                        if (embedBuilder.Fields.Count >= 25)
                        {
                            await e.SendReplySafe("Too many fields! (Limit is 25)");

                            return;
                        }

                        embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Creating new field `{currentField.Name}`");
                        }

                        break;

                    case "--fieldValue":
                        if (value.Length > 1024)
                        {
                            await e.SendReplySafe($"`--fieldValue` is too long (`{value.Length} > 1024`)\n```\n{value}\n```");

                            return;
                        }

                        if (currentField == null)
                        {
                            await e.SendReplySafe($"`fieldValue` can not precede `fieldName`.");

                            return;
                        }

                        currentField.WithValue(value);
                        if (debug)
                        {
                            await e.Channel.SendMessageSafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
                        }

                        break;

                    case "--edit":
                        if (!guid.TryParse(value, out guid msgId) || channel == null || (msg = await channel.GetMessageAsync(msgId)) == null)
                        {
                            await e.SendReplySafe($"`--edit` did not find a message with ID `{value}` in the <#{channel?.Id ?? 0}> channel.");

                            return;
                        }

                        break;

                    default:
                        await e.SendReplySafe($"Unknown option: `{optionString}`");

                        return;
                    }
                }

                if (currentField != null && currentField.Value == null)
                {
                    await e.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                    return;
                }

                switch (msg)
                {
                case null:
                    if (channel == null)
                    {
                        await e.SendReplySafe(embed : embedBuilder.Build());
                    }
                    else
                    {
                        await channel.SendMessageAsync(embed : embedBuilder.Build());
                    }
                    break;

                case RestUserMessage message:
                    await message?.ModifyAsync(m => m.Embed = embedBuilder.Build());

                    break;

                case SocketUserMessage message:
                    await message?.ModifyAsync(m => m.Embed = embedBuilder.Build());

                    break;

                default:
                    await e.SendReplySafe("GetMessage went bork.");

                    break;
                }
            };
            commands.Add(newCommand);

            return(commands);
        }
Пример #19
0
        public async Task InterServerChatSettings(string _botID = null)
        {
            if (_botID == SecurityInfo.botID || _botID == null)
            {
                bool hasAdmin = await HasAdmin();

                if (Context.User.Id == Context.Guild.OwnerId || hasAdmin)
                {
                    string interServerChan = Program.interServerChats.ContainsKey(Context.Guild.Id) ? Program.interServerChats[Context.Guild.Id].ToString()
                        : "No InterServer Chat channel has been assigned.\n\u200b";

                    string showUserServer = Program.showUserServer.Contains(Context.Guild.Id) ? "Enabled" : "Disabled";

                    string broadcastServerName = Program.broadcastServerName.Contains(Context.Guild.Id) ? "Enabled" : "Disabled";

                    string wlEnabled = Program.wlEnable.Contains(Context.Guild.Id) ? "Enabled" : "Disabled";

                    EmbedBuilder interServSettings = new EmbedBuilder();
                    interServSettings.WithColor(SecurityInfo.botColor);
                    interServSettings.WithTitle("__Current InterServer Chat Configuration__");

                    EmbedFieldBuilder interServChanEmb = new EmbedFieldBuilder();
                    interServChanEmb.WithIsInline(false);
                    interServChanEmb.WithName("InterServer Chat Channel");
                    if (interServerChan != "No InterServer Chat channel has been assigned.\n\u200b")
                    {
                        interServerChan = $"Name: {Context.Guild.GetChannel(Convert.ToUInt64(interServerChan)).Name}\n" +
                                          $"ID: {interServerChan}\n\u200b";
                    }
                    interServChanEmb.WithValue(interServerChan);
                    interServSettings.AddField(interServChanEmb);

                    EmbedFieldBuilder wlEnabledEmb = new EmbedFieldBuilder();
                    wlEnabledEmb.WithIsInline(false);
                    wlEnabledEmb.WithName("Whitelist");
                    wlEnabledEmb.WithValue(wlEnabled + "\n\u200b");
                    interServSettings.AddField(wlEnabledEmb);

                    EmbedFieldBuilder showUserServEmb = new EmbedFieldBuilder();
                    showUserServEmb.WithIsInline(true);
                    showUserServEmb.WithName("Show User's Guild");
                    showUserServEmb.WithValue(showUserServer);
                    interServSettings.AddField(showUserServEmb);

                    EmbedFieldBuilder broadcastServNameEmb = new EmbedFieldBuilder();
                    broadcastServNameEmb.WithIsInline(true);
                    broadcastServNameEmb.WithName("Broadcast Guild Name");
                    broadcastServNameEmb.WithValue(broadcastServerName);
                    interServSettings.AddField(broadcastServNameEmb);

                    if (_botID == SecurityInfo.botID)
                    {
                        await Context.User.SendMessageAsync("", false, interServSettings.Build());
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync("", false, interServSettings.Build());
                    }
                }
            }
        }
Пример #20
0
        public async Task Sihirdar([Remainder] string isim)
        {
            await Turkcemi(Context);

            try
            {
                Console.WriteLine(isim + "aranıyor");
                if (l == 1)
                {
                    await Context.Channel.SendMessageAsync(isim + " Aranıyor...");
                }
                else
                {
                    await Context.Channel.SendMessageAsync("Searching for " + isim + "...");
                }
                kills   = new string[5];
                deaths  = new string[5];
                assists = new string[5];
                result  = new string[5];
                isim.Replace(" ", "%20");


                // 1
                riot.summonerbul(isim);
                riot.macbilgi(riot.summonerid, riot.mac1id);
                kills[0]   = riot.kill;
                deaths[0]  = riot.death;
                assists[0] = riot.assist;
                result[0]  = riot.macsonuc;
                // 2
                riot.summonerbul(isim);
                riot.macbilgi(riot.summonerid, riot.mac2id);
                kills[1]   = riot.kill;
                deaths[1]  = riot.death;
                assists[1] = riot.assist;
                result[1]  = riot.macsonuc;
                // 3
                riot.summonerbul(isim);
                riot.macbilgi(riot.summonerid, riot.mac3id);
                kills[2]   = riot.kill;
                deaths[2]  = riot.death;
                assists[2] = riot.assist;
                result[2]  = riot.macsonuc;
                // 4
                riot.summonerbul(isim);
                riot.macbilgi(riot.summonerid, riot.mac4id);
                kills[3]   = riot.kill;
                deaths[3]  = riot.death;
                assists[3] = riot.assist;
                result[3]  = riot.macsonuc;
                // 5
                riot.summonerbul(isim);
                riot.macbilgi(riot.summonerid, riot.mac5id);
                kills[4]   = riot.kill;
                deaths[4]  = riot.death;
                assists[4] = riot.assist;
                result[4]  = riot.macsonuc;

                var eb = new EmbedBuilder()
                {
                    Title = "", Description = "**Maçlar**", Color = Color.Blue
                };
                if (l == 0)
                {
                    eb = new EmbedBuilder()
                    {
                        Title = "", Description = "**Matches**", Color = Color.Blue
                    }
                }
                ;
                string newname = riot.summonername;
                newname.First().ToString().ToUpper();
                EmbedAuthorBuilder MyAuthorBuilder = new EmbedAuthorBuilder();
                if (l == 1)
                {
                    MyAuthorBuilder.WithName(newname + " - Tüm profil için tıkla");
                }
                else
                {
                    MyAuthorBuilder.WithName(newname + " - Click for complete profile");
                }
                MyAuthorBuilder.WithIconUrl("https://i.hizliresim.com/JlvA4B.jpg");
                eb.WithAuthor(MyAuthorBuilder);
                for (int i = 0; i < 5; i++)
                {
                    if (result[i] == "Zafer")
                    {
                        if (l == 1)
                        {
                            result[i] = ":white_check_mark: Zafer";
                        }
                        else
                        {
                            result[i] = ":white_check_mark: Win";
                        }
                    }
                    if (result[i] == "Bozgun")
                    {
                        if (l == 1)
                        {
                            result[i] = ":no_entry_sign: Bozgun";
                        }
                        else
                        {
                            result[i] = ":no_entry_sign: Loss";
                        }
                    }
                }
                EmbedFieldBuilder MyEmbedField = new EmbedFieldBuilder();
                MyEmbedField.WithIsInline(true);
                MyEmbedField.WithName(result[0]);
                MyEmbedField.WithValue(kills[0] + "/" + deaths[0] + "/" + assists[0]);
                eb.AddField(MyEmbedField);

                EmbedFieldBuilder MyEmbedField2 = new EmbedFieldBuilder();
                MyEmbedField2.WithIsInline(true);
                MyEmbedField2.WithName(result[1]);
                MyEmbedField2.WithValue(kills[1] + "/" + deaths[1] + "/" + assists[1]);
                eb.AddField(MyEmbedField2);

                EmbedFieldBuilder MyEmbedField3 = new EmbedFieldBuilder();
                MyEmbedField3.WithIsInline(true);
                MyEmbedField3.WithName(result[2]);
                MyEmbedField3.WithValue(kills[2] + "/" + deaths[2] + "/" + assists[2]);
                eb.AddField(MyEmbedField3);

                EmbedFieldBuilder MyEmbedField4 = new EmbedFieldBuilder();
                MyEmbedField4.WithIsInline(true);
                MyEmbedField4.WithName(result[3]);
                MyEmbedField4.WithValue(kills[3] + "/" + deaths[3] + "/" + assists[3]);
                eb.AddField(MyEmbedField4);

                EmbedFieldBuilder MyEmbedField5 = new EmbedFieldBuilder();
                MyEmbedField5.WithIsInline(true);
                MyEmbedField5.WithName(result[4]);
                MyEmbedField5.WithValue(kills[4] + "/" + deaths[4] + "/" + assists[4]);
                eb.AddField(MyEmbedField5);

                EmbedFieldBuilder MyEmbedField6 = new EmbedFieldBuilder();
                MyEmbedField6.WithIsInline(true);
                MyEmbedField6.WithName("...");
                MyEmbedField6.WithValue("...");
                eb.AddField(MyEmbedField6);

                eb.WithUrl("http://www.lolking.net/summoner/tr/" + riot.summonerid2);

                await Context.Channel.SendMessageAsync("", false, eb);

                // Task.Delay(5000);
            }
            catch (Exception e)
            {
                if (l == 1)
                {
                    await Context.Channel.SendMessageAsync("```İşlemi gerçekleştirirken bir hata meydana geldi.\n" + e.Message + "\nHatanın kaynağı büyük ihtimal ile güncellenmemiş API anahtarı. \ndeveloper.riotgames.com```");
                }
                else
                {
                    await Context.Channel.SendMessageAsync("```Error: \n" + e.Message + "" + "\nProbably it caused by non updated API key. \ndeveloper.riotgames.com```");
                }
            }
        }
Пример #21
0
        private static async Task <Embed> CreateSingleCardEmbedOutput(string cardName, bool small)
        {
            EmbedBuilder      builder      = new EmbedBuilder();
            EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder();

            fieldBuilder.WithName(string.Format("{0}(Card)", cardName));
            fieldBuilder.WithIsInline(false);

            // get ah prices from the hexprice api
            SearchRequest searchQuery = new SearchRequest()
            {
                SearchQuery = cardName,
            };
            HttpResponseMessage response = await Program.httpClient.PostAsJsonAsync("items/search", searchQuery);

            if (response.IsSuccessStatusCode)
            {
                SearchResult[] resultList = await response.Content.ReadAsAsync <SearchResult[]>();

                int  resultIndex;
                bool foundExactMatch = false;
                for (resultIndex = 0; resultIndex < resultList.Length; resultIndex++)
                {
                    if (resultList[resultIndex].Item.LinkName.Equals(cardName, StringComparison.OrdinalIgnoreCase))
                    {
                        foundExactMatch = true;
                        break;
                    }
                }

                if (foundExactMatch)
                {
                    int platBuyout = resultList[resultIndex].CurrentCheapestPlat;
                    int goldBuyout = resultList[resultIndex].CurrentCheapestGold;

                    fieldBuilder.WithValue(string.Format("Lowest Buyout: [{0} | {1}]({2})", platBuyout == -1 ? "none" : string.Format("{0}p", platBuyout), goldBuyout == -1 ? "none" : string.Format("{0}g", goldBuyout), CreateHexPriceLink(resultList[resultIndex])));
                }
                else
                {
                    fieldBuilder.WithValue("Couldn't find AH data");
                }
            }
            else
            {
                fieldBuilder.WithValue("Couldn't connect to hexprice.com");
            }

            builder.AddField(fieldBuilder);


            // get equipment/card pairs out of the db
            string           sql     = "SELECT Equipment FROM EquipCardPairs WHERE EquipCardPairs.Card = '" + cardName.Replace("\'", "\'\'") + "'";
            SQLiteCommand    command = new SQLiteCommand(sql, Program.dbConnection);
            SQLiteDataReader reader  = command.ExecuteReader();

            List <string> equipsOfMatchingCard = new List <string>();

            while (reader.Read())
            {
                equipsOfMatchingCard.Add(Convert.ToString(reader["Equipment"]));
            }
            string equipments = string.Empty;

            if (equipsOfMatchingCard.Count > 0)
            {
                equipments += "Equipment: ";
                for (int i = 0; i < equipsOfMatchingCard.Count; i++)
                {
                    equipments += equipsOfMatchingCard[i];
                    if (i < equipsOfMatchingCard.Count - 1)
                    {
                        equipments += ", ";
                    }
                }
            }
            else
            {
                equipments = "No Equipment";
            }

            // add equipment/card image
            if (small)
            {
                fieldBuilder = new EmbedFieldBuilder().WithName(equipments)
                               .WithValue(string.Format("[ImageLink]({0})", CreateCardLink(cardName)));
                builder.AddField(fieldBuilder);
                builder.WithUrl(CreateCardLink(cardName));
                builder.WithThumbnailUrl(CreateCardLink(cardName));
            }
            else
            {
                builder.WithImageUrl(CreateCardLink(cardName));
                builder.WithFooter(equipments);
            }
            return(builder.WithColor(new Color(112, 141, 241)).Build());
        }
Пример #22
0
        public async Task Help(string _botID = null, string _param = null, string _param2 = null, string _param3 = null, string _param4 = null)
        {
            if (_botID != null && _botID != SecurityInfo.botID)
            {
                _param4 = _botID;
                _botID  = null;
            }

            List <string> _params = new List <string>
            {
                (_param == null) ? _param : _param.ToLower(),
                (_param2 == null) ? _param2 : _param2.ToLower(),
                (_param3 == null) ? _param3 : _param3.ToLower(),
                (_param4 == null) ? _param4 : _param4.ToLower()
            };

            EmbedBuilder helpMessage = new EmbedBuilder();

            helpMessage.WithTitle("Attention! Bot for Discord");
            helpMessage.WithDescription($"Bot Version {SecurityInfo.botVersion}  -  Programmed using Discord.Net 2.1.1 and Microsoft .NET Framework 4.7.2");
            helpMessage.WithColor(SecurityInfo.botColor);
            helpMessage.WithCurrentTimestamp();

            EmbedFieldBuilder prefixField = new EmbedFieldBuilder();

            prefixField.WithIsInline(false);
            prefixField.WithName("Prefix");
            prefixField.WithValue(CommandHandler.prefix.ToString() + "\n\u200b");
            helpMessage.AddField(prefixField);

            EmbedFieldBuilder helpField = new EmbedFieldBuilder();

            helpField.WithIsInline(true);
            helpField.WithName("\\help Parameters");
            helpField.WithValue(
                $"***NOTE:** If you choose to supply the {SecurityInfo.botID} parameter, it must be first. If you do not supply it, only one parameter may be given.*\n\n" +

                SecurityInfo.botID + "\n" +
                "  - DMs you all available help commands for the bot or the bot commands for any other given parameters.\n\n" +

                "useful\n" +
                "  - Lists all available useful commands for the bot.\n\n" +

                "spam\n" +
                "  - Lists all available spam commands for the bot.\n\n" +

                "admin\n" +
                "  - Lists all available admin commands for the bot.\n\n" +

                "interserver\n" +
                "  - Lists all available InterServer Chat commands for the bot.\n\u200b");

            EmbedFieldBuilder usefulField = new EmbedFieldBuilder();

            usefulField.WithIsInline(true);
            usefulField.WithName("Useful");
            usefulField.WithValue(
                "\\help [parameter(s) (optional)]\n" +
                "  - Lists available commands for the bot.\n\n" +

                "\\ping\n" +
                "  - Returns the latency of the bot.\n\n" +

                $"\\changelog [{SecurityInfo.botID} (optional)]\n" +
                "  - Sends a link to the version history (changelog) of the bot.\n\n" +

                "\\membercount\n" +
                "  - Lists number of users and bots on the server by status.\n\u200b");

            EmbedFieldBuilder spamField = new EmbedFieldBuilder();

            spamField.WithIsInline(true);
            spamField.WithName("Fun Spams");
            spamField.WithValue(
                "***NOTE:** User only works if \\mentions is set to 1. Set User to the ID or mention of the user you want to mention.*\n\n" +

                "**References from:** War Thunder\n\n" +

                "\\attention [position (optional)] [user ID/mention (optional)]\n" +
                "  - Message is randomized.\n" +
                "  - Position can contain one letter A-J and/or one number 1-10. Order and capitalization do not matter.\n" +
                "  - Position is randomized if none is given.\n" +
                "  - Order of parameters does not matter.\n\n" +

                "**References from:** Sword Art Online Abridged\n\n" +

                "\\gary [user (optional)]\n" +
                "  - \"We must save my family!\"\n\n" +

                "\\bandits [user (optional)]\n" +
                "  - \"The bandits are coming!\"\n\n" +

                "\\sword [user (optional)]\n" +
                "  - \"There's a person attached to this sword, you know! I WILL NOT BE OBJECTIFIED!\"\n\n" +

                "\\karf [user (optional)]\n" +
                "  - Quote is randomized.\n\u200b");

            EmbedFieldBuilder adminField = new EmbedFieldBuilder();

            adminField.WithIsInline(false);
            adminField.WithName("Admin");
            adminField.WithValue(
                "***NOTE:** Users with the \"Administrator\" power are considered Server Owners for these commands. \"Admins\" are the role(s) the Server Owners have designated as \"Admin\" roles.*\n\n" +
                "***NOTE 2:** The Role and Channel parameters can either be their respective ID or a mention of the channel/role.*\n\n" +

                $"\\settings [{SecurityInfo.botID} (optional)]\n" +
                "  - **ADMINS/SERVER OWNERS:** Displays the current configuration of the bot.\n\n" +

                "\\admin [role]\n" +
                "  - **SERVER OWNERS:** Sets/removes the specified role as an administrative role for the bot's admin commands.\n\n" +

                "\\announce [channel]\n" +
                "  - **ADMINS/SERVER OWNERS:** Sets the specified channel as the channel for bot announcements.\n" +
                "  - To disable announcements, type in \"-\" as the channel.\n\n" +

                "\\mentions [0/1]\n" +
                "  - **ADMINS/SERVER OWNERS:** Enables (1) or disables (0) user mentions for the bot.\n\u200b");

            EmbedFieldBuilder interServerField = new EmbedFieldBuilder();

            interServerField.WithIsInline(false);
            interServerField.WithName("InterServer Chat");
            interServerField.WithValue(
                "***NOTE:** All of these commands require the user to be a Server Owner or a user with the \"Administrator\" permission.*\n\n" +
                "***NOTE 2:** The channel parameter can either be its ID or a mention of the channel.*\n\n" +

                $"\\interserver-settings [{SecurityInfo.botID} (optional)]\n" +
                "  - Displays the current InterServer Chat configuration for the bot.\n\n" +

                "\\interserver-chat [channel]\n" +
                "  - Sets the specified channel as the channel for an InterServer Chat.\n" +
                "  - To disable InterServer Chat, type in \"-\" as the channel.\n\n" +

                "\\display-user-guild [0/1]\n" +
                "  - Enables (1) or disables (0) whether or not the bot shows what server the message was sent from.\n\n" +

                "\\broadcast-guild-name [0/1]\n" +
                "  - Enables (1) or disables (0) whether or not other servers can see your server's name if they have \\display-user-server set to 1.");

            EmbedFieldBuilder interServerWBLField = new EmbedFieldBuilder();

            interServerWBLField.WithIsInline(false);
            interServerWBLField.WithName("\u200b");
            interServerWBLField.WithValue(
                "\\enable-whitelist [0/1]\n" +
                "  - Enables (1) or disables (0) whether or not whitelist-only mode is on. Whitelist-only mode only allows your messages to reach whitelisted servers and messages from whitelisted servers to reach you.\n\n" +

                "\\whitelist [Server ID]\n" +
                "  - Adds the given server to the whitelist. Overrides the blacklist.\n\n" +

                "\\blacklist [Server ID]\n" +
                "  - Adds the given server to the blacklist.\n\u200b");

            List <string> parameters = new List <string>
            {
                "useful",
                "spam",
                "admin",
                "interserver"
            };

            bool fieldExists = false;

            foreach (string param in parameters)
            {
                fieldExists = _params.Contains(param);

                if (fieldExists)
                {
                    break;
                }
            }
            if (!fieldExists)
            {
                if (_botID != SecurityInfo.botID)
                {
                    helpMessage.AddField(helpField);
                }
                else
                {
                    helpMessage.AddField(usefulField);
                    helpMessage.AddField(spamField);
                    helpMessage.AddField(adminField);
                    helpMessage.AddField(interServerField);
                    helpMessage.AddField(interServerWBLField);
                }
            }

            if (_botID == null)
            {
                if (_params.Contains("useful"))
                {
                    helpMessage.AddField(usefulField);
                }
                else if (_params.Contains("spam"))
                {
                    helpMessage.AddField(spamField);
                }
                else if (_params.Contains("admin"))
                {
                    helpMessage.AddField(adminField);
                }
                else if (_params.Contains("interserver"))
                {
                    helpMessage.AddField(interServerField);
                    helpMessage.AddField(interServerWBLField);
                }

                await Context.Channel.SendMessageAsync("", false, helpMessage.Build());
            }
            else if (_botID == SecurityInfo.botID)
            {
                if (_params.Contains("useful"))
                {
                    helpMessage.AddField(usefulField);
                }
                if (_params.Contains("spam"))
                {
                    helpMessage.AddField(spamField);
                }
                if (_params.Contains("admin"))
                {
                    helpMessage.AddField(adminField);
                }
                if (_params.Contains("interserver"))
                {
                    helpMessage.AddField(interServerField);
                    helpMessage.AddField(interServerWBLField);
                }

                await Context.User.SendMessageAsync("", false, helpMessage.Build());
            }
        }
Пример #23
0
        private void PopulateEmbedFieldsWithModuleCommands(ModuleInfo moduleInfo, ref CakeEmbedBuilder cakeEmbedBuilder, string commandSearchFilter = "")
        {
            foreach (CommandInfo command in moduleInfo.Commands)
            {
                if (!CanAddCommandToEmbedField(command))
                {
                    continue;
                }

                EmbedFieldBuilder commandField = GetEmbedFieldWithCommandInfo(command);
                cakeEmbedBuilder.AddField(commandField);
            }

            #region Local_Function

            bool CanAddCommandToEmbedField(CommandInfo command)
            {
                if (CommandHasHideAttribute(command))
                {
                    return(false);
                }

                if (!string.IsNullOrWhiteSpace(commandSearchFilter))
                {
                    if (!CommandContainsSearchFilter(command))
                    {
                        return(false);
                    }
                }

                return(true);
            }

            bool CommandContainsSearchFilter(CommandInfo command)
            {
                if (!string.IsNullOrWhiteSpace(command.Name))
                {
                    if (command.Name.Contains(commandSearchFilter))
                    {
                        return(true);
                    }
                }

                if (!string.IsNullOrWhiteSpace(command.Remarks))
                {
                    if (command.Remarks.Contains(commandSearchFilter))
                    {
                        return(true);
                    }
                }

                if (!string.IsNullOrWhiteSpace(command.Summary))
                {
                    if (command.Summary.Contains(commandSearchFilter))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            EmbedFieldBuilder GetEmbedFieldWithCommandInfo(CommandInfo commandInfo)
            {
                EmbedFieldBuilder commandField = new EmbedFieldBuilder();

                commandField.WithIsInline(true);
                commandField.WithName(commandInfo.Name);
                commandField.WithValue(GetCommandDescriptionFromCommandInfo(commandInfo));
                return(commandField);
            }

            string GetCommandDescriptionFromCommandInfo(CommandInfo commandInfo)
            {
                return($"`{commandInfo.Summary}`{ System.Environment.NewLine + commandInfo.Remarks}");
            }

            #endregion
        }
Пример #24
0
        public async Task MemberCount()
        {
            long total = (long)Context.Guild.MemberCount;
            long totalBots = 0L, onlineBots = 0L;
            long totalUsers = total, onlineUsers = 0L, awayUsers = 0L, doNotDisturbUsers = 0L, invisibleUsers = 0L;

            foreach (SocketGuildUser user in Context.Guild.Users)
            {
                if (!user.IsBot)
                {
                    switch (user.Status)
                    {
                    case UserStatus.AFK:
                    case UserStatus.Idle:
                        awayUsers++;
                        break;

                    case UserStatus.DoNotDisturb:
                        doNotDisturbUsers++;
                        break;

                    case UserStatus.Invisible:
                        invisibleUsers++;
                        break;

                    case UserStatus.Online:
                        onlineUsers++;
                        break;

                    case UserStatus.Offline:
                    default:
                        break;
                    }
                }
                else
                {
                    totalUsers--;
                    totalBots++;

                    switch (user.Status)
                    {
                    case UserStatus.AFK:
                    case UserStatus.Idle:
                    case UserStatus.DoNotDisturb:
                    case UserStatus.Invisible:
                    case UserStatus.Online:
                        onlineBots++;
                        break;

                    case UserStatus.Offline:
                    default:
                        break;
                    }
                }
            }

            long offlineUsers = totalUsers - (onlineUsers + awayUsers + doNotDisturbUsers + invisibleUsers);
            long offlineBots  = totalBots - onlineBots;

            EmbedBuilder onlineMessage = new EmbedBuilder();

            onlineMessage.WithColor(SecurityInfo.botColor);
            onlineMessage.WithTitle("__Member Count__");
            onlineMessage.WithCurrentTimestamp();

            EmbedFieldBuilder totalBuilder = new EmbedFieldBuilder();

            totalBuilder.WithIsInline(false);
            totalBuilder.WithName("Total");
            totalBuilder.WithValue(total);
            onlineMessage.AddField(totalBuilder);

            EmbedFieldBuilder userBuilder = new EmbedFieldBuilder();

            userBuilder.WithIsInline(true);
            userBuilder.WithName($"\nUsers: {totalUsers}");
            userBuilder.WithValue(
                $"\nOnline: {onlineUsers}" +
                $"\nAway: {awayUsers}" +
                $"\nDo Not Disturb: {doNotDisturbUsers}" +
                $"\nInvisible: {invisibleUsers}" +
                $"\nOffline: {offlineUsers}\n");
            onlineMessage.AddField(userBuilder);

            EmbedFieldBuilder botBuilder = new EmbedFieldBuilder();

            botBuilder.WithIsInline(true);
            botBuilder.WithName($"\nBots: {totalBots}");
            botBuilder.WithValue(
                $"\nOnline: {onlineBots}" +
                $"\nOffline: {offlineBots}");
            onlineMessage.AddField(botBuilder);

            await Context.Channel.SendMessageAsync("", false, onlineMessage.Build());
        }
Пример #25
0
        public async Task HelpAsync([Optional] params string[] query)
        {
            try
            {
                List <EmbedFieldBuilder> fieldBuilders = new List <EmbedFieldBuilder>();
                string footerText;
                if (query.Length == 0)
                {
                    footerText = "Use `b!help [moduleName]` to get an in-depth prompt.";
                    foreach (var item in _commands.Modules.Where(m => m.Parent is null))
                    {
                        if (item.Commands.Count == 0)
                        {
                            continue;
                        }

                        StringBuilder     commandsBuilder = new StringBuilder();
                        EmbedFieldBuilder fieldBuilder    = new EmbedFieldBuilder();
                        fieldBuilder.WithIsInline(false)
                        .WithName(item.Name);

                        foreach (var cmd in item.Commands)
                        {
                            commandsBuilder.Append($"`{cmd.Name}`, ");
                        }
                        fieldBuilder.WithValue(commandsBuilder.ToString().Remove(commandsBuilder.Length - 2));
                        fieldBuilders.Add(fieldBuilder);
                    }

                    EmbedBuilder embedBuilder = new EmbedBuilder();
                    embedBuilder.WithDescription("Here are the commands:")
                    .WithTitle("Help")
                    .WithFields(fieldBuilders)
                    .WithFooter(footerText)
                    .WithThumbnailUrl(Context.Client.CurrentUser.GetAvatarUrl())
                    .WithColor(Color.DarkOrange);
                    await ReplyAsync("", false, embedBuilder.Build());

                    //await ReplyAsync(strBuilder.ToString());
                    return;
                }
                else
                {
                    EmbedBuilder embedBuilder = new EmbedBuilder();

                    string moduleName = query.ParseText();
                    bool   success    = false;

                    foreach (var item in _commands.Modules.Where(m => m.Parent is null))
                    {
                        if (moduleName.ToLower().Replace("ı", "i") != item.Name.ToLower().Replace("ı", "i"))
                        {
                            continue;
                        }
                        embedBuilder.WithTitle(item.Name + " Commands");
                        foreach (var cmd in item.Commands)
                        {
                            EmbedFieldBuilder fieldBuilder     = new EmbedFieldBuilder();
                            StringBuilder     usageSummBuilder = new StringBuilder();

                            usageSummBuilder.Append(cmd.Summary + Environment.NewLine)
                            .Append("**Usage:** ");
                            string temp = "";
                            foreach (var arg in cmd.Parameters)
                            {
                                temp = temp + $"<{arg.Name}>" + " ";
                            }
                            usageSummBuilder.Append($"`{ (cmd.Name + " " + temp).TrimEnd() }`" + Environment.NewLine);

                            fieldBuilder.WithIsInline(false)
                            .WithName(cmd.Name)
                            .WithValue(usageSummBuilder.ToString());
                            fieldBuilders.Add(fieldBuilder);
                        }
                        success = true;
                    }
                    if (!success)
                    {
                        await ReplyAsync("Such module doesn't exist.");

                        return;
                    }

                    embedBuilder.WithFields(fieldBuilders)
                    .WithColor(Color.DarkOrange);

                    await ReplyAsync("", false, embedBuilder.Build());

                    //await ReplyAsync(usageSummBuilder.ToString());
                    return;
                }
            }
            catch (Exception ex)
            {
                await StaticMethods.ExceptionHandler(ex, Context);

                return;
            }
        }
Пример #26
0
        //Type is what you are giving away (Rank, kit, key, etc.)
        public async Task gAway(string time, string prize, string type)
        {
            Console.WriteLine("Starting giveaway");
            int t = Int32.Parse(time.Remove(time.Length - 1));


            //Starts the Embeded Message
            MyEmbedBuilder.WithColor(new Color(255, 255, 0));
            var Name = MyEmbedField.WithName(":game_die: **GIVEAWAY**  :game_die:");

            MyEmbedField.WithIsInline(true);


            //Changes message if time is seconds or minutes
            if (time.Contains('h'))
            {
                var msg = MyEmbedField.WithValue("Free " + "***" + prize + "***" + " " + type + "\nReact with :cdicon2: to win!\n" + "Time remaining: " + t.ToString() + " hours");
                t = t * 3600;
            }
            if (time.Contains('m'))
            {
                var msg = MyEmbedField.WithValue("Free " + "***" + prize + "***" + " " + type + "\nReact with :cdicon2: to win!\n" + "Time remaining: " + t.ToString() + " minutes");

                t = t * 60;
            }
            else
            {
                var msg = MyEmbedField.WithValue("Free " + "***" + prize + "***" + " " + type + "\nReact with :cdicon2: to win!\n" + "Time remaining: " + t.ToString() + " seconds");
            }



            //Sends message
            MyEmbedBuilder.AddField(MyEmbedField);
            var message = await Context.Channel.SendMessageAsync("", false, MyEmbedBuilder.Build());

            //Reacts to message
            await message.AddReactionAsync(dice);

            //Begins countdown and edits embeded field every hour, minute, or second
            while (t > 0)
            {
                await Task.Delay(1000);

                Console.WriteLine(t);
                t--;
                var newMessage = await message.Channel.GetMessageAsync(message.Id) as IUserMessage;

                var embed2 = new EmbedBuilder();
                embed2.AddField(Name);
                embed2.WithColor(new Color(255, 255, 0));

                if (t >= 3600)
                {
                    int t3 = t;
                    t3 = t3 / 3600;
                    int time_minutes = t;
                    time_minutes = (t / 60) % 60;

                    MyEmbedField.WithValue("Free " + "***" + prize + "***" + " " + type + "!" + "\nReact with :game_die: to win!\n" + "Time remaining: " + t3.ToString() + " hours " + time_minutes + " minutes");
                }
                if (t >= 60 && t < 3600)
                {
                    int t2 = t;
                    t2 = t2 / 60;
                    int time_seconds = t % 60;
                    MyEmbedField.WithValue("Free " + "***" + prize + "***" + " " + type + "!" + "\nReact with :game_die: to win!\n" + "Time remaining: " + t2.ToString() + " minutes " + time_seconds + " seconds");
                }

                if (t < 60)
                {
                    MyEmbedField.WithValue("Free " + "***" + prize + "***" + " " + type + "!" + "\nReact with :game_die: to win!\n" + "Time remaining: " + t.ToString() + " seconds");
                }
                await newMessage.ModifyAsync(m => m.Embed = embed2.Build());
            }


            //Adds users to list and randomly selects winner
            await message.RemoveReactionAsync(dice, message.Author);

            IReadOnlyCollection <IUser> temp = await message.GetReactionUsersAsync("🎲");

            if (temp.Count() > 0)
            {
                IUser winner   = temp.ElementAt(rand.Next(temp.Count));
                var   message3 = await message.Channel.GetMessageAsync(message.Id) as IUserMessage;

                var embed3 = new EmbedBuilder();
                embed3.AddField(Name);
                embed3.WithColor(new Color(255, 255, 0));

                MyEmbedField.WithValue("***Congratulations*** " + "! " + winner.Mention + " You won the free " + prize + " " + type + "!");
                await message3.ModifyAsync(m => m.Embed = embed3.Build());

                await message3.AddReactionAsync(trophy);
            }
            else
            {
                var message4 = await message.Channel.GetMessageAsync(message.Id) as IUserMessage;

                var embed4 = new EmbedBuilder();
                embed4.AddField(Name);
                embed4.WithColor(new Color(255, 255, 0));

                MyEmbedField.WithValue("There are no winners today :)");
                await message4.ModifyAsync(m => m.Embed = embed4.Build());

                await message4.AddReactionAsync(trophy);
            }
        }
        public async Task SendEmbedFromCli(CommandArguments cmdArgs, IUser pmInstead = null)
        {
            if (string.IsNullOrEmpty(cmdArgs.TrimmedMessage) || cmdArgs.TrimmedMessage == "-h" || cmdArgs.TrimmedMessage == "--help")
            {
                await cmdArgs.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
                                            "[ --channel     ] Channel where to send the embed.\n" +
                                            "[ --edit <msgId>] Replace a MessageId with a new embed (use after --channel)\n" +
                                            "[ --text        ] Regular content text\n" +
                                            "[ --title       ] Title\n" +
                                            "[ --description ] Description\n" +
                                            "[ --footer      ] Footer\n" +
                                            "[ --color       ] #rrggbb hex color used for the embed stripe.\n" +
                                            "[ --image       ] URL of a Hjuge image in the bottom.\n" +
                                            "[ --thumbnail   ] URL of a smol image on the side.\n" +
                                            "[ --fieldName   ] Create a new field with specified name.\n" +
                                            "[ --fieldValue  ] Text value of a field - has to follow a name.\n" +
                                            "[ --fieldInline ] Use to set the field as inline.\n" +
                                            "Where you can repeat the field* options multiple times.\n```"
                                            );

                return;
            }

            SocketTextChannel channel = null;

            bool              debug        = false;
            string            text         = null;
            IMessage          msg          = null;
            EmbedFieldBuilder currentField = null;
            EmbedBuilder      embedBuilder = new EmbedBuilder();

            foreach (Match match in this.RegexCliParam.Matches(cmdArgs.TrimmedMessage))
            {
                string optionString = this.RegexCliOption.Match(match.Value).Value;

                if (optionString == "--debug")
                {
                    if (IsGlobalAdmin(cmdArgs.Message.Author.Id) || IsSupportTeam(cmdArgs.Message.Author.Id))
                    {
                        debug = true;
                    }
                    continue;
                }

                if (optionString == "--fieldInline")
                {
                    if (currentField == null)
                    {
                        await cmdArgs.SendReplySafe($"`fieldInline` can not precede `fieldName`.");

                        return;
                    }

                    currentField.WithIsInline(true);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Setting inline for field `{currentField.Name}`");
                    }
                    continue;
                }

                string value;
                if (match.Value.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = match.Value.Substring(optionString.Length + 1).Trim()))
                {
                    await cmdArgs.SendReplySafe($"Invalid value for `{optionString}`");

                    return;
                }

                if (value.Length >= UserProfileOption.ValueCharacterLimit)
                {
                    await cmdArgs.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                    return;
                }

                switch (optionString)
                {
                case "--channel":
                    if (!guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = cmdArgs.Server.Guild.GetTextChannel(id)) == null)
                    {
                        await cmdArgs.SendReplySafe($"Channel {value} not found.");

                        return;
                    }

                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Channel set: `{channel.Name}`");
                    }

                    break;

                case "--text":
                    if (value.Length > GlobalConfig.MessageCharacterLimit)
                    {
                        await cmdArgs.SendReplySafe($"`--text` is too long (`{value.Length} > {GlobalConfig.MessageCharacterLimit}`)");

                        return;
                    }

                    text = value;
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Text set: `{value}`");
                    }

                    break;

                case "--title":
                    if (value.Length > 256)
                    {
                        await cmdArgs.SendReplySafe($"`--title` is too long (`{value.Length} > 256`)");

                        return;
                    }

                    embedBuilder.WithTitle(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Title set: `{value}`");
                    }

                    break;

                case "--description":
                    if (value.Length > 2048)
                    {
                        await cmdArgs.SendReplySafe($"`--description` is too long (`{value.Length} > 2048`)");

                        return;
                    }

                    embedBuilder.WithDescription(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Description set: `{value}`");
                    }

                    break;

                case "--footer":
                    if (value.Length > 2048)
                    {
                        await cmdArgs.SendReplySafe($"`--footer` is too long (`{value.Length} > 2048`)");

                        return;
                    }

                    embedBuilder.WithFooter(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Description set: `{value}`");
                    }

                    break;

                case "--image":
                    try
                    {
                        embedBuilder.WithImageUrl(value.Trim('<', '>'));
                    }
                    catch (Exception)
                    {
                        await cmdArgs.SendReplySafe($"`--image` is invalid url");

                        return;
                    }

                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Image URL set: `{value}`");
                    }

                    break;

                case "--thumbnail":
                    try
                    {
                        embedBuilder.WithThumbnailUrl(value.Trim('<', '>'));
                    }
                    catch (Exception)
                    {
                        await cmdArgs.SendReplySafe($"`--thumbnail` is invalid url");

                        return;
                    }

                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Thumbnail URL set: `{value}`");
                    }

                    break;

                case "--color":
                    try
                    {
                        uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                        if (color > uint.Parse("FFFFFF", System.Globalization.NumberStyles.AllowHexSpecifier))
                        {
                            await cmdArgs.SendReplySafe("Color out of range.");

                            return;
                        }

                        embedBuilder.WithColor(color);
                        if (debug)
                        {
                            await cmdArgs.Channel.SendMessageSafe($"Color `{value}` set.");
                        }
                    }
                    catch (Exception)
                    {
                        await cmdArgs.SendReplySafe("Invalid color format.");

                        return;
                    }
                    break;

                case "--fieldName":
                    if (value.Length > 256)
                    {
                        await cmdArgs.SendReplySafe($"`--fieldName` is too long (`{value.Length} > 256`)\n```\n{value}\n```");

                        return;
                    }

                    if (currentField != null && currentField.Value == null)
                    {
                        await cmdArgs.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                        return;
                    }

                    if (embedBuilder.Fields.Count >= 25)
                    {
                        await cmdArgs.SendReplySafe("Too many fields! (Limit is 25)");

                        return;
                    }

                    embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Creating new field `{currentField.Name}`");
                    }

                    break;

                case "--fieldValue":
                    if (value.Length > 1024)
                    {
                        await cmdArgs.SendReplySafe($"`--fieldValue` is too long (`{value.Length} > 1024`)\n```\n{value}\n```");

                        return;
                    }

                    if (currentField == null)
                    {
                        await cmdArgs.SendReplySafe($"`fieldValue` can not precede `fieldName`.");

                        return;
                    }

                    currentField.WithValue(value);
                    if (debug)
                    {
                        await cmdArgs.Channel.SendMessageSafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
                    }

                    break;

                case "--edit":
                    if (!guid.TryParse(value, out guid msgId) || (msg = await channel?.GetMessageAsync(msgId)) == null)
                    {
                        await cmdArgs.SendReplySafe($"`--edit` did not find a message with ID `{value}` in the <#{(channel?.Id ?? 0)}> channel.");

                        return;
                    }

                    break;

                default:
                    await cmdArgs.SendReplySafe($"Unknown option: `{optionString}`");

                    return;
                }
            }

            if (currentField != null && currentField.Value == null)
            {
                await cmdArgs.SendReplySafe($"Field `{currentField.Name}` is missing a value!");

                return;
            }

            switch (msg)
            {
            case null:
                if (pmInstead != null)
                {
                    await pmInstead.SendMessageAsync(text : text, embed : embedBuilder.Build());
                }
                else if (channel == null)
                {
                    await cmdArgs.SendReplySafe(text : text, embed : embedBuilder.Build());
                }
                else
                {
                    await channel.SendMessageAsync(text : text, embed : embedBuilder.Build());
                }
                break;

            case RestUserMessage message:
                await message?.ModifyAsync(m => {
                    m.Content = text;
                    m.Embed   = embedBuilder.Build();
                });

                break;

            case SocketUserMessage message:
                await message?.ModifyAsync(m => {
                    m.Content = text;
                    m.Embed   = embedBuilder.Build();
                });

                break;

            default:
                await cmdArgs.SendReplySafe("GetMessage went bork.");

                break;
            }
        }
Пример #28
0
        public async Task Help()
        {
            bool isAdmin = false;

            SocketGuildUser user = _client.GetGuild(Context.Guild.Id).GetUser(Context.User.Id);

            foreach (SocketRole role in user.Roles)
            {
                if (role.Name == "Admin")
                {
                    isAdmin = true;
                }
            }

            //await ReplyAsync(output);
            var eb            = new EmbedBuilder();
            var eb2           = new EmbedBuilder();
            var eb3           = new EmbedBuilder();
            var eb4           = new EmbedBuilder();
            var adminEmbed    = new EmbedBuilder();
            var settingsEmbed = new EmbedBuilder();

            //general commands
            EmbedFieldBuilder GeneralHelpCommandField = new EmbedFieldBuilder();

            GeneralHelpCommandField.Name  = "General Help";
            GeneralHelpCommandField.Value = "`-Help`\n`-About`";
            GeneralHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder GeneralHelpDescriptionField = new EmbedFieldBuilder();

            GeneralHelpDescriptionField.Name     = "Description";
            GeneralHelpDescriptionField.IsInline = true;
            GeneralHelpDescriptionField.Value    = "This command.\nGeneral information about this bot.";

            //coord commands
            EmbedFieldBuilder CoordHelpCommandField = new EmbedFieldBuilder();

            CoordHelpCommandField.Name  = "Coordination Commands";
            CoordHelpCommandField.Value = "`-StartGames`\n`-ChangeCoord <user#1111>`\n`-AddP <s, z> <username>`\n" +
                                          "`-AddR <username>`\n`-Remove <username>`\n`-NewRound`\n`-StopGames`";
            CoordHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder CoordHelpDescriptionField = new EmbedFieldBuilder();

            CoordHelpDescriptionField.Name     = "Description";
            CoordHelpDescriptionField.IsInline = true;
            CoordHelpDescriptionField.Value    = "Starts games of Castle Wars or Soul Wars.\nChanges the coordinator of the game.\n" +
                                                 "Adds a perm member to either team.\nAdds a rotating member to available team.\nRemoves a user from the games.\n" +
                                                 "Use this at the start of each round to switch teams.\nThis closes the games.";

            //geobie commands
            EmbedFieldBuilder GeobieHelpCommandField = new EmbedFieldBuilder();

            GeobieHelpCommandField.Name  = "Goebiebands Commands";
            GeobieHelpCommandField.Value = "`-s <world> <type> <user>`\n`-dead <world>`\n`-removeworld <world>`";
            GeobieHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder GeobieHelpDescriptionField = new EmbedFieldBuilder();

            GeobieHelpDescriptionField.Name     = "Description";
            GeobieHelpDescriptionField.IsInline = true;
            GeobieHelpDescriptionField.Value    = "Registers a scout. Types: a, f, w.\nMark a world dead.\nRemoves a world from the list.";

            //warbands commands
            EmbedFieldBuilder WarbandsHelpCommandField = new EmbedFieldBuilder();

            WarbandsHelpCommandField.Name  = "Warbands Commands";
            WarbandsHelpCommandField.Value = "`-w <world> <type>`\n`-ClearWarbands`";
            WarbandsHelpCommandField.WithIsInline(true);
            EmbedFieldBuilder WarbandsHelpDescriptionField = new EmbedFieldBuilder();

            WarbandsHelpDescriptionField.Name     = "Description";
            WarbandsHelpDescriptionField.IsInline = true;
            WarbandsHelpDescriptionField.Value    = "Adds or edits a world.\nClears the current list.";

            //admin embed
            EmbedFieldBuilder GeobieAdminCommandField = new EmbedFieldBuilder();

            GeobieAdminCommandField.Name  = "Goebiebands Commands";
            GeobieAdminCommandField.Value = "`-clearinfo`\n`-outputtotals`\n`-ResetDaily`\n`-clearinfomonthly`";
            GeobieAdminCommandField.WithIsInline(true);
            EmbedFieldBuilder GeobieAdminDescriptionField = new EmbedFieldBuilder();

            GeobieAdminDescriptionField.Name     = "Description";
            GeobieAdminDescriptionField.IsInline = true;
            GeobieAdminDescriptionField.Value    = "`Clears the current Goebiebands info`\n`Prints out total number of scouts per user`\n`Resets the day's progress`" +
                                                   "\n`Clears all information`";

            EmbedFieldBuilder FCAdminCommands = new EmbedFieldBuilder();

            FCAdminCommands.Name  = "FC Commands";
            FCAdminCommands.Value = "`-See <username>`\n`-printlist`\n`-promotions`\n`-clearfc`\n`-dailyreset`";
            FCAdminCommands.WithIsInline(true);
            EmbedFieldBuilder FCAdminDescription = new EmbedFieldBuilder();

            FCAdminDescription.Name     = "Description";
            FCAdminDescription.IsInline = true;
            FCAdminDescription.Value    = "`Marks the user as seen`\n`Prints the list`\n`Prints promotions`\n`Clears all info`\n`Resets daily progress`";

            //settings commands
            EmbedFieldBuilder SettingsCommandField = new EmbedFieldBuilder();

            SettingsCommandField.Name  = "Settings Commands";
            SettingsCommandField.Value = "`-settings warbandsserver <ser id>`\n`-settings minigamesserver <ser id>`\n" +
                                         "`-settings mcastlewarschannel <ch id>`\n`-settings mgeobiechannel <ch id>`\n`-settings " +
                                         "mwarbandschannel <ch id>`\n`-settings wwarbandschannel <ch id>`\n`-settings addadminid <user id>`\n" +
                                         "`-settings removeadminid <user id>`\n`-settings SetFcPromotionLimit <num>`";
            SettingsCommandField.WithIsInline(true);
            EmbedFieldBuilder SettingsDescriptionField = new EmbedFieldBuilder();

            SettingsDescriptionField.Name     = "Description";
            SettingsDescriptionField.IsInline = true;
            SettingsDescriptionField.Value    = "`Sets the warbands server`\n`Sets the minigames server`\n`Sets the minigames cws channel`\n" +
                                                "`Sets the minigames geobie channel`\n`Sets the minigames wbs channel`\n`Sets the warbands wbs channel`\n" +
                                                "`Adds a bot admin`\n`Removes a bot admin`\n`Sets number needed for promotion`";

            //add embed fields to the builders
            eb.AddField(GeneralHelpCommandField);
            eb.AddField(GeneralHelpDescriptionField);
            eb2.AddField(CoordHelpCommandField);
            eb2.AddField(CoordHelpDescriptionField);
            eb3.AddField(GeobieHelpCommandField);
            eb3.AddField(GeobieHelpDescriptionField);
            eb4.AddField(WarbandsHelpCommandField);
            eb4.AddField(WarbandsHelpDescriptionField);
            adminEmbed.AddField(GeobieAdminCommandField);
            adminEmbed.AddField(GeobieAdminDescriptionField);
            adminEmbed.AddField(FCAdminCommands);
            adminEmbed.AddField(FCAdminDescription);
            settingsEmbed.AddField(SettingsCommandField);
            settingsEmbed.AddField(SettingsDescriptionField);

            await ReplyAsync("", false, eb);
            await ReplyAsync("", false, eb2);
            await ReplyAsync("", false, eb3);
            await ReplyAsync("", false, eb4);

            if (isAdmin)
            {
                IDMChannel userChannel = await Context.User.GetOrCreateDMChannelAsync();

                await userChannel.SendMessageAsync("", false, adminEmbed);
            }

            if (Config.ADMIN_ID.Contains(Context.User.Id))
            {
                IDMChannel userChannel = await Context.User.GetOrCreateDMChannelAsync();

                await userChannel.SendMessageAsync("", false, settingsEmbed);
            }
        }
Пример #29
0
        public async Task RunGiveaway(int seconds, string prize, int numWinners, ICommandContext context, Action <ulong> removeInstance)
        {
            //Starts the Embeded Message
            MyEmbedBuilder.WithColor(Color.DarkBlue);
            var Name = MyEmbedField.WithName(":game_die: **GIVEAWAY**  :game_die:");

            MyEmbedField.WithIsInline(true);

            var msg = MyEmbedField.WithValue($"Prize: ***{prize}***\nReact with {dice} to win!\nTime remaining: {seconds} seconds");

            //Sends message
            MyEmbedBuilder.AddField(MyEmbedField);
            var message = await context.Channel.SendMessageAsync("", false, MyEmbedBuilder.Build());

            //Reacts to message
            await message.AddReactionAsync(dice);

            //Begins countdown and edits embeded field every hour, minute, or second
            while (seconds > 0)
            {
                await Task.Delay(5000);

                seconds -= 5;
                var countdownEmbed = new EmbedBuilder();
                countdownEmbed.AddField(Name);
                countdownEmbed.WithColor(Color.DarkBlue);
                MyEmbedField.WithValue($"Prize: ***{prize}***\nReact with {dice} to win!\nTime remaining: {seconds} seconds");
                if (isCancel)
                {
                    MyEmbedField.WithValue($"GIVEAWAY CANCELLED!");
                    await message.ModifyAsync(m => m.Embed = countdownEmbed.Build());

                    removeInstance(channelId);
                    return;
                }
                await message.ModifyAsync(m => m.Embed = countdownEmbed.Build());
            }

            //Adds users to list and randomly selects winner
            await message.RemoveReactionAsync(dice, message.Author);

            var temp = await message.GetReactionUsersAsync(dice, 500).FlattenAsync();

            var finalEmbed = new EmbedBuilder();

            finalEmbed.AddField(Name);
            finalEmbed.WithColor(new Color(255, 255, 0));

            if (temp.Any())
            {
                List <IUser>  winners      = new List <IUser>();
                StringBuilder winnersList  = new StringBuilder();
                List <IUser>  participants = temp.ToList();

                if (numWinners > participants.Count())
                {
                    numWinners = participants.Count();
                }

                for (int i = 0; i < numWinners; i++)
                {
                    var randNum = rand.Next(participants.Count());
                    var winner  = participants.ElementAt(randNum);

                    winners.Add(winner);
                    var formattedWinner = (numWinners == 1 || (i == numWinners - 1)) ? $"{winner.Mention}" : $"{winner.Mention}, ";
                    winnersList.Append(formattedWinner);

                    participants.RemoveAt(randNum);

                    if (!participants.Any())
                    {
                        break;
                    }
                }
                MyEmbedField.WithValue($"***Congratulations***! {winnersList.ToString()}. You won ***{prize}***!");
                await message.ModifyAsync(m => m.Embed = finalEmbed.Build());

                await message.AddReactionAsync(trophy);
            }
            else
            {
                MyEmbedField.WithValue("There are no winners today");
                await message.ModifyAsync(m => m.Embed = finalEmbed.Build());

                await message.AddReactionAsync(trophy);
            }
            removeInstance(channelId);
        }
Пример #30
0
        public async Task Calendar()
        {
            if (Context.Guild == null)
            {
                //Text was send by DM, not supported
                string helptext = "Please use this command in a text channel of your server, not via DM. This will be fixed in a later release.";

                var channel = await Context.User.GetOrCreateDMChannelAsync();

                await channel.SendMessageAsync(helptext);
            }
            else
            {
                EmbedBuilder MyEmbedBuilder = new EmbedBuilder();
                MyEmbedBuilder.WithColor(new Color(43, 234, 152));
                MyEmbedBuilder.WithTitle("Planned Events");

                MyEmbedBuilder.WithDescription("These are our upcoming events:");

                MyEmbedBuilder.WithThumbnailUrl("https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-512.png");
                //MyEmbedBuilder.WithImageUrl("https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-512.png");

                //Footer
                EmbedFooterBuilder MyFooterBuilder = new EmbedFooterBuilder();
                MyFooterBuilder.WithText("You can get more information on an event by using !event *eventid* -- DM the bot with !help to get a command overview.");
                MyFooterBuilder.WithIconUrl("https://vignette2.wikia.nocookie.net/mario/images/f/f6/Question_Block_Art_-_New_Super_Mario_Bros.png/revision/latest?cb=20120603213532");
                MyEmbedBuilder.WithFooter(MyFooterBuilder);

                //Author
                EmbedAuthorBuilder MyAuthorBuilder = new EmbedAuthorBuilder();
                MyAuthorBuilder.WithName($"{Context.Guild.Name}'s Schedule");
                //MyAuthorBuilder.WithUrl("http://www.google.com");
                MyEmbedBuilder.WithAuthor(MyAuthorBuilder);

                foreach (CalendarEvent Event in CalendarXMLManagement.arrEvents)
                {
                    if (Event.Active & (Context.Guild.Id == Event.EventGuild & (Event.EventDate.Date >= DateTime.UtcNow.Date) | Event.PublicEvent))
                    {
                        string sType = null;
                        if (Event.PublicEvent)
                        {
                            sType = "Public";
                        }
                        else
                        {
                            sType = "Internal";
                        }

                        //EmbedField
                        EmbedFieldBuilder MyEmbedField = new EmbedFieldBuilder();
                        MyEmbedField.WithIsInline(true);
                        MyEmbedField.WithName(Event.Eventname + $" ({sType})");
                        MyEmbedField.WithValue(
                            $"Date: **{Event.EventDate.ToShortDateString()} **\n" +
                            $"Time: **{Event.EventDate.ToShortTimeString()} UTC**\n" +
                            $"Attendees: **{Event.Attendees.Count}**\n" +
                            $"ID: **{Event.EventID}**\n");

                        //if (Event.MaxAttendees == 0)
                        //{
                        //    sEmbedDescription += $"Attendees: **{sAttendees}**\n";
                        //}
                        //else
                        //{
                        //    sEmbedDescription += $"Attendees: **{sAttendees}/{E}**\n";
                        //}

                        MyEmbedBuilder.AddField(MyEmbedField);
                    }
                }

                await ReplyAsync("", false, MyEmbedBuilder);
            }
        }