Exemplo n.º 1
0
        public async Task Weather(IUserMessage umsg, string city, string country)
        {
            var channel = (ITextChannel)umsg.Channel;
            city = city.Replace(" ", "");
            country = city.Replace(" ", "");
            string response;
            using (var http = new HttpClient())
                response = await http.GetStringAsync($"http://api.ninetales.us/nadekobot/weather/?city={city}&country={country}").ConfigureAwait(false);

            var obj = JObject.Parse(response)["weather"];

            var embed = new EmbedBuilder()
                .AddField(fb => fb.WithName("🌍 Location").WithValue($"{obj["target"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("📏 Lat,Long").WithValue($"{obj["latitude"]}, {obj["longitude"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("☁ Condition").WithValue($"{obj["condition"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("😓 Humidity").WithValue($"{obj["humidity"]}%").WithIsInline(true))
                .AddField(fb => fb.WithName("💨 Wind Speed").WithValue($"{obj["windspeedk"]}km/h / {obj["windspeedm"]}mph").WithIsInline(true))
                .AddField(fb => fb.WithName("🌡 Temperature").WithValue($"{obj["centigrade"]}°C / {obj["fahrenheit"]}°F").WithIsInline(true))
                .AddField(fb => fb.WithName("🔆 Feels like").WithValue($"{obj["feelscentigrade"]}°C / {obj["feelsfahrenheit"]}°F").WithIsInline(true))
                .AddField(fb => fb.WithName("🌄 Sunrise").WithValue($"{obj["sunrise"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("🌇 Sunset").WithValue($"{obj["sunset"]}").WithIsInline(true))
                .WithColor(NadekoBot.OkColor);
            await channel.EmbedAsync(embed.Build()).ConfigureAwait(false);
        }
Exemplo n.º 2
0
 public bool Build(out EmbedBuilder embed, out string messageContent, out string error)
 {
     ArgumentParseResult parseResult = EmbedHelper.TryParseEmbedFromJSONObject(JSON, out embed, out messageContent);
     error = parseResult.Message;
     return parseResult.Success;
 }
Exemplo n.º 3
0
        public async Task Players([Remainder] string serverName)
        {
            serverName = serverName.ToLower();

            IEnumerable <GameServerInfo> servers = await AltaApi.ApiClient.ServerClient.GetOnlineServersAsync();

            StringBuilder response = new StringBuilder();

            response.AppendLine("Did you mean one of these?");

            foreach (GameServerInfo server in servers)
            {
                response.AppendLine(server.Name);

                if (Regex.Match(server.Name, @"\b" + serverName + @"\b", RegexOptions.IgnoreCase).Success)
                {
                    SocketGuildUser guildUser = Context.User as SocketGuildUser;

                    if ((guildUser == null || !guildUser.GuildPermissions.ManageChannels) && Regex.Match(server.Name, "pvp", RegexOptions.IgnoreCase).Success)
                    {
                        await ReplyAsync("PvP Player List is disabled");

                        return;
                    }

                    response.Clear();

                    EmbedBuilder tempBuilder = new EmbedBuilder();

                    tempBuilder.AddField("Name", server.Name);
                    tempBuilder.AddField("Type", (Map)server.SceneIndex);
                    tempBuilder.AddField("Players", server.OnlinePlayers.Count());

                    foreach (UserInfo user in server.OnlinePlayers)
                    {
                        MembershipStatusResponse membershipResponse = await AltaApi.ApiClient.UserClient.GetMembershipStatus(user.Identifier);

                        response.AppendFormat("- {1}{0}\n", user.Username, membershipResponse.IsMember ? "<:Supporter:547252984481054733> " : "");
                    }

                    tempBuilder.WithDescription(response.ToString());
                    await ReplyAsync("", embed : tempBuilder.Build());

                    return;
                }
            }
            string[] lines   = response.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            string   message = "";

            for (int i = 0; i < lines.Length; i++)
            {
                if (message.Length + lines[i].Length < 2000)
                {
                    message += $"{lines[i]}\n";
                }
                else
                {
                    await ReplyAsync($"{message}");

                    message = "";
                }
            }
            //await ReplyAsync(response.ToString());
        }
 public static EmbedBuilder WithRandomColor(this EmbedBuilder embedBuilder)
 {
     return(embedBuilder.WithColor(Colors[Random.Next() % Colors.Length]));
 }
Exemplo n.º 5
0
        public async Task InitialiseWelcome(int option = 0)
        {
            int input;

            if (option == 0)
            {
                await ReplyAsync("```\n" +
                                 "Reply with the command you would like to perform\n" +
                                 "[1] Set the welcome message\n" +
                                 "[2] Set the current channel for welcome events\n" +
                                 "[3] Enable the welcome event\n" +
                                 "[4] Disable the welcome event\n" +
                                 "[5] View Welcome Info" +
                                 "" +
                                 "```");

                var next = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                input = int.Parse(next.Content);
            }
            else
            {
                input = option;
            }

            var Guild = GuildConfig.GetServer(Context.Guild);

            if (input == 1)
            {
                await ReplyAsync(
                    "Please reply with the welcome message you want to be sent when a user joins the server ie. `Welcome to Our Server!!`");

                var next2 = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                Guild.WelcomeMessage = next2.Content;
                Guild.WelcomeChannel = Context.Channel.Id;
                await ReplyAsync("The Welcome Message for this server has been set to:\n" +
                                 $"**{next2.Content}**\n" +
                                 $"In the channel **{Context.Channel.Name}**");
            }
            else if (input == 2)
            {
                Guild.WelcomeChannel = Context.Channel.Id;
                await ReplyAsync($"Welcome Events will be sent in the channel: **{Context.Channel.Name}**");
            }
            else if (input == 3)
            {
                Guild.WelcomeEvent = true;
                await ReplyAsync("Welcome Messageing for this server has been set to: true");
            }
            else if (input == 4)
            {
                Guild.WelcomeEvent = false;
                await ReplyAsync("Welcome Messageing for this server has been set to: false");
            }
            else if (input == 5)
            {
                var embed = new EmbedBuilder();
                try
                {
                    embed.AddField("Message", Guild.WelcomeMessage);
                    embed.AddField("Channel", Context.Guild.GetChannel(Guild.WelcomeChannel).Name);
                    embed.AddField("Status", Guild.WelcomeEvent ? "On" : "Off");
                    await ReplyAsync("", false, embed.Build());
                }
                catch
                {
                    await ReplyAsync(
                        "Error, this guilds welcome config is not fully set up yet, please consider using options 1 thru 4 first");
                }
            }
            else
            {
                await ReplyAsync("ERROR: you did not supply a valid option. type only `1` etc.");
            }

            GuildConfig.SaveServer(Guild);
        }
Exemplo n.º 6
0
        /// <summary>
        ///     Checks contents of non-command messages for miscellaneous functionality.
        /// </summary>
        /// <remarks>
        ///     Mostly used for shit posting, but also does useful things like nag users to use more up to date tools, or
        ///     automatically answer some simple questions.
        /// </remarks>
        /// <param name="message">The message to check.</param>
        private async void Listen(SocketMessage message)
        {
            // Don't want to listen to what a bot tells us to do
            if (message.Author.IsBot)
            {
                return;
            }

            //Handle Pastebin Message

            /*
             * Disabled since Discord added large message embeds
             * if (message.Attachments.Count == 1)
             * {
             *  var file = message.Attachments.FirstOrDefault();
             *
             *  //Should never be null, but better safe than sorry.
             *  if (file == null)
             *      return;
             *
             *  if (file.Filename.Equals("message.txt", StringComparison.OrdinalIgnoreCase) ||
             *      file.Filename.EndsWith(".log", StringComparison.OrdinalIgnoreCase))
             *      await LargeMessage(file);
             * }*/

            // Embed Steam workshop links
            if (message.Content.Contains("://steamcommunity.com/sharedfiles/filedetails/",
                                         StringComparison.OrdinalIgnoreCase) || message.Content.Contains(
                    "://steamcommunity.com/workshop/filedetails/", StringComparison.OrdinalIgnoreCase))
            {
                var workshop = new Workshop(_dataService, _log);
                await workshop.SendWorkshopEmbed(message);

                return;
            }

            // Listen for specific user questions, then answer them if we can
            // Listen for carve messages
            if (_dataService.RSettings.AutoReplies.Carve.Any(s => message.Content.ToLower().Contains(s)))
            {
                await Carve();

                return;
            }

            // Listen for packing questions
            if (_dataService.RSettings.AutoReplies.Packing.Any(s => message.Content.ToLower().Contains(s)))
            {
                await Packing();

                return;
            }

            // Tell users that pakrat is bad
            if (_dataService.RSettings.AutoReplies.Pakrat.Any(s => message.Content.ToLower().Contains(s)))
            {
                await Pakrat();

                return;
            }

            // Recommend WallWorm over propper
            if (_dataService.RSettings.AutoReplies.Propper.Any(s => message.Content.ToLower().Contains(s)))
            {
                await Propper();
            }

            /// <summary>
            /// Shames users for asking about carve.
            /// </summary>
            /// <param name="message"></param>
            /// <returns></returns>
            async Task Carve()
            {
                var carveEmbed = new EmbedBuilder()
                                 .WithAuthor($"Hey there {message.Author.Username}!", message.Author.GetAvatarUrl())
                                 .WithTitle("DO NOT USE CARVE!")
                                 .WithThumbnailUrl("https://i.ytimg.com/vi/xh9Kr2iO4XI/maxresdefault.jpg")
                                 .WithDescription(
                    "You were asking about carve. We don't use carve here. Not only does it create bad brushwork, but it " +
                    "can also cause Hammer to stop responding and crash. If you're here trying to defend using carve, just stop - you are wrong.")
                                 .WithColor(new Color(243, 128, 72));

                await message.Channel.SendMessageAsync(embed : carveEmbed.Build());
            }

            /// <summary>
            /// Tells users how to pack custom content.
            /// </summary>
            /// <param name="message"></param>
            /// <returns></returns>
            async Task Packing()
            {
                var packingEmbed = new EmbedBuilder()
                                   .WithAuthor($"Hey there {message.Author.Username}!", message.Author.GetAvatarUrl())
                                   .WithTitle("Click here to learn how to use VIDE!")
                                   .WithUrl("https://www.tophattwaffle.com/packing-custom-content-using-vide-in-steampipe/")
                                   .WithThumbnailUrl("https://www.tophattwaffle.com/wp-content/uploads/2013/11/vide.png")
                                   .WithDescription(
                    "I noticed you may be looking for information on how to pack custom content into your level. " +
                    "This is easily done using VIDE. Click the link above to download VIDE and learn how to use it.")
                                   .WithColor(new Color(243, 128, 72));

                await message.Channel.SendMessageAsync(embed : packingEmbed.Build());
            }

            /// <summary>
            /// Nags users to not use pakrat.
            /// </summary>
            /// <param name="message"></param>
            /// <returns></returns>
            async Task Pakrat()
            {
                var pakratEmbed = new EmbedBuilder()
                                  .WithAuthor($"Hey there {message.Author.Username}!", message.Author.GetAvatarUrl())
                                  .WithTitle("Click here to learn how to use VIDE!")
                                  .WithUrl("https://www.tophattwaffle.com/packing-custom-content-using-vide-in-steampipe/")
                                  .WithThumbnailUrl("https://www.tophattwaffle.com/wp-content/uploads/2013/11/vide.png")
                                  .WithDescription("I was minding my own business when I heard you mention something about PakRat. " +
                                                   "Don't know if you know this, but PakRat is super old and has been know to cause issues in newer games. " +
                                                   "There is a newer program that handles packing better called VIDE. You should check that out instead.")
                                  .WithColor(new Color(243, 128, 72));

                await message.Channel.SendMessageAsync(embed : pakratEmbed.Build());
            }

            /// <summary>
            /// Suggests WWMT over Propper
            /// </summary>
            /// <param name="message"></param>
            /// <returns></returns>
            async Task Propper()
            {
                var wallWormEmbed = new EmbedBuilder()
                                    .WithAuthor($"Hey there {message.Author.Username}!", message.Author.GetAvatarUrl())
                                    .WithTitle("Click here to go to the WallWorm site!")
                                    .WithUrl("https://dev.wallworm.com/")
                                    .WithThumbnailUrl("https://www.tophattwaffle.com/wp-content/uploads/2017/12/worm_logo.png")
                                    .WithDescription(
                    "I saw you were asking about propper. While Propper still works, it's advised to learn " +
                    "a better modeling solution. The preferred method for Source Engine is using 3dsmax with WallWorm Model Tools" +
                    " If you don't want to learn 3dsmax and WWMT, you can learn to configure propper at the link below.: " +
                    "\n\nhttps://www.tophattwaffle.com/configuring-propper-for-steampipe/")
                                    .WithColor(new Color(243, 128, 72));

                await message.Channel.SendMessageAsync(embed : wallWormEmbed.Build());
            }

            async Task LargeMessage(Attachment file)
            {
                //Limit size
                if (file.Size > 5000000)
                {
                    return;
                }

                using (var client = new WebClient())
                {
                    try
                    {
                        var content = client.DownloadString(file.Url);

                        var webResult = client.UploadString(new Uri("https://hastebin.com/documents"), content);

                        var jResult = JObject.Parse(webResult);

                        await message.Channel.SendMessageAsync(
                            "The message was pretty long, for convenience I've uploaded it online:\n" +
                            @"https://hastebin.com/raw/" + jResult.PropertyValues().FirstOrDefault());
                    }
                    catch (Exception e)
                    {
                        await _log.LogMessage("Tried to send to hastebin, but failed for some reason.\n" + e, false);
                    }
                }
            }
        }
Exemplo n.º 7
0
 public static async Task PaginatedReplyAsync(this ISocketMessageChannel channel, List<string> data, int page = 1, EmbedBuilder eb = null)
 {
     await channel.SendEmbedAsync(Paginate(data, page, eb));
 }
Exemplo n.º 8
0
        public async Task Buy([Summary("What kind of thing you want to buy, either stocks or crypto")] string type, [Summary("The name of the thing you want to buy")] string name, [Summary("How many you want to buy")] long amount = 1)
        {
            var symbolType = StockAPIHelper.GetSymbolTypeFromString(type);

            name = name.ToLower();
            if (amount <= 0)
            {
                throw new DiscordCommandException("Number too low", $"{Context.User.Mention}, you can't purchase {(amount == 0 ? "" : "less than ")}no {(symbolType == SymbolType.Crypto ? name.ToUpper() : "shares")}");
            }

            var profile = Context.CallerProfile;
            var info    = await StockAPIHelper.GetSymbolInfo(name, symbolType);

            if (profile.Currency < info.LatestPrice)
            {
                throw new DiscordCommandException("Not enough currency", $"{Context.User.Mention}, you need {Context.Money((long) info.LatestPrice - profile.Currency)} more to buy a single {(symbolType == SymbolType.Crypto ? name.ToUpper() : "share")}");
            }

            long price  = ((long)Math.Ceiling(info.LatestPrice));
            long canBuy = profile.Currency / price;
            long toBuy  = Math.Min(canBuy, amount);

            string message;

            if (canBuy >= amount)
            {
                message = $"{Context.User.Mention}, do you want to purchase {toBuy} {(symbolType == SymbolType.Crypto ? "" : $"{(toBuy == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} for {Context.Money(price * toBuy)}? You currently have {Context.Money(profile.Currency)}.";
            }
            else
            {
                message = $"{Context.User.Mention}, you currently have {Context.Money(profile.Currency)}, that's only enough to buy {toBuy} {(symbolType == SymbolType.Crypto ? "" : $"{(toBuy == 1 ? "one share" : "shares")} in ")}{name.ToUpper()}. Do you still want to buy {(toBuy == 1 ? "it" : "them")} for {Context.Money(price * toBuy)}?";
            }

            ReactionMessageHelper.CreateConfirmReactionMessage(Context, await ReplyAsync(message), onPurchase, onReject);

            async Task onPurchase(ReactionMessage m)
            {
                Context.ClearCachedValues();
                profile = Context.CallerProfile;
                if (profile.Currency < price * toBuy)
                {
                    await m.Message.ModifyAsync(mod =>
                    {
                        mod.Content          = "";
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.WithColor(Color.Red);
                        builder.WithTitle(Strings.SomethingChanged);
                        builder.WithDescription($"{Context.User.Mention}, you no longer have enough to buy {toBuy} {(symbolType == SymbolType.Crypto ? "" : $"{(toBuy == 1 ? "one share" : "shares")} in ")}{name.ToUpper()}");
                        mod.Embed = builder.Build();
                    });

                    return;
                }

                profile.Currency -= price * toBuy;
                var investments = symbolType == SymbolType.Stock ? profile.Investments.Stocks.Active : profile.Investments.Crypto.Active;

                if (!investments.ContainsKey(name))
                {
                    investments.Add(name, new List <Investment>());
                }

                investments[name].Add(new Investment
                {
                    Amount            = toBuy,
                    PurchasePrice     = info.LatestPrice,
                    PurchaseTimestamp = DateTimeOffset.Now
                });

                Context.UserCollection.Update(profile);

                await m.Message.ModifyAsync(properties => properties.Content = $"{Context.WhatDoICall(Context.User)} bought {toBuy} {(symbolType == SymbolType.Crypto ? "" : $"{(toBuy == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} for {Context.Money(price * toBuy)}");
            }

            async Task onReject(ReactionMessage m)
            {
                await m.Message.ModifyAsync(properties => properties.Content = $"Purchase of {(symbolType == SymbolType.Crypto ? "" : $"{ (toBuy == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} canceled");
            }
        }
Exemplo n.º 9
0
 public Play() : base("play", "Plays youtube videos in voice chats", false, true)
 {
     HelpMenu = new EmbedBuilder();
     HelpMenu.WithTitle("Give it a YoutTube link and it'll ~~maybe~~ work.");
 }
Exemplo n.º 10
0
        public async Task GrandExchange([Remainder] string item = null)
        {
            bool found = false;
            int  ID    = 0;

            if (item == null)
            {
                await Context.Channel.SendMessageAsync("Specify an item name please.");

                return;
            }

            foreach (KeyValuePair <int, string> key in OsrsGEItem.Items)
            {
                if (key.Value.ToLower() == item.ToLower())
                {
                    ID    = key.Key;
                    found = true;
                }
            }

            if (!found)
            {
                await Context.Channel.SendMessageAsync($"Could not find **{item}**.");

                return;
            }


            using (HttpClient client = new HttpClient())
            {
                string json = await client.GetStringAsync(OsrsGEItem.GeItemID + ID);

                OsrsGEItem geItem = JsonConvert.DeserializeObject <OsrsGEItem>(json);

                EmbedBuilder eb = new EmbedBuilder();

                eb.WithAuthor((x) =>
                {
                    x.IconUrl = geItem.item.icon;
                    x.Name    = geItem.item.name;
                    x.Url     = $"http://services.runescape.com/m=itemdb_oldschool/Dragon_bones/viewitem?obj={ID}";
                });

                eb.ThumbnailUrl = geItem.item.icon_large;

                eb.Description = $"*{geItem.item.description}*\n```swift\nPrice: {geItem.item.current.price}```";

                eb.AddField((x) =>
                {
                    x.Name = "Today";
                    if (geItem.item.today.trend == "negative")
                    {
                        x.Value = "📉 ";
                    }
                    else if (geItem.item.today.trend == "positive")
                    {
                        x.Value = "📈 ";
                    }

                    x.Value += $"{geItem.item.today.price.Replace(" ", "")}";

                    x.IsInline = true;
                });

                eb.AddField((x) =>
                {
                    x.Name = "Over The Past 30 Days";
                    if (geItem.item.day30.trend == "negative")
                    {
                        x.Value = "📉 ";
                    }
                    else if (geItem.item.day30.trend == "positive")
                    {
                        x.Value = "📈 ";
                    }

                    x.Value += $"{geItem.item.day30.change}";

                    x.IsInline = true;
                });

                eb.AddField((x) =>
                {
                    x.Name = "Over The Past 90 Days";
                    if (geItem.item.day90.trend == "negative")
                    {
                        x.Value = "📉 ";
                    }
                    else if (geItem.item.day90.trend == "positive")
                    {
                        x.Value = "📈 ";
                    }

                    x.Value += $"{geItem.item.day90.change}";

                    x.IsInline = true;
                });

                eb.AddField((x) =>
                {
                    x.Name = "Over The Past 180 Days";
                    if (geItem.item.day180.trend == "negative")
                    {
                        x.Value = "📉 ";
                    }
                    else if (geItem.item.day180.trend == "positive")
                    {
                        x.Value = "📈 ";
                    }

                    x.Value += $"{geItem.item.day180.change}";

                    x.IsInline = true;
                });

                await Context.Channel.SendMessageAsync("", embed : eb.Build());
            }
        }
        public async Task GetStatusAsync()
        {
            var builder = new EmbedBuilder();

            builder.WithTitle("Bot Status");
            var configuration = "Production";
            var adminUser     = Context.Client.GetUser(_config.DiscordBotAdminUser);
            var startTime     = Program.StartTime;
            var uptime        = DateTime.UtcNow.Subtract(startTime);

#if DEBUG
            configuration = "Development";
#endif
            builder.WithFields(new List <EmbedFieldBuilder>
            {
                new EmbedFieldBuilder()
                {
                    Name  = "Version:",
                    Value = AppSettings.VERSION
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Configuration:",
                    Value = configuration
                },
                new EmbedFieldBuilder()
                {
                    Name  = $"{AppSettings.BOT_ADMIN_TERM} (Bot Admin/Developer)",
                    Value = $"{adminUser.Username}#{adminUser.Discriminator}"
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Number of Users on this Server:",
                    Value = Context.Guild != null ? Context.Guild.Users.Count : 0
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Uptime",
                    Value = $"{uptime.Days} Days {uptime.Hours} Hours {uptime.Minutes} Minutes"
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Dump Data",
                    Value = $"Available: {DumpDataService.DataAvailable}; Updating: {DumpDataService.IsUpdating}"
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Last Dump Data Update",
                    Value = $"{(DumpDataService.LastDumpUpdateTimeUtc == DateTime.UnixEpoch || (!DumpDataService.DataAvailable && DumpDataService.IsUpdating)?"Updating":DateTime.UtcNow.Subtract(DumpDataService.LastDumpUpdateTimeUtc).ToString("h'h 'm'm 's's'") + " ago")}"
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Recruitment",
                    Value = RecruitmentService.RecruitmentStatus
                },
                new EmbedFieldBuilder()
                {
                    Name  = "Pool Status",
                    Value = RecruitmentService.PoolStatus
                }
            });
            await ReplyAsync(embed : builder.Build());
        }
Exemplo n.º 12
0
        public async Task Quote([Remainder] string message)
        {
            await Context.Channel.DeleteMessageAsync(Context.Message, RequestOptions.Default);

            var users          = GetUsers().ToList();
            var userByUsername = users.ToDictionary(x => x.Username, y => y);
            var userByNickname = users.Cast <SocketGuildUser>().Where(x => !string.IsNullOrWhiteSpace(x.Nickname)).ToDictionary(x => x.Nickname, y => y as IUser);
            var userByName     = userByNickname.Union(userByUsername).ToDictionary(x => x.Key, y => y.Value);

            var lines = message.Split('\n').ToList();
            SocketTextChannel referredChannel = null;

            foreach (var socketGuildChannel in Context.Guild.Channels)
            {
                var channel = socketGuildChannel as SocketTextChannel;
                if (channel != null && channel.Mention == lines[0].Trim())
                {
                    referredChannel = channel;
                    lines.RemoveAt(0);
                }
            }

            var embedDescription = new StringBuilder();
            var embedAuthor      = new EmbedAuthorBuilder();

            var timestamp = string.Empty;

            foreach (var line in lines)
            {
                var isAuthorLine = false;
                foreach (var user in userByName)
                {
                    if (line.StartsWith(user.Key))
                    {
                        embedAuthor = new EmbedAuthorBuilder
                        {
                            Name    = user.Key,
                            IconUrl = user.Value.GetAvatarUrl()
                        };

                        isAuthorLine = true;

                        var trim = line.Substring(user.Key.Length);
                        timestamp = trim.Trim();

                        break;
                    }
                }

                if (!isAuthorLine)
                {
                    embedDescription.AppendLine(line);
                }
            }

            var footerText = string.Empty;
            var titleText  = string.Empty;

            if (!string.IsNullOrEmpty(timestamp))
            {
                footerText = $"  -  {timestamp}";
                titleText  = timestamp;
            }

            if (referredChannel != null)
            {
                footerText += $", in #{referredChannel.Name}";
                titleText  += $", in #{referredChannel.Name}";
            }

            var embed = new EmbedBuilder
            {
                Color = Color.Blue,
                //Title = titleText,
                Author      = embedAuthor,
                Description = embedDescription.ToString(),
                Footer      = new EmbedFooterBuilder {
                    Text = footerText
                },
            };

            await ReplyAsync("", false, embed.Build());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Genera el builder para el update recibido como parametro
        /// </summary>
        /// <param name="dlc">Corresponde a los datos del juego</param>
        /// <param name="builderDlc">Correspone al builder donde se harán las configuraciones</param>
        /// <returns>Regresa verdadero si todo se ejecuta correctamente.</returns>
        public static bool generaBuilderDlc(stdClassCSharp dlc, ref EmbedBuilder builderDlc, ref string jdwonloader, ref int totalLinks)
        {
            bool respuesta = false;

            try
            {
                StringBuilder sbDatos      = new StringBuilder();
                int           parte        = 0;
                string        linkTemporal = "";
                sbDatos.Append("**");
                sbDatos.Append(dlc["Titulo"]);
                sbDatos.Append("**");

                builderDlc.WithTitle(sbDatos.ToString());

                sbDatos.Clear();

                builderDlc.WithColor(0xFFFFFF);
                builderDlc.WithTimestamp(DateTimeOffset.Now);
                if (dlc["ImagenJuego", TiposDevolver.Boleano])
                {
                    builderDlc.WithFooter(footer =>
                    {
                        footer
                        .WithText("carátule BOT by Urferu response")
                        .WithIconUrl(dlc["ImagenJuego"]);
                    });
                    builderDlc.WithThumbnailUrl(dlc["ImagenJuego"])
                    .WithImageUrl(dlc["ImagenJuego"]);
                }

                if (dlc["UploadBy", TiposDevolver.Boleano])
                {
                    builderDlc.WithAuthor(author =>
                    {
                        author.WithName(dlc["UploadBy"]).WithIconUrl(dlc["ImagenDiscord"]);
                    });
                }

                if (dlc["Peso", TiposDevolver.Boleano])
                {
                    builderDlc.AddField("Peso", dlc["Peso"]);
                }

                if (dlc["Formato", TiposDevolver.Boleano])
                {
                    builderDlc.AddField("Formato", dlc["Formato"]);
                }

                if (dlc["Password", TiposDevolver.Boleano])
                {
                    builderDlc.AddField("Password", dlc["Password"]);
                }

                foreach (var link in dlc["Links"].toArray())
                {
                    if (sbDatos.Length > 0)
                    {
                        sbDatos.Append(Environment.NewLine);
                    }
                    if (sbDatos.Length + link.ToString().Length > 1024)
                    {
                        parte++;
                        builderDlc.AddField($"Links parte {parte}", sbDatos.ToString());
                        sbDatos.Clear();
                    }
                    sbDatos.Append(link);
                    linkTemporal = link.Substring(0, link.Length - 1);
                    linkTemporal = linkTemporal.Substring(linkTemporal.IndexOf('(') + 1);
                    jdwonloader  = $"{jdwonloader},{linkTemporal}";
                    totalLinks++;
                }

                if (parte > 0)
                {
                    parte++;
                    builderDlc.AddField($"Links parte {parte}", sbDatos.ToString());
                }
                else
                {
                    builderDlc.AddField("Links", sbDatos.ToString());
                }

                sbDatos.Clear();
                parte = 0;

                jdwonloader = $"[Add JDownloader]({jdwonloader.Substring(1)}) <- Click Derecho - Copiar enlace";
                respuesta   = true;
            }
            catch
            {
                respuesta = false;
            }
            return(respuesta);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Genera el builder para el juego recibido como parametro
        /// </summary>
        /// <param name="game">Corresponde a los datos del juego</param>
        /// <param name="builderGame">Correspone al builder donde se harán las configuraciones</param>
        /// <returns>Regresa verdadero si todo se ejecuta correctamente.</returns>
        public static bool generaBuilderGame(stdClassCSharp game, ref EmbedBuilder builderGame, ref string jdwonloader, ref int totalLinks)
        {
            bool respuesta = false;

            try
            {
                StringBuilder sbDatos      = new StringBuilder();
                int           parte        = 0;
                string        linkTemporal = "";
                sbDatos.Append("**");
                sbDatos.Append(game["Titulo"]);
                sbDatos.Append("**");

                builderGame.WithTitle(sbDatos.ToString());

                sbDatos.Clear();

                builderGame.WithDescription(game["Descripcion"]);
                builderGame.WithColor(0xD0021B);
                builderGame.WithTimestamp(DateTimeOffset.Now);
                if (game["ImagenJuego", TiposDevolver.Boleano])
                {
                    builderGame.WithFooter(footer =>
                    {
                        footer
                        .WithText("carátule BOT by Urferu response")
                        .WithIconUrl(game["ImagenJuego"]);
                    });
                    builderGame.WithThumbnailUrl(game["ImagenJuego"])
                    .WithImageUrl(game["ImagenJuego"]);
                }

                if (game["UploadBy", TiposDevolver.Boleano])
                {
                    builderGame.WithAuthor(author =>
                    {
                        author.WithName(game["UploadBy"]).WithIconUrl(game["ImagenDiscord"]);
                    });
                }

                if (game["Peso", TiposDevolver.Boleano])
                {
                    builderGame.AddField("Peso", game["Peso"]);
                }

                if (game["Formato", TiposDevolver.Boleano])
                {
                    builderGame.AddField("Formato", game["Formato"]);
                }

                if (game["Password", TiposDevolver.Boleano])
                {
                    builderGame.AddField("Password", game["Password"]);
                }

                foreach (string link in game["Links"].toArray())
                {
                    if (sbDatos.Length > 0)
                    {
                        sbDatos.Append(Environment.NewLine);
                    }
                    if (sbDatos.Length + link.ToString().Length > 1024)
                    {
                        parte++;
                        builderGame.AddField($"Links Del Juego parte {parte}", sbDatos.ToString());
                        sbDatos.Clear();
                    }

                    sbDatos.Append(link);
                    linkTemporal = link.Substring(0, link.Length - 1);
                    linkTemporal = linkTemporal.Substring(linkTemporal.IndexOf('(') + 1);
                    jdwonloader  = $"{jdwonloader},{linkTemporal}";
                    totalLinks++;
                }

                if (parte > 0)
                {
                    parte++;
                    builderGame.AddField($"Links Del Juego parte {parte}", sbDatos.ToString());
                }
                else
                {
                    builderGame.AddField($"Links Del Juego", sbDatos.ToString());
                }

                sbDatos.Clear();
                parte = 0;

                if (game["UpdateIndex", TiposDevolver.Boleano])
                {
                    stdClassCSharp update = new stdClassCSharp();

                    if (searchUpdate(game["Titulo"], ref update, game["UpdateIndex", TiposDevolver.Entero]) &&
                        update.toArray().Length > 0)
                    {
                        game["Update"] = update;
                        stdClassCSharp links = game["Update"].Links;
                        foreach (string link in links.toArray())
                        {
                            if (sbDatos.Length > 0)
                            {
                                sbDatos.Append(Environment.NewLine);
                            }
                            if (sbDatos.Length + link.ToString().Length > 1024)
                            {
                                parte++;
                                builderGame.AddField($"Links Update {game["Update"].Version} {parte}", sbDatos.ToString());
                                sbDatos.Clear();
                            }

                            sbDatos.Append(link);
                            linkTemporal = link.Substring(0, link.Length - 1);
                            linkTemporal = linkTemporal.Substring(linkTemporal.IndexOf('(') + 1);
                            jdwonloader  = $"{jdwonloader},{linkTemporal}";
                            totalLinks++;
                        }

                        if (parte > 0)
                        {
                            parte++;
                            builderGame.AddField($"Links Update {game["Update"].Version} {parte}", sbDatos.ToString());
                        }
                        else
                        {
                            builderGame.AddField($"Links Update {game["Update"].Version}", sbDatos.ToString());
                        }

                        sbDatos.Clear();
                        parte = 0;
                    }
                }

                if (game["DlcIndex", TiposDevolver.Boleano])
                {
                    stdClassCSharp dlc = new stdClassCSharp();

                    if (searchDlc(game["Titulo"], ref dlc, game["DlcIndex", TiposDevolver.Entero]) &&
                        dlc.toArray().Length > 0)
                    {
                        game["Dlc"] = dlc;
                        stdClassCSharp links = game["Dlc"].Links;
                        foreach (string link in links.toArray())
                        {
                            if (sbDatos.Length > 0)
                            {
                                sbDatos.Append(Environment.NewLine);
                            }
                            if (sbDatos.Length + link.ToString().Length > 1024)
                            {
                                parte++;
                                builderGame.AddField($"DLC's parte {parte}", sbDatos.ToString());
                                sbDatos.Clear();
                            }

                            sbDatos.Append(link);
                            linkTemporal = link.Substring(0, link.Length - 1);
                            linkTemporal = linkTemporal.Substring(linkTemporal.IndexOf('(') + 1);
                            jdwonloader  = $"{jdwonloader},{linkTemporal}";
                            totalLinks++;
                        }

                        if (parte > 0)
                        {
                            parte++;
                            builderGame.AddField($"DLC's parte {parte}", sbDatos.ToString());
                        }
                        else
                        {
                            builderGame.AddField("DLC's", sbDatos.ToString());
                        }

                        sbDatos.Clear();
                        parte = 0;
                    }
                }
                jdwonloader = $"[Add JDownloader]({jdwonloader.Substring(1)}) <- Click Derecho - Copiar enlace";
                respuesta   = true;
            }
            catch
            {
                respuesta = false;
            }
            return(respuesta);
        }
Exemplo n.º 15
0
 private void AddPage(ref List <Embed> pages, ref EmbedBuilder builder, string title)
 {
     pages.Add(builder.Build());
     builder = new EmbedBuilder().WithColor(Color.Green).WithTitle(title);
 }
Exemplo n.º 16
0
        public async Task Rolecreation()
        {
            var embed = new EmbedBuilder();

            embed.AddField("Creating roles for you now...",
                           "please hold on while i create roles and channel for you!")
            .WithAuthor(author => { author
                                    .WithName("Birdie Bot")
                                    .WithIconUrl(Global.Birdieicon); })
            .WithThumbnailUrl(Global.Birdiethumbnail)
            .WithColor(new Color(255, 0, 0))
            .WithTitle("Birdie Bot notification")
            .WithFooter(footer =>
                        { footer
                          .WithText(Global.Botcreatorname)
                          .WithIconUrl(Global.Birdieicon); })
            .WithCurrentTimestamp()
            .Build();
            var message = await Context.Channel.SendMessageAsync("", false, embed);


            try
            {
                var allRanks      = new[] { "Challenger", "GrandMaster", "Master", "Diamond", "Platinum", "Gold", "Silver", "Bronze", "Iron", "Unranked", "New Ones :)" };
                var TFTRanks      = new[] { "TFT-Challenger", "TFT-Grandmaster", "TFT-Master", "TFT-Diamond", "TFT-Platinum", "TFT-Gold", "TFT-Silver", "TFT-Bronze", "TFT-Iron", "TFT-Unranked" };
                var allrankcolors = new[] { new Color(240, 140, 15), new Color(253, 7, 7), new Color(192, 7, 146), new Color(32, 102, 148), new Color(46, 204, 113), new Color(241, 196, 15), new Color(151, 156, 159), new Color(187, 121, 68), new Color(255, 255, 255), new Color(124, 136, 120), new Color(188, 157, 154) };
                var TFTcolors     = new[] { new Color(240, 140, 15), new Color(253, 7, 7), new Color(192, 7, 146), new Color(32, 102, 148), new Color(46, 204, 113), new Color(241, 196, 15), new Color(151, 156, 159), new Color(187, 121, 68), new Color(255, 255, 255), new Color(124, 136, 120) };

                string channelname = "Birdie-Connect";

                //my int for the color array (normal queue)
                int y = 0;

                //int for color array TFT
                int yy = 0;

                //running through all the different roles and create them
                //somehow when it checks for roles, it returns null everytime. But it only does it here?
                for (int x = 0; x < allRanks.GetLength(0); x++, y++)
                {
                    //checking if the role from allranks array can be found on the server
                    var role = Context.Guild.Roles.FirstOrDefault(z => z.Name.ToLower() == allRanks[x].ToLower());
                    if (role == null)
                    {
                        GuildPermissions permissions = default;
                        bool             ishoisted   = true;
                        RequestOptions   options     = null;
                        Console.WriteLine("Creating Role " + allRanks[x] + " On the server " + Context.Guild.Name + "!");
                        await Context.Guild.CreateRoleAsync(allRanks[x], permissions, allrankcolors[y], ishoisted, options);
                    }

                    //else if the rolecheck matches the current role then it must exist on server
                    else if (role != null)
                    {
                        Console.WriteLine(allRanks[x] + " Already exists on the the server " + Context.Guild.Name + "!");
                    }
                }

                for (int xx = 0; xx < TFTRanks.GetLength(0); xx++, yy++)
                {
                    var TFTRole = Context.Guild.Roles.FirstOrDefault(zz => zz.Name.ToLower() == TFTRanks[xx].ToLowerInvariant());
                    if (TFTRole == null)
                    {
                        GuildPermissions permissions = default;
                        bool             ishoisted   = false;
                        RequestOptions   options     = null;
                        Console.WriteLine("Creating Role " + TFTRanks[xx] + " On the server " + Context.Guild.Name + "!");
                        await Context.Guild.CreateRoleAsync(TFTRanks[xx], permissions, allrankcolors[yy], ishoisted, options);
                    }
                    else if (TFTRole != null)
                    {
                        Console.WriteLine(TFTRanks[xx] + " Already exists on the the server " + Context.Guild.Name + "!");
                    }
                }

                //check if there is a channel with the name "channelname"
                int  totalchannels = Context.Guild.Channels.Count;
                int  counter       = 0;
                bool exist         = false;
                foreach (SocketGuildChannel channel in Context.Guild.Channels)
                {
                    counter++;
                    //if channel is found - notify in console
                    if (channelname.ToLowerInvariant() == channel.Name)
                    {
                        Console.WriteLine(channelname + " Already exists on the the server " + Context.Guild.Name + "!");
                        exist = true;
                    }

                    //if no channel was found - create it
                    if (counter == totalchannels && exist == false)
                    {
                        RequestOptions channeloptions = null;
                        await Context.Guild.CreateTextChannelAsync(channelname, channeloptions);

                        Console.WriteLine(channelname + " Has been created on the server " + Context.Guild.Name + "!");
                    }
                }

                await Task.Delay(3000);

                await message.ModifyAsync(x =>
                {
                    x.Embed = new EmbedBuilder()
                              .AddField("All roles and channels has been created!",
                                        "Feel free to move the channel as you please!")
                              .WithAuthor(author => { author
                                                      .WithName("Birdie Bot")
                                                      .WithIconUrl(Global.Birdieicon); })
                              .WithThumbnailUrl(Global.Birdiethumbnail)
                              .WithColor(new Color(0, 255, 0))
                              .WithTitle("Birdie Bot notification")
                              .WithFooter(footer =>
                                          { footer
                                            .WithText(Global.Botcreatorname)
                                            .WithIconUrl(Global.Birdieicon); })
                              .WithCurrentTimestamp()
                              .Build();
                });
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 17
0
            public async Task SetEmbedColor(string color)
            {
                if (color.StartsWith('#'))
                {
                    color = color.Substring(1, color.Length - 1);
                }
                int hexColor;

                if (Int32.TryParse(color, System.Globalization.NumberStyles.HexNumber, null, out hexColor))
                {
                    string result = "0x" + color.PadRight(6, '0');
                    if (hexColor < 16777216 && hexColor >= 0)
                    {
                        string previousColorCode = CommandHandlerService.MessageAuthor.EmbedColor;
                        string previousColor;
                        if (previousColorCode.Length != 6)
                        {
                            previousColor = previousColorCode.Substring(2, previousColorCode.Length - 2);
                        }
                        else
                        {
                            previousColor = previousColorCode;
                        }
                        string oldColorName = colornamesApiHandler.GetColorName(previousColor);
                        if (oldColorName == null)
                        {
                            oldColorName = "Color has no name yet.";
                        }
                        string newColorName = colornamesApiHandler.GetColorName(color);
                        if (newColorName == null)
                        {
                            newColorName = "Color has no name yet.";
                        }
                        //hex value is in range
                        User user = DatabaseAccess.Instance.Users.Find(u => u.Id == Context.Message.Author.Id);
                        user.EmbedColor = result;

                        EmbedBuilder embed = new EmbedBuilder()
                                             .WithTitle("Custom embed color changed successfully")
                                             .WithFooter(Sally.NET.DataAccess.File.FileAccess.GENERIC_FOOTER, Sally.NET.DataAccess.File.FileAccess.GENERIC_THUMBNAIL_URL)
                                             .AddField("Previous color name", oldColorName)
                                             .AddField("Previous color hexcode", previousColor)
                                             .AddField("New color name", newColorName)
                                             .AddField("New color hexcode", color)
                                             .AddField("All color names are provided by colornames.org", "https://colornames.org")
                                             .WithDescription("New color preview on the left side")
                                             .WithColor(new Discord.Color((uint)Convert.ToInt32(color, 16)));

                        await Context.Message.Channel.SendMessageAsync(embed : embed.Build());
                    }
                    else
                    {
                        await Context.Message.Channel.SendMessageAsync("wrong hex value");
                    }
                }
                else
                {
                    //error
                    await Context.Message.Channel.SendMessageAsync("Something went wrong");
                }
            }
Exemplo n.º 18
0
            public async Task Config(string name = null, string prop = null, [Leftover] string value = null)
            {
                var configNames = _settingServices.Select(x => x.Name);

                // if name is not provided, print available configs
                name = name?.ToLowerInvariant();
                if (string.IsNullOrWhiteSpace(name))
                {
                    var embed = new EmbedBuilder()
                                .WithOkColor()
                                .WithTitle(GetText("config_list"))
                                .WithDescription(string.Join("\n", configNames));

                    await ctx.Channel.EmbedAsync(embed);

                    return;
                }

                var setting = _settingServices.FirstOrDefault(x =>
                                                              x.Name.StartsWith(name, StringComparison.InvariantCultureIgnoreCase));

                // if config name is not found, print error and the list of configs
                if (setting is null)
                {
                    var embed = new EmbedBuilder()
                                .WithErrorColor()
                                .WithDescription(GetText("config_not_found", Format.Code(name)))
                                .AddField(GetText("config_list"), string.Join("\n", configNames));

                    await ctx.Channel.EmbedAsync(embed);

                    return;
                }

                name = setting.Name;

                // if prop is not sent, then print the list of all props and values in that config
                prop = prop?.ToLowerInvariant();
                var propNames = setting.GetSettableProps();

                if (string.IsNullOrWhiteSpace(prop))
                {
                    var propStrings = GetPropsAndValuesString(setting, propNames);
                    var embed       = new EmbedBuilder()
                                      .WithOkColor()
                                      .WithTitle($"⚙️ {setting.Name}")
                                      .WithDescription(propStrings);


                    await ctx.Channel.EmbedAsync(embed);

                    return;
                }
                // if the prop is invalid -> print error and list of

                var exists = propNames.Any(x => x == prop);

                if (!exists)
                {
                    var propStrings    = GetPropsAndValuesString(setting, propNames);
                    var propErrorEmbed = new EmbedBuilder()
                                         .WithErrorColor()
                                         .WithDescription(GetText("config_prop_not_found", Format.Code(prop), Format.Code(name)))
                                         .AddField($"⚙️ {setting.Name}", propStrings);

                    await ctx.Channel.EmbedAsync(propErrorEmbed);

                    return;
                }

                // if prop is sent, but value is not, then we have to check
                // if prop is valid ->
                if (string.IsNullOrWhiteSpace(value))
                {
                    value = setting.GetSetting(prop);

                    if (string.IsNullOrWhiteSpace(value))
                    {
                        value = "-";
                    }

                    if (prop != "currency.sign")
                    {
                        value = Format.Code(Format.Sanitize(value?.TrimTo(1000)), "json");
                    }

                    var embed = new EmbedBuilder()
                                .WithOkColor()
                                .AddField("Config", Format.Code(setting.Name), true)
                                .AddField("Prop", Format.Code(prop), true)
                                .AddField("Value", value);

                    var comment = setting.GetComment(prop);
                    if (!string.IsNullOrWhiteSpace(comment))
                    {
                        embed.AddField("Comment", comment);
                    }

                    await ctx.Channel.EmbedAsync(embed);

                    return;
                }

                var success = setting.SetSetting(prop, value);

                if (!success)
                {
                    await ReplyErrorLocalizedAsync("config_edit_fail", Format.Code(prop), Format.Code(value));

                    return;
                }

                await ctx.OkAsync();
            }
Exemplo n.º 19
0
        public async Task Sell([Summary("What kind of thing you want to sell, either stocks or crypto")] string type, [Summary("The name of the thing you want to sell")] string name, [Summary("How many you want to sell")] long amount = 1)
        {
            var symbolType = StockAPIHelper.GetSymbolTypeFromString(type);

            name = name.ToLower();
            if (amount <= 0)
            {
                throw new DiscordCommandException("Number too low", $"{Context.User.Mention}, you can't sell {(amount == 0 ? "" : "less than ")}no {(symbolType == SymbolType.Crypto ? name.ToUpper() : "shares")}");
            }

            var profile           = Context.CallerProfile;
            var investments       = symbolType == SymbolType.Stock ? profile.Investments.Stocks.Active : profile.Investments.Crypto.Active;
            var investmentsInName = investments.GetValueOrDefault(name);

            if (investmentsInName == null || investmentsInName.Count == 0)
            {
                throw new DiscordCommandException("Nothing to sell", $"{Context.User.Mention}, you don't have any investments in {name.ToUpper()}");
            }

            SymbolInfo info = await StockAPIHelper.GetSymbolInfo(name, symbolType);

            long toSell = Math.Min(investmentsInName.Sum(x => x.Amount), amount);

            long price           = (long)Math.Ceiling(info.LatestPrice);
            long totalSellAmount = toSell * price;

            string message;

            if (toSell >= amount)
            {
                message = $"{Context.User.Mention}, do you want to sell {toSell} {(symbolType == SymbolType.Crypto ? "" : $"{(toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} for {Context.Money(price * toSell)}?";
            }
            else
            {
                message = $"{Context.User.Mention}, you currently have {toSell} {(symbolType == SymbolType.Crypto ? "" : $"{(toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()}. Do you still want to sell {(toSell == 1 ? "it" : "them")} for {Context.Money(price * toSell)}?";
            }

            ReactionMessageHelper.CreateConfirmReactionMessage(Context, await ReplyAsync(message), onSell, onReject);

            async Task onSell(ReactionMessage m)
            {
                Context.ClearCachedValues();
                profile           = Context.CallerProfile;
                investments       = symbolType == SymbolType.Stock ? profile.Investments.Stocks.Active : profile.Investments.Crypto.Active;
                investmentsInName = investments.GetValueOrDefault(name);

                if (investmentsInName == null)
                {
                    await m.Message.ModifyAsync(mod =>
                    {
                        mod.Content          = "";
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.WithColor(Color.Red);
                        builder.WithTitle(Strings.SomethingChanged);
                        builder.WithDescription($"{Context.User.Mention}, you no longer have any investments in {name.ToUpper()}");
                        mod.Embed = builder.Build();
                    });

                    return;
                }
                if (investmentsInName.Sum(x => x.Amount) < toSell)
                {
                    await m.Message.ModifyAsync(mod =>
                    {
                        mod.Content          = "";
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.WithColor(Color.Red);
                        builder.WithTitle(Strings.SomethingChanged);
                        builder.WithDescription($"{Context.User.Mention}, you no longer have {toSell} {(symbolType == SymbolType.Crypto ? "" : $"{(toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()}");
                        mod.Embed = builder.Build();
                    });

                    return;
                }

                var        sold = new List <Investment>();
                Investment remainderToReturn = null;
                Investment remainderToStore  = null;

                long totalPurchaseAmount = 0;

                long stillToSell = toSell;

                foreach (var inv in investmentsInName.OrderByDescending(x => Math.Abs(price - x.PurchasePrice)))
                {
                    if (stillToSell >= inv.Amount)
                    {
                        totalPurchaseAmount += inv.Amount * (long)Math.Ceiling(inv.PurchasePrice);
                        stillToSell         -= inv.Amount;
                        sold.Add(inv);
                    }
                    else
                    {
                        totalPurchaseAmount += stillToSell * (long)Math.Ceiling(inv.PurchasePrice);

                        remainderToStore = new Investment
                        {
                            Amount            = stillToSell,
                            PurchasePrice     = inv.PurchasePrice,
                            PurchaseTimestamp = inv.PurchaseTimestamp,
                        };

                        remainderToReturn = new Investment
                        {
                            Amount            = inv.Amount - stillToSell,
                            PurchasePrice     = inv.PurchasePrice,
                            PurchaseTimestamp = inv.PurchaseTimestamp,
                        };

                        stillToSell = 0;

                        break;
                    }
                    if (stillToSell == 0)
                    {
                        break;
                    }
                }

                if (stillToSell > 0)
                {
                    await m.Message.ModifyAsync(mod =>
                    {
                        mod.Content          = "";
                        EmbedBuilder builder = new EmbedBuilder();
                        builder.WithColor(Color.Red);
                        builder.WithTitle(Strings.SomethingChanged);
                        builder.WithDescription($"{Context.User.Mention}, you no longer have {toSell} {(symbolType == SymbolType.Crypto ? "" : $"{(toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()}");
                        mod.Embed = builder.Build();
                    });

                    return;
                }

                var oldInvestments = (symbolType == SymbolType.Stock) ? profile.Investments.Stocks.Old : profile.Investments.Crypto.Old;

                List <Investment> oldInvestmentsInName;

                if (!oldInvestments.ContainsKey(name))
                {
                    oldInvestmentsInName = new List <Investment>();
                    oldInvestments.Add(name, oldInvestmentsInName);
                }
                else
                {
                    oldInvestmentsInName = oldInvestments[name];
                }

                profile.Currency += totalSellAmount;
                foreach (var inv in sold)
                {
                    investmentsInName.Remove(inv);
                    inv.SellPrice     = info.LatestPrice;
                    inv.SellTimestamp = DateTimeOffset.Now;
                    oldInvestmentsInName.Add(inv);
                }

                if (remainderToReturn != null)
                {
                    investmentsInName.Add(remainderToReturn);
                }

                if (remainderToStore != null)
                {
                    remainderToStore.SellPrice     = info.LatestPrice;
                    remainderToStore.SellTimestamp = DateTimeOffset.Now;
                    oldInvestmentsInName.Add(remainderToStore);
                }

                Context.UserCollection.Update(profile);

                long diff = totalSellAmount - totalPurchaseAmount;

                string modify;

                if (diff != 0)
                {
                    modify = $"{Context.WhatDoICall(Context.User)} sold {toSell} {(symbolType == SymbolType.Crypto ? "" : $"{(toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} for {Context.Money(totalSellAmount)}, {(diff > 0 ? "earning" : "losing")} {Math.Abs(diff)}. That's a {Math.Abs(diff / (double)totalPurchaseAmount):P2} {(diff > 0 ? "gain" : "loss")}";
                }
                else
                {
                    modify = $"{Context.WhatDoICall(Context.User)} sold {toSell} {(symbolType == SymbolType.Crypto ? "" : $"{(toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} for {Context.Money(totalSellAmount)}, breaking even";
                }

                await m.Message.ModifyAsync(p => p.Content = modify);
            }

            async Task onReject(ReactionMessage m)
            {
                await m.Message.ModifyAsync(p => p.Content = $"Sale of {(symbolType == SymbolType.Crypto ? "" : $"{ (toSell == 1 ? "one share" : "shares")} in ")}{name.ToUpper()} canceled");
            }
        }
Exemplo n.º 20
0
            public async Task ClubInformation([Remainder] string clubName = null)
            {
                if (string.IsNullOrWhiteSpace(clubName))
                {
                    await ClubInformation(Context.User).ConfigureAwait(false);

                    return;
                }

                ClubInfo club;

                if (!_service.GetClubByName(clubName, out club))
                {
                    await ReplyErrorLocalized("club_not_exists").ConfigureAwait(false);

                    return;
                }

                var lvl = new LevelStats(club.Xp);

                await Context.Channel.SendPaginatedConfirmAsync(_client, 0, (page) =>
                {
                    var embed = new EmbedBuilder()
                                .WithOkColor()
                                .WithTitle($"{club.ToString()}")
                                .WithDescription(GetText("level_x", lvl.Level) + $" ({club.Xp} xp)")
                                .AddField("Owner", club.Owner.ToString(), true)
                                .AddField("Level Req.", club.MinimumLevelReq.ToString(), true)
                                .AddField("Members", string.Join("\n", club.Users
                                                                 .OrderByDescending(x => {
                        if (club.OwnerId == x.Id)
                        {
                            return(2);
                        }
                        else if (x.IsClubAdmin)
                        {
                            return(1);
                        }
                        else
                        {
                            return(0);
                        }
                    })
                                                                 .Skip(page * 10)
                                                                 .Take(10)
                                                                 .Select(x =>
                    {
                        if (club.OwnerId == x.Id)
                        {
                            return(x.ToString() + "🌟");
                        }
                        else if (x.IsClubAdmin)
                        {
                            return(x.ToString() + "⭐");
                        }
                        return(x.ToString());
                    })), false);

                    if (Uri.IsWellFormedUriString(club.ImageUrl, UriKind.Absolute))
                    {
                        return(embed.WithThumbnailUrl(club.ImageUrl));
                    }

                    return(embed);
                }, club.Users.Count / 10);
            }
Exemplo n.º 21
0
 private static bool TryGetLogChannel(SocketGuild guild, ModerationType type, out SocketTextChannel channel, out EmbedBuilder baseEmbed)
 {
     if (GuildEventLoggerSettings.TryGetValue(guild.Id, out EventLoggerSettings settings))
     {
         if (settings.UserModLogChannels.TryGetValue(type, out ulong channelId))
         {
             channel   = guild.GetTextChannel(channelId);
             baseEmbed = GetBaseEmbed(type);
             return(channel != null);
         }
     }
     channel   = default;
     baseEmbed = null;
     return(false);
 }
Exemplo n.º 22
0
        public async Task AddReminderMinute(uint minute = 0, [Remainder] string reminderString = null)
        {
            try
            {
                if (minute > 1439)
                {
                    await CommandHandeling.ReplyAsync(Context,
                                                      "Booole. [time] have to be in range 0-1439 (in minutes)");


                    return;
                }

                var hour       = 0;
                var timeFormat = $"{minute}m";

                if (minute >= 60)
                {
                    for (var i = 0; minute >= 59; i++)
                    {
                        minute = minute - 59;
                        hour++;

                        timeFormat = $"{hour}h {minute}m";
                    }
                }

                var timeString = timeFormat; //// MAde t ominutes

                var timeDateTime = DateTime.UtcNow +
                                   TimeSpan.ParseExact(timeString, ReminderFormat.Formats, CultureInfo.CurrentCulture);

                var randomIndex = _secureRandom.Random(0, OctoNamePull.OctoNameRu.Length - 1);
                var randomOcto  = OctoNamePull.OctoNameRu[randomIndex];
                var extra       = randomOcto.Split(new[] { "](" }, StringSplitOptions.RemoveEmptyEntries);
                var name        = extra[0].Remove(0, 1);
                var url         = extra[1].Remove(extra[1].Length - 1, 1);

                var bigmess =
                    $"{reminderString}\n\n" +
                    $"We will send you a DM in  __**{timeDateTime}**__ `by UTC`\n" +
                    $"**Time Now:                               {DateTime.UtcNow}** `by UTC`";

                var embed = new EmbedBuilder();
                embed.WithAuthor(Context.User);
                embed.WithTimestamp(DateTimeOffset.UtcNow);
                embed.WithColor(_secureRandom.Random(0, 255), _secureRandom.Random(0, 255),
                                _secureRandom.Random(0, 255));
                embed.AddField($"**____**", $"{bigmess}");
                embed.WithTitle($"{name} напомнит тебе:");
                embed.WithUrl(url);

                await CommandHandeling.ReplyAsync(Context, embed);


                var account = UserAccounts.GetAccount(Context.User, 0);
                //account.SocketUser = SocketGuildUser(Context.User);
                var newReminder = new CreateReminder(timeDateTime, reminderString);

                account.ReminderList.Add(newReminder);
                UserAccounts.SaveAccounts(0);
            }
            catch
            {
                var botMess =
                    await ReplyAsync(
                        "boo... An error just appear >_< \n" +
                        "Say `HelpRemind`");

                HelperFunctions.DeleteMessOverTime(botMess, 5);
            }
        }
Exemplo n.º 23
0
        public async Task AutoMessage(int option = 0)
        {
            int input;

            if (option == 0)
            {
                await ReplyAsync("```\n" +
                                 "Reply with the command you would like to perform\n" +
                                 "[1] Set the auto message for this channel\n" +
                                 "[2] Set amount of messages before automessaging\n" +
                                 "[3] Enable Automessaging in this channel\n" +
                                 "[4] Disable AutoMessaging\n" +
                                 "[5] View AutoMessage Info" +
                                 "" +
                                 "```");

                var next = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                input = int.Parse(next.Content);
            }
            else
            {
                input = option;
            }

            var serverobj = GuildConfig.GetServer(Context.Guild);

            if (serverobj.AutoMessage.All(x => x.channelID != Context.Channel.Id))
            {
                serverobj.AutoMessage.Add(new GuildConfig.autochannels
                {
                    automessage = "AutoMessage",
                    channelID   = Context.Channel.Id,
                    enabled     = false,
                    messages    = 0,
                    sendlimit   = 50
                });
            }
            var chan = serverobj.AutoMessage.First(x => x.channelID == Context.Channel.Id);

            if (input == 1)
            {
                await ReplyAsync(
                    "Please reply with the message you would like to auto-send in this channel");

                var next2 = await NextMessageAsync();

                chan.automessage = next2.Content;
                await ReplyAsync(
                    "The auto-message for this channel will now be:\n" +
                    "`-----`\n" +
                    $"{chan.automessage}\n" +
                    "`-----`");
            }
            else if (input == 2)
            {
                await ReplyAsync("Please reply with the amount of messages you would like in between automessages");

                var next2 = await NextMessageAsync();

                if (int.TryParse(next2.Content, out var result))
                {
                    chan.sendlimit = result;
                    await ReplyAsync($"Automessages will now be sent every {result} messages in this channel");
                }
                else
                {
                    await ReplyAsync("Error: Not an integer");
                }
            }
            else if (input == 3)
            {
                chan.enabled = true;
                await ReplyAsync("Automessages will now be sent in this channel");
            }
            else if (input == 4)
            {
                chan.enabled = false;
                await ReplyAsync("Automessages will no longer be sent  in this channel");
            }
            else if (input == 5)
            {
                var embed = new EmbedBuilder();
                foreach (var channel in serverobj.AutoMessage)
                {
                    if (Context.Guild.TextChannels.Any(x => x.Id == channel.channelID))
                    {
                        embed.AddField(Context.Guild.TextChannels.First(x => x.Id == channel.channelID).Name,
                                       $"Message: {channel.automessage}\n" +
                                       $"Message Count: {CommandHandler.AutomessageList.FirstOrDefault(x => x.GuildID == Context.Guild.Id).Channels.FirstOrDefault(x => x.channelID == Context.Channel.Id).messages}\n" +
                                       $"Enabled: {channel.enabled}\n" +
                                       $"Msg/AutoMessage: {channel.sendlimit}");
                    }
                }

                await Context.Channel.SendMessageAsync("", false, embed.Build());
                await ReplyAsync("Done");
            }
            else
            {
                await ReplyAsync("ERROR: you did not supply an option. type only `1` etc.");
            }

            var AGuild = CommandHandler.AutomessageList.FirstOrDefault(x => x.GuildID == Context.Guild.Id);

            if (AGuild == null)
            {
                CommandHandler.AutomessageList.Add(new CommandHandler.AutoMessages
                {
                    GuildID  = Context.Guild.Id,
                    Channels = serverobj.AutoMessage
                });
            }
            else
            {
                AGuild.Channels = serverobj.AutoMessage;
            }

            GuildConfig.SaveServer(serverobj);
        }
Exemplo n.º 24
0
        public async Task AddReminderToSomeOne(ulong userId, [Remainder] string args)
        {
            try
            {
                string[] splittedArgs = null;
                if (args.ToLower().Contains("  in "))
                {
                    splittedArgs = args.ToLower().Split(new[] { "  in " }, StringSplitOptions.None);
                }
                else if (args.ToLower().Contains(" in  "))
                {
                    splittedArgs = args.ToLower().Split(new[] { " in  " }, StringSplitOptions.None);
                }
                else if (args.ToLower().Contains("  in  "))
                {
                    splittedArgs = args.ToLower().Split(new[] { "  in  " }, StringSplitOptions.None);
                }
                else if (args.ToLower().Contains(" in "))
                {
                    splittedArgs = args.ToLower().Split(new[] { " in " }, StringSplitOptions.None);
                }


                if (splittedArgs == null)
                {
                    var bigmess = "boole-boole... you are using this command incorrectly!!\n" +
                                  "Right way: `Remind [text] in [time]`\n" +
                                  "Between message and time **HAVE TO BE** written `in` part" +
                                  "(Time can be different, but follow the rules! **day-hour-minute-second**. You can skip any of those parts, but they have to be in the same order. One space or without it between each of the parts\n" +
                                  "I'm a loving order octopus!";

                    await CommandHandeling.ReplyAsync(Context, bigmess);

                    return;
                }

                var timeString = splittedArgs[splittedArgs.Length - 1];
                if (timeString == "24h")
                {
                    timeString = "1d";
                }
                splittedArgs[splittedArgs.Length - 1] = "";
                var reminderString = string.Join(" in ", splittedArgs, 0, splittedArgs.Length - 1);

                var timeDateTime =
                    DateTime.UtcNow +
                    TimeSpan.ParseExact(timeString, ReminderFormat.Formats, CultureInfo.CurrentCulture);

                var user = Global.Client.GetUser(userId);


                var randomIndex = _secureRandom.Random(0, OctoNamePull.OctoNameRu.Length - 1);
                var randomOcto  = OctoNamePull.OctoNameRu[randomIndex];
                var extra       = randomOcto.Split(new[] { "](" }, StringSplitOptions.RemoveEmptyEntries);
                var name        = extra[0].Remove(0, 1);
                var url         = extra[1].Remove(extra[1].Length - 1, 1);

                var embed = new EmbedBuilder();
                embed.WithAuthor(Context.User);
                embed.WithTimestamp(DateTimeOffset.UtcNow);
                embed.WithColor(_secureRandom.Random(0, 255), _secureRandom.Random(0, 255),
                                _secureRandom.Random(0, 255));

                var bigmess2 =
                    $"{reminderString}\n\n" +
                    $"We will send you a DM in  __**{timeDateTime}**__ `by UTC`\n" +
                    $"**Time Now:                               {DateTime.UtcNow}** `by UTC`";


                embed.AddField($"**____**", $"{bigmess2}");
                embed.WithTitle($"{name} напомнит {user.Username}:");
                embed.WithUrl(url);


                var account     = UserAccounts.GetAccount(user, 0);
                var newReminder = new CreateReminder(timeDateTime, $"From {Context.User.Username}: " + reminderString);

                account.ReminderList.Add(newReminder);
                UserAccounts.SaveAccounts(0);


                await CommandHandeling.ReplyAsync(Context, embed);
            }
            catch
            {
                var botMess = await ReplyAsync(
                    "boo... An error just appear >_< \n" +
                    "Say `HelpRemind`");

                HelperFunctions.DeleteMessOverTime(botMess, 5);
            }
        }
 public static EmbedBuilder WithCopyrightFooter(this EmbedBuilder embedBuilder, string userName = null, string command = null)
 {
     return(embedBuilder.WithCurrentTimestamp().WithFooter(new EmbedFooterBuilder().WithIconUrl("https://cdn.discordapp.com/avatars/491673480006205461/30abe7a1feffb0b06a1611a94fbc1248.png").WithText($"{(command == null ? String.Empty : $"Command {command}")} © HeroBot {DateTime.Now.Year} • {(userName == null ? String.Empty : $"Requested by {userName}")}")));
Exemplo n.º 26
0
        public async Task AddReminder([Remainder] string args)
        {
            try
            {
                string[] splittedArgs = { };
                if (args.ToLower().Contains("  in "))
                {
                    splittedArgs = args.ToLower().Split(new[] { "  in " }, StringSplitOptions.None);
                }
                else if (args.ToLower().Contains(" in  "))
                {
                    splittedArgs = args.ToLower().Split(new[] { " in  " }, StringSplitOptions.None);
                }
                else if (args.ToLower().Contains("  in  "))
                {
                    splittedArgs = args.ToLower().Split(new[] { "  in  " }, StringSplitOptions.None);
                }
                else if (args.ToLower().Contains(" in "))
                {
                    splittedArgs = args.ToLower().Split(new[] { " in " }, StringSplitOptions.None);
                }


                if (splittedArgs == null)
                {
                    const string bigmess = "boole-boole... you are using this command incorrectly!!\n" +
                                           "Right way: `Remind [text] in [time]`\n" +
                                           "Between message and time **HAVE TO BE** written `in` part" +
                                           "(Time can be different, but follow the rules! **day-hour-minute-second**. You can skip any of those parts, but they have to be in the same order. One space or without it between each of the parts\n" +
                                           "I'm a loving order octopus!";
                    await CommandHandeling.ReplyAsync(Context, bigmess);

                    return;
                }
                var account            = UserAccounts.GetAccount(Context.User, 0);
                var accountForTimeZone = UserAccounts.GetAccount(Context.User, Context.Guild.Id);

                var timezone = accountForTimeZone.TimeZone ?? "UTC";

                TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById($"{timezone}");


                var timeString = splittedArgs[splittedArgs.Length - 1];
                if (timeString == "24h")
                {
                    timeString = "1d";
                }
                splittedArgs[splittedArgs.Length - 1] = "";
                var reminderString = string.Join(" in ", splittedArgs, 0, splittedArgs.Length - 1);

                var timeDateTime = DateTime.UtcNow +
                                   TimeSpan.ParseExact(timeString, ReminderFormat.Formats, CultureInfo.CurrentCulture);
                var randomIndex = _secureRandom.Random(0, OctoNamePull.OctoNameRu.Length - 1);
                var randomOcto  = OctoNamePull.OctoNameRu[randomIndex];

                var extra = randomOcto.Split(new[] { "](" }, StringSplitOptions.RemoveEmptyEntries);
                var name  = extra[0].Remove(0, 1);
                var url   = extra[1].Remove(extra[1].Length - 1, 1);


                var localTime = TimeZoneInfo.ConvertTimeFromUtc(timeDateTime, tz);

                var bigmess2 =
                    $"{reminderString}\n\n" +
                    $"We will send you a DM in  __**{localTime}**__ `by {timezone}`\n";
                var embed = new EmbedBuilder();
                embed.WithAuthor(Context.User);
                embed.WithTimestamp(DateTimeOffset.UtcNow);
                embed.WithColor(_secureRandom.Random(0, 254), _secureRandom.Random(0, 254),
                                _secureRandom.Random(0, 254));
                embed.AddField($"**____**", $"{bigmess2}");
                embed.WithTitle($"{name} напомнит тебе:");
                embed.WithUrl(url);


                var newReminder = new CreateReminder(timeDateTime, reminderString);

                account.ReminderList.Add(newReminder);
                UserAccounts.SaveAccounts(0);


                await CommandHandeling.ReplyAsync(Context, embed);
            }
            catch (Exception e)
            {
                var botMess = await ReplyAsync(
                    "boo... An error just appear >_< \n" +
                    "Say `HelpRemind`");

                HelperFunctions.DeleteMessOverTime(botMess, 5);
                ConsoleLogger.Log($" [REMINDER][Exception] ({Context.User.Username}) - {e.Message}",
                                  ConsoleColor.DarkBlue);
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 27
0
        async Task GetWikiDescription(string url, string item, EmbedBuilder builder, bool isFixing = true)
        {
            string[] split = item.Split('#');

            item = split[0];

            using (HttpClient httpClient = new HttpClient())
            {
                string description = null;

                if (isFixing)
                {
                    HttpResponseMessage apiSearch = await httpClient.GetAsync(url + "/api.php?action=opensearch&profile=fuzzy&redirects=resolve&search=" + item);

                    //Format of result is really weird (array of mismatched types).
                    //Adding in square brackets to make first item a string array (rather than just string)
                    string result = apiSearch.Content.ReadAsStringAsync().Result;
                    result = result.Insert(1, "[");
                    result = result.Insert(result.IndexOf(','), "]");

                    string[][] array = JsonConvert.DeserializeObject <string[][]>(result);

                    if (array == null || array[1].Length == 0)
                    {
                        description = "Page not found";

                        url += "/" + item.Replace(" ", "_");

                        description += $"\n[Click here to create it!]({url})";
                    }
                    else
                    {
                        item = array[1][0];
                    }
                }

                if (description == null)
                {
                    HttpResponseMessage apiResponseText = await httpClient.GetAsync("https://townshiptale.gamepedia.com/api.php?format=json&action=parse&page=" + item);

                    ApiResponse apiResponse = null;

                    try
                    {
                        string text = apiResponseText.Content.ReadAsStringAsync().Result;

                        apiResponse = JsonConvert.DeserializeObject <ApiResponse>(text);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        apiResponse = new ApiResponse();
                    }

                    if (apiResponse.parse == null)
                    {
                        if (!isFixing)
                        {
                            await GetWikiDescription(url, item, builder, true);

                            return;
                        }
                    }
                    else
                    {
                        url += "/" + item.Replace(" ", "_");

                        int startSearch = 0;

                        if (split.Length > 1)
                        {
                            startSearch = apiResponse.parse.text.value.IndexOf("mw-headline\" id=\"" + split[1], StringComparison.InvariantCultureIgnoreCase);

                            if (startSearch < 0)
                            {
                                startSearch = apiResponse.parse.text.value.IndexOf("<p><b>" + split[1], StringComparison.InvariantCultureIgnoreCase);

                                if (startSearch < 0)
                                {
                                    startSearch = 0;
                                }
                                else
                                {
                                    //Need to look for best subheading

                                    int headlineStart = apiResponse.parse.text.value.LastIndexOf("mw-headline\" id=\"", startSearch, startSearch) + 17;

                                    int headlineEnd = apiResponse.parse.text.value.IndexOf("\"", headlineStart);

                                    string headline = apiResponse.parse.text.value.Substring(headlineStart, headlineEnd - headlineStart);

                                    split[1] = headline;
                                }
                            }

                            url += '#' + split[1];
                        }

                        int start = apiResponse.parse.text.value.IndexOf("<p>", startSearch);

                        if (start < 0 && startSearch > 0)
                        {
                            start = apiResponse.parse.text.value.IndexOf("<p>");
                        }

                        if (builder.ImageUrl == null && apiResponse.parse.images.Length > 0)
                        {
                            for (int i = 0; i < apiResponse.parse.images.Length; i++)
                            {
                                if (apiResponse.parse.text.value.IndexOf(apiResponse.parse.images[i]) < startSearch)
                                {
                                    continue;
                                }

                                HttpResponseMessage imageResponse = await httpClient.GetAsync("https://townshiptale.gamepedia.com/api.php?action=query&prop=imageinfo&format=json&iiprop=url&titles=File:" + apiResponse.parse.images[i]);

                                string text = imageResponse.Content.ReadAsStringAsync().Result;

                                try
                                {
                                    builder.ImageUrl = JsonConvert.DeserializeObject <ImageResponse>(text).Url;
                                }
                                catch
                                {
                                    builder.ImageUrl = null;
                                }

                                break;
                            }
                        }

                        if (start >= 0)
                        {
                            int end = apiResponse.parse.text.value.IndexOf("</p>", start);

                            if (end > 0)
                            {
                                start += 3;

                                description = apiResponse.parse.text.value.Substring(start, end - start)
                                              .Replace("<b>", "**")
                                              .Replace("</b>", "**")
                                              .Trim();

                                description = Regex.Replace(description, item + "s?", match => $"[{match.Value}]({url})");

                                RemoveHtml(ref description);
                            }
                        }

                        if (description == null)
                        {
                            description = "No description found";
                        }

                        description += $"\n[Click here for more info]({url})";
                    }
                }

                builder.AddField(item, description);
            };
        }
Exemplo n.º 28
0
        public async Task Np()
        {
            if (!_node.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyFailureEmbed("I have not joined any Voice Channel yet.");

                return;
            }

            if (player.Track == null)
            {
                await ReplyFailureEmbed("I'm currently not playing anything");

                return;
            }

            if (player.Track.IsStream)
            {
                await ReplyFailureEmbed("I cannot display information about a stream");

                return;
            }

            double percentageDone = (100.0 / player.Track.Duration.TotalSeconds) *
                                    player.Track.Position.TotalSeconds;
            int    rounded  = (int)Math.Floor(percentageDone / 10);
            string progress = "";

            for (int i = 0; i < 10; i++)
            {
                if (i == rounded)
                {
                    progress += " :red_circle: ";
                    continue;
                }

                progress += "▬";
            }

            var eb = new EmbedBuilder()
            {
                Color       = Blue,
                Title       = $"{MUSICAL_NOTE} Currently playing by {player.Track.Author}",
                Description =
                    $"**[{player.Track.Title}]({player.Track.Url})**{(player.PlayerState == PlayerState.Paused ? " (Paused)" : "")}"
            };

            var imageUrl = await player.Track.FetchArtworkAsync();

            if (!string.IsNullOrWhiteSpace(imageUrl))
            {
                eb.WithThumbnailUrl(imageUrl);
            }

            eb.AddField(x =>
            {
                x.IsInline = false;
                x.Name     = "Progress";
                x.Value    =
                    $"[{Formatter.FormatTime(player.Track.Position)}] {progress} [{Formatter.FormatTime(player.Track.Duration)}]";
            });

            await ReplyEmbed(eb);
        }
Exemplo n.º 29
0
        public async Task HandleReaction(DiscordSocketClient discordSocketClient, SocketReaction reaction,
                                         ISocketMessageChannel channel, Dictionary <string, string> _reactionWatcher, Program program)
        {
            if (reaction.MessageId.ToString() == "586248421715738629")
            {
                var eventDetailChannel = (ISocketMessageChannel)discordSocketClient.GetChannel(572721078359556097);
                var embededMessage     = (IUserMessage)await eventDetailChannel.GetMessageAsync(586248421715738629);

                var embedInfo = embededMessage.Embeds.First();
                var guild     = discordSocketClient.Guilds.FirstOrDefault(x => x.Id == (ulong)505485680344956928);
                var user      = guild.GetUser(reaction.User.Value.Id);

                var embedBuilder = new EmbedBuilder
                {
                    Title       = embedInfo.Title,
                    Description = embedInfo.Description.Replace("\n" + user.Username, "").Trim(),
                    Footer      = new EmbedFooterBuilder {
                        Text = embedInfo.Footer.ToString()
                    },
                    Color = embedInfo.Color
                };

                await embededMessage.ModifyAsync(msg => msg.Embed = embedBuilder.Build());

                return;
            }

            //IRL Event section
            var data = JsonExtension.GetJsonData("../../../Resources/irleventdata.txt");

            if (reaction.UserId != 504633036902498314 && data.Keys.Contains(reaction.MessageId.ToString()))
            {
                //green_check (671412276594475018)
                //blue_check (671413239992549387)
                //red_check (671413258468720650)
                //<:peepoLimburg:600782036919123968>

                if (reaction.Emote.ToString() == "<:green_check:671412276594475018>")
                {
                    var deelnemersMsgData  = JsonExtension.ToDictionary <string[]>(data[reaction.MessageId.ToString()]);
                    var eventDetailChannel = reaction.Channel;
                    var msgId          = deelnemersMsgData.First().Key;
                    var embededMessage = (IUserMessage)await eventDetailChannel.GetMessageAsync(ulong.Parse(msgId));

                    var embedInfo = embededMessage.Embeds.First();
                    var user      = discordSocketClient.GetUser(reaction.User.Value.Id);

                    var des         = embedInfo.Description.Split("\n");
                    var description = "";
                    foreach (var deelnemer in des)
                    {
                        if (!deelnemer.Contains(reaction.UserId.ToString()))
                        {
                            description += "\n" + deelnemer;
                        }
                    }

                    var embedBuilder = new EmbedBuilder
                    {
                        Title       = embedInfo.Title,
                        Description = description,
                        Footer      = new EmbedFooterBuilder {
                            Text = embedInfo.Footer.ToString()
                        },
                        Color = embedInfo.Color
                    };

                    await embededMessage.ModifyAsync(msg => msg.Embed = embedBuilder.Build());

                    return;
                }

                if (reaction.Emote.ToString() == "<:red_check:671413258468720650>")
                {
                    var user = discordSocketClient.GetUser(reaction.User.Value.Id);
                    var deelnemersMsgData = JsonExtension.ToDictionary <string[]>(data[reaction.MessageId.ToString()]);
                    var d = deelnemersMsgData[reaction.MessageId + "0"];
                    var generalChannel = discordSocketClient.GetGuild(505485680344956928)
                                         .GetChannel(ulong.Parse(d.First()));
                    await generalChannel.AddPermissionOverwriteAsync(user,
                                                                     new OverwritePermissions().Modify(sendMessages: PermValue.Deny, viewChannel: PermValue.Deny,
                                                                                                       readMessageHistory: PermValue.Deny));


                    var user2       = discordSocketClient.GetUser(reaction.User.Value.Id);
                    var infoChannel = discordSocketClient.GetGuild(505485680344956928).GetChannel(reaction.Channel.Id);
                    await generalChannel.AddPermissionOverwriteAsync(user2,
                                                                     new OverwritePermissions().Modify(sendMessages: PermValue.Deny, viewChannel: PermValue.Deny,
                                                                                                       readMessageHistory: PermValue.Deny));

                    return;
                }
            }

            //Remove Roles from reactions added to specific channels

            if (channel.Id == 510227606822584330 || channel.Id == 627292184143724544)
            {
                var guild = discordSocketClient.GetGuild(505485680344956928);
                if (channel.Id == 510227606822584330)
                {
                    guild = discordSocketClient.GetGuild(505485680344956928);
                }
                else if (channel.Id == 627292184143724544)
                {
                    guild = discordSocketClient.GetGuild(627156958880858113);
                }

                var user = guild.GetUser(reaction.UserId);

                var t = reaction.Emote.ToString();

                foreach (var reactionDic in _reactionWatcher)
                {
                    if (reactionDic.Key == t)
                    {
                        var role = guild.Roles.FirstOrDefault(x => x.Name == reactionDic.Value);
                        await(user as IGuildUser).RemoveRoleAsync(role);
                    }
                }
            }

            //Turn page from help command

            //right (681843066104971287)
            //left (681842980134584355)
            if (reaction.UserId != 504633036902498314)
            {
                if (reaction.Emote.ToString() == "<:right:681843066104971287>")
                {
                    var t       = reaction.Message.ToString();
                    var message = await channel.GetMessageAsync(reaction.MessageId);

                    var casted    = (IUserMessage)message;
                    var usedEmbed = casted.Embeds.First();
                    var pagenr    = usedEmbed.Title.Split("[")[1].Split("]")[0];

                    var currentNr = int.Parse(pagenr.Split("/")[0]);
                    var maxNr     = int.Parse(pagenr.Split("/")[1]);

                    if (currentNr >= maxNr)
                    {
                        return;
                    }

                    casted.ModifyAsync(msg =>
                                       msg.Embed = Help.GetHelpList(discordSocketClient, int.Parse(pagenr.Split("/").First())));
                }

                if (reaction.Emote.ToString() == "<:left:681842980134584355>")
                {
                    var t       = reaction.Message.ToString();
                    var message = await channel.GetMessageAsync(reaction.MessageId);

                    var casted    = (IUserMessage)message;
                    var usedEmbed = casted.Embeds.First();
                    var pagenr    = usedEmbed.Title.Split("[")[1].Split("]")[0];

                    var currentNr = int.Parse(pagenr.Split("/")[0]);

                    if (currentNr <= 0)
                    {
                        return;
                    }

                    casted.ModifyAsync(msg =>
                                       msg.Embed = Help.GetHelpList(discordSocketClient,
                                                                    int.Parse(pagenr.Split("/").First()) - 2));
                }
            }
        }
Exemplo n.º 30
0
        public async Task ShowQueue()
        {
            if (!_node.TryGetPlayer(Context.Guild, out var player))
            {
                await ReplyFailureEmbed("I have not joined any Voice Channel yet.");

                return;
            }

            if (player.Track == null)
            {
                await ReplyFailureEmbed("I'm currently not playing anything");

                return;
            }

            var eb = new EmbedBuilder()
            {
                Color  = Blue,
                Title  = $"{MUSICAL_NOTE} Queue",
                Footer = RequestedByMe()
            };

            eb.AddField(x =>
            {
                x.IsInline = false;
                x.Name     = $"Now playing by {player.Track.Author}";
                x.Value    =
                    $"[{Formatter.FormatTime(player.Track.Duration)}] - **[{player.Track.Title}]({player.Track.Url})**";
            });

            if (player.Queue.Count == 0)
            {
                await ReplyEmbed(eb);

                return;
            }

            // Otherwise built the rest of the queue
            int count = 0;

            foreach (var item in player.Queue)
            {
                ++count;
                var track = item;
                eb.AddField(x =>
                {
                    x.IsInline = false;
                    // ReSharper disable once AccessToModifiedClosure
                    x.Name  = $"#{count.ToString()} by {track.Author}";
                    x.Value = $"[{Formatter.FormatTime(track.Duration)}] - **[{track.Title}]({track.Url})**";
                });

                if (count >= 10)
                {
                    break;
                }
            }

            TimeSpan duration = new TimeSpan();

            foreach (var item in player.Queue)
            {
                var track = item;
                duration = duration.Add(track.Duration);
            }

            duration = duration.Add(player.Track.Duration.Subtract(player.Track.Position));
            eb.AddField(x =>
            {
                x.IsInline = false;
                x.Name     = $"{player.Queue.Count.ToString()} songs in queue";
                x.Value    = $"[{Formatter.FormatTime(duration)}] total playtime";
            });

            await ReplyEmbed(eb);
        }
Exemplo n.º 31
0
        private async Task <MsgType> HandleAllPlayersDead(EmbedBuilder result)
        {
            NPC    mob      = (NPC)Utils.RandomElement(mobParty).character;
            string lostInfo = allMobsDead ? "No one is left standing to claim victory." : "You have been defeated." + Environment.NewLine;

            if (currentArea.IsDungeon)
            {
                await Database.DeleteRecord <Area>("Dungeons", MainAreaPath.path, "AreaId");
            }

            MsgType   msgType   = MsgType.Main;
            Encounter encounter = await ChallengeEnd();

            if (encounter != null)
            {
                msgType = encounter.Name switch
                {
                    Encounter.Names.Loot => MsgType.Loot,
                    _ => msgType,
                };
            }

            bool deathCost = msgType == MsgType.Main;

            foreach (var cb in playerParty)
            {
                PerkLoad.CheckPerks(cb.character, Perk.Trigger.EndFight, cb.character);

                if (encounter != null)
                {
                    if (encounter.koinsToGain > 0)
                    {
                        cb.character.KCoins += encounter.koinsToGain;
                    }
                    if (encounter.xpToGain > 0)
                    {
                        cb.character.XpGain(encounter.xpToGain, 1);
                    }
                }

                if (cb.character is Player player)
                {
                    if (!allMobsDead && deathCost)
                    {
                        lostInfo += DefeatCost(player, mob, 0.5) + Environment.NewLine;
                    }

                    await player.Respawn(false);

                    if (endDungeon)
                    {
                        player.AreaInfo = ParentAreaPath(currentArea, partyLeader.AreaInfo.floor);
                    }
                    player.SaveFileMongo();
                }
                else if (cb.character is NPC n)
                {
                    FollowerCheck(n, party, allPlayersDead);
                }
            }

            result.AddField("Defeat", lostInfo);

            if (encounter != null)
            {
                string loot = null;
                if (encounter.loot != null && encounter.loot.Count > 0)
                {
                    int c = Math.Min(encounter.loot.Count, 10);
                    for (int i = 0; i < c; i++)
                    {
                        loot += $"{i + 1}|" + encounter.loot[i] + Environment.NewLine;
                    }
                    if (c < encounter.loot.Count)
                    {
                        loot += $"And {encounter.loot.Count - c} more...";
                    }
                }

                string extraResult = (encounter.koinsToGain > 0 ? $"+{encounter.koinsToGain} Kuts" + Environment.NewLine : null)
                                     + (encounter.xpToGain > 0 ? $"+{encounter.xpToGain} XP" + Environment.NewLine : null)
                                     + loot;

                result.AddField("Rewards",
                                extraResult.Length != 0 ? extraResult : "None");

                encounter.koinsToGain = 0;
                encounter.xpToGain    = 0;

                if (party != null)
                {
                    partyLeader.NewEncounter(encounter);
                }
            }

            if (!allMobsDead && currentEncounter.Name != Encounter.Names.Bounty &&
                currentArea.type != AreaType.Dungeon && currentArea.type != AreaType.Arena)
            {
                PopulationHandler.Add(currentArea, mob);
            }
            return(msgType);
        }
Exemplo n.º 32
0
        public static async Task MakeAnimeObjectAsync(IMessage message, IGuildUser author, object obj)
        {
            var anime = obj as Models.AnimeModel;
            if(anime == null)
            {
                await message.Channel.SendMessageAsync($"{author.Mention}: Something went wrong! I'm so sorry :(");
                return;
            }

            EmbedBuilder eb = new EmbedBuilder();
            eb.WithColor(new Color(0, 255, 0))
            .WithTitle(anime.Title)
            .WithDescription(anime.Genre)
            .WithUrl(anime.Url)
            .WithThumbnailUrl(anime.ImageUrl)
            .WithAuthor(x=>
            {
                x.Name = author.Nickname == null ? author.Username : author.Nickname;
                x.IconUrl = author.AvatarUrl;
            });

            //Add Episodes field
            eb.AddField(x =>
            {
                x.IsInline = true;
                x.Name = "Episodes";
                x.Value = anime.Episodes;
            });

            if (!String.IsNullOrEmpty(anime.Duration))
            {
                eb.AddField(x =>
                {
                    x.IsInline = true;
                    x.Name = "Duration";
                    x.Value = anime.Duration;
                });
            }

            eb.AddField(x =>
            {
                x.IsInline = true;
                x.Name = "Score";
                x.Value = anime.Score;
            });

            eb.AddField(x =>
            {
                x.IsInline = true;
                x.Name = "Type";
                x.Value = anime.Type;
            });

            eb.AddField(x =>
            {
                x.IsInline = false;
                x.Name = "Description";
                x.Value = anime.Description;
            });

            await message.Channel.SendMessageAsync("", embed: eb);
        }