Ejemplo n.º 1
0
            public async Task GetSauce(string url)
            {
                if (!Util.String.ValidateUrl(url))
                {
                    await Util.Error.BuildError("Invalid URL", Context);

                    return;
                }

                using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
                string  assembledUrl = SingleResultUrl + ApiKey + HttpUtility.UrlEncode(url);
                dynamic keys         = JObject.Parse(await Client.GetStringAsync(assembledUrl));

                if (keys.header.status != 0)
                {
                    BuildSauceNaoError(keys, Context);
                    return;
                }

                string similarity = (keys.results[0].header.similarity ?? "?").ToString();
                string src        = (keys.results[0].data.source ?? (keys.results[0].data.ext_urls[0] ?? "?")).ToString();

                if (src == "?")
                {
                    await ReplyAsync($"SauceNAO didn't give me a source...\n{GetRequestsLeft(keys, RequestsLeftType.Message)}");

                    return;
                }
                await ReplyAsync($"I am **{similarity}%** confident it is **{src}** thanks to SauceNAO.\n" + GetRequestsLeft(keys, RequestsLeftType.Message));
            }
Ejemplo n.º 2
0
        public async Task Syn(string word, string langId = "en")
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            try
            {
                await GetJson(new DictInputs
                {
                    get     = "entries",
                    langId  = langId,
                    word    = word,
                    filters = "/synonyms"
                });

                dynamic keys = JObject.Parse(text);

                List <EmbedFieldBuilder> allSynonyms = new List <EmbedFieldBuilder>
                {
                    new()
                    {
                        Name     = "Word / Region",
                        Value    = $"{word } / {langId}",
                        IsInline = false
                    }
                };

                string allSynonymsString = "";

                foreach (var sense in keys.results[0].lexicalEntries[0].entries[0].senses)
                {
                    foreach (var subsense in sense.subsenses)
                    {
                        foreach (var synonym in subsense.synonyms)
                        {
                            allSynonymsString += $"{synonym.text }, ";
                        }
                    }
                }

                allSynonymsString = allSynonymsString.Remove(allSynonymsString.Length - 2);

                allSynonyms.Add(new EmbedFieldBuilder
                {
                    Name     = "Synonym(s)",
                    Value    = allSynonymsString,
                    IsInline = false
                });

                //string _first_def = keys.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0].ToString();

                EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, "Oxford Dictionary API", "Synonym(s)", Color.Orange);
                embed.Fields = allSynonyms;

                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception e)
            {
                //await GeneralTools.CommHandler.BuildError(e, Context);
                await ReplyAsync("Either that word doesn't exist in the dictionary or it has no synonyms.");
            }
        }
Ejemplo n.º 3
0
        public async Task Define(string word, string langId = "en")
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            try
            {
                await GetJson(new DictInputs
                {
                    get     = "entries",
                    langId  = langId,
                    word    = word,
                    filters = "/definitions"
                });

                dynamic keys = JObject.Parse(text);

                List <EmbedFieldBuilder> allDefinitions = new List <EmbedFieldBuilder>
                {
                    new()
                    {
                        Name     = "Word / Region",
                        Value    = $"{word } / {langId}",
                        IsInline = false
                    }
                };

                string allDefinitionsString = "";
                int    count = 1;

                foreach (var key in keys.results[0].lexicalEntries[0].entries[0].senses)
                {
                    allDefinitionsString += $"**{count}**. {key.definitions[0]}\n";
                    count++;
                }

                allDefinitions.Add(new EmbedFieldBuilder
                {
                    Name     = "Definition(s)",
                    Value    = allDefinitionsString,
                    IsInline = false
                });

                //string _first_def = keys.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0].ToString();

                EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, "Oxford Dictionary API", "Definition(s)", Color.Orange);
                embed.Fields = allDefinitions;

                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception e)
            {
                await Util.Error.BuildError(e, Context);
            }
        }
Ejemplo n.º 4
0
            public async Task GetTop(string url, int amount = 5)
            {
                amount = (int)MathF.Max(1.0f, MathF.Min(5.0f, amount));

                if (!Util.String.ValidateUrl(url))
                {
                    await Util.Error.BuildError("Invalid URL", Context);

                    return;
                }

                using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
                string  assembledUrl = TopResultUrl + amount + ApiKey + HttpUtility.UrlEncode(url);
                dynamic keys         = JObject.Parse(await Client.GetStringAsync(assembledUrl));

                if (keys.header.status != 0)
                {
                    BuildSauceNaoError(keys, Context);
                    return;
                }

                JArray extUrls;

                string similarity, src;
                string extraData = "";

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

                for (int i = 0; i < amount; i++)
                {
                    similarity = (keys.results[i].header.similarity ?? "No similarity given").ToString();
                    src        = (keys.results[i].data.source ?? "").ToString();
                    extUrls    = keys.results[i].data.ext_urls;

                    if (extUrls != null)
                    {
                        extraData = (src == "" ? "" : ", ") + String.Join(", ", extUrls);
                    }

                    embedFields.Add(new EmbedFieldBuilder
                    {
                        Name     = "No. " + (i + 1),
                        IsInline = false,
                        Value    = similarity + "% (" + GetConfidenceString(float.Parse(similarity)) + ") - " + src + extraData
                    });

                    extraData = "";
                }

                EmbedBuilder embed = GetTemplate(keys, "SauceNAO of given image - Top " + amount, embedFields);

                await ReplyAsync("", false, embed.Build());
            }
Ejemplo n.º 5
0
        public async Task Inflections(string word, string langId = "en")
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            try
            {
                await GetJson(new DictInputs
                {
                    get     = "inflections",
                    langId  = langId,
                    word    = word,
                    filters = ""
                });

                dynamic keys = JObject.Parse(text);

                List <EmbedFieldBuilder> allInflections = new List <EmbedFieldBuilder>
                {
                    new()
                    {
                        Name     = "Word / Region",
                        Value    = $"{word } / {langId}",
                        IsInline = false
                    }
                };

                foreach (var inflection in keys.results[0].lexicalEntries)
                {
                    allInflections.Add(new EmbedFieldBuilder
                    {
                        Name  = "$Inflection of: {inflection.inflectionOf[0].id}",
                        Value = $"Type: {inflection.grammaticalFeatures[0].text }\n" +
                                $"Kind: {inflection.grammaticalFeatures[0].type}",
                        //grammaticalFeatures[0].text
                        //grammaticalFeatures[0].type
                        //inflectionOf[0].id
                        IsInline = false
                    });
                }

                //string _first_def = keys.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0].ToString();

                EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, "Oxford Dictionary API", "Inflections", Color.Orange);
                embed.Fields = allInflections;

                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception e)
            {
                await Util.Error.BuildError(e, Context);
            }
        }
Ejemplo n.º 6
0
            public async Task GetDetails(string url)
            {
                if (!Util.String.ValidateUrl(url))
                {
                    await Util.Error.BuildError("Invalid URL", Context);

                    return;
                }

                using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
                string  assembledUrl = SingleResultUrl + ApiKey + HttpUtility.UrlEncode(url);
                dynamic keys         = JObject.Parse(await Client.GetStringAsync(assembledUrl));

                if (keys.header.status != 0)
                {
                    BuildSauceNaoError(keys, Context);
                    return;
                }

                string src = (keys.results[0].data.source ?? (keys.results[0].data.ext_urls[0] ?? "?")).ToString();

                if (src == "?")
                {
                    await ReplyAsync($"SauceNAO didn't give me a source...\n{GetRequestsLeft(keys, RequestsLeftType.Message)}");

                    return;
                }

                List <EmbedFieldBuilder> embedFields = new List <EmbedFieldBuilder>
                {
                    new() { Name = "Similarity", IsInline = true, Value = (keys.results[0].header.similarity ?? "Not given").ToString() },
                    new() { Name = "Source", IsInline = true, Value = (keys.results[0].data.source ?? "Not given").ToString() },
                    new() { Name = "Thumbnail", IsInline = true, Value = (keys.results[0].header.thumbnail ?? "Not given").ToString() },
                    new() { Name = "Index", IsInline = true, Value = (keys.results[0].header.index_id ?? "ID Not given").ToString() + "\n" + (keys.results[0].header.index_name ?? "Name Not given").ToString() },
                    new() { Name = "Title", IsInline = true, Value = (keys.results[0].data.title ?? "Not given").ToString() },
                    new() { Name = "Extra Links", IsInline = true, Value = String.Join(", ", (JArray)keys.results[0].data.ext_urls).ToString() }
                };

                EmbedBuilder embed = GetTemplate(keys, "SauceNAO of given image - Detailed output", embedFields);

                await ReplyAsync("", false, embed.Build());
            }
Ejemplo n.º 7
0
        public async Task News(int appid, int cap = 5)
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            try
            {
                KeyValue news = SteamNewsInterface.GetNewsForApp0002(appid: appid);

                news = news["newsitems"];
                int amount = System.Math.Min(System.Math.Min(news.Children.Count, cap), 5);

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

                for (int i = 0; i < amount; i++)
                {
                    Uri articleUri = new Uri(news.Children[i]["url"].AsString() ?? string.Empty);

                    string label = "";
                    if (news.Children[i]["feedlabel"].AsString() != "Community Announcements")
                    {
                        label = "\n*(" + news.Children[i]["feedlabel"].AsString() + ")*";
                    }

                    articleDetails.Add(new EmbedFieldBuilder
                    {
                        Name  = news.Children[i]["title"].AsString() + label,
                        Value = "[Go to article (" + articleUri.Host + ")](" +
                                news.Children[i]["url"].AsString() + ")"
                    });
                }

                EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, $"Latest {amount} news articles for the app: {ReturnAppName(appid)}", "Data obtained Steam WebAPI using SteamKit2", Color.DarkBlue);
                embed.Fields = articleDetails;

                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception exp)
            {
                await Util.Error.BuildError(exp, Context);
            }
        }
Ejemplo n.º 8
0
Archivo: Help.cs Proyecto: xubiod/xubot
        public async Task Search(string lookup, bool deep = true, int page = 1)
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            if (page < 1)
            {
                page = 1;
            }
            int itemsPerPage = src.BotSettings.Global.Default.EmbedListMaxLength;

            List <CommandInfo> commList    = Program.XuCommand.Commands.ToList();
            List <CommandInfo> compatibles = new List <CommandInfo>();

            bool add;

            foreach (CommandInfo cmd in commList)
            {
                add = false;

                add |= cmd.Name.Contains(lookup);

                if (cmd.Aliases != null && deep)
                {
                    foreach (string alias in cmd.Aliases)
                    {
                        add |= alias.Contains(lookup);
                    }
                }

                if (add)
                {
                    compatibles.Add(cmd);
                }
            }

            int limit = System.Math.Min(commList.Count - (page - 1) * itemsPerPage, itemsPerPage);
            int index;

            string cmds = "";

            for (int i = 0; i < limit; i++)
            {
                index = i + itemsPerPage * (page - 1);

                if (index > compatibles.Count - 1)
                {
                    break;
                }

                cmds += GetAllGroups(compatibles[index].Module) + compatibles[index].Name + "\n";
            }
            if (cmds == "")
            {
                cmds = "I don't think any command called that exists...";
            }

            EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, "Help - Search", $"Showing page #{page} out of {System.Math.Ceiling((float)compatibles.Count / itemsPerPage)} pages.\nShowing a few of the **{compatibles.Count}** cmds with the lookup.", Color.Magenta);

            embed.Fields = new List <EmbedFieldBuilder>
            {
                new()
                {
                    Name     = "Search Results",
                    Value    = $"```\n{cmds}```",
                    IsInline = true
                }
            };

            await ReplyAsync("", false, embed.Build());
        }
Ejemplo n.º 9
0
        public async Task List()
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            try
            {
                await GetJson(new DictInputs
                {
                    get = "languages"
                });

                dynamic keys = JObject.Parse(text);

                List <string> allMonolingualDictionaries = new List <string>();
                List <string> allBilingualDictionaries   = new List <string>();

                foreach (var key in keys.results)
                {
                    if (key.targetLanguage != null)
                    {
                        allBilingualDictionaries.Add($"{key.source } ({key.sourceLanguage.language } (**{key.sourceLanguage.id }**) => {key.targetLanguage.language } (**{key.targetLanguage.id }**))\n".ToString());
                    }
                    else
                    {
                        allMonolingualDictionaries.Add($"{key.source } ({key.sourceLanguage.language } (**{key.sourceLanguage.id }**))\n".ToString());
                    }
                }

                //string _first_def = keys.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0].ToString();

                string monolingualListString0 = "";
                string monolingualListString1 = "";

                string bilingualListString0 = "";
                string bilingualListString1 = "";

                int count = 0;

                foreach (var dictionary in allMonolingualDictionaries)
                {
                    if (count < 10)
                    {
                        monolingualListString0 += dictionary;
                    }
                    else
                    {
                        monolingualListString1 += dictionary;
                    }
                    count++;
                }

                count = 0;

                foreach (var dictionary in allBilingualDictionaries)
                {
                    if (count < 10)
                    {
                        bilingualListString0 += dictionary;
                    }
                    else
                    {
                        bilingualListString1 += dictionary;
                    }
                    count++;
                }

                EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, "Oxford Dictionary API", "Dictionaries: Complete List (IDs in bold)", Color.Orange);
                embed.Fields = new List <EmbedFieldBuilder>
                {
                    new()
                    {
                        Name     = "Monolingual (pt 1)",
                        Value    = monolingualListString0,
                        IsInline = true
                    },
                    new()
                    {
                        Name     = "Monolingual (pt 2)",
                        Value    = monolingualListString1,
                        IsInline = true
                    },
                    new()
                    {
                        Name     = "Bilingual (pt 1)",
                        Value    = bilingualListString0,
                        IsInline = true
                    },
                    new()
                    {
                        Name     = "Bilingual (pt 2)",
                        Value    = bilingualListString1,
                        IsInline = true
                    }
                };

                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception e)
            {
                await Util.Error.BuildError(e, Context);
            }
        }
Ejemplo n.º 10
0
        public async Task User(ulong id)
        {
            using Util.WorkingBlock wb = new Util.WorkingBlock(Context);
            try
            {
                KeyValue ownedGames      = PlayerServiceInterface.GetOwnedGames(steamid: id, include_appinfo: 1);
                KeyValue playerSummaries = SteamUserInterface.GetPlayerSummaries002(steamids: id);
                KeyValue playerLevel     = PlayerServiceInterface.GetSteamLevel(steamid: id);

                playerSummaries = playerSummaries["players"].Children[0];

                decimal twoWeeks = 0;
                decimal forever  = 0;

                string  mostTimeIn = "";
                decimal mostTime   = 0;

                string  mostWeekIn = "";
                decimal mostWeek   = 0;

                EmbedFieldBuilder mostWeekField = new EmbedFieldBuilder {
                    Name = "Most Playtime (2 wks)", Value = "Has not played in last 2 weeks.", IsInline = true
                };
                EmbedFieldBuilder mostTimeField = new EmbedFieldBuilder {
                    Name = "Most Playtime (forever)", Value = "Has not played since account creation (Wha...?)", IsInline = true
                };

                foreach (KeyValue game in ownedGames["games"].Children)
                {
                    forever  += game["playtime_forever"].AsInteger();
                    twoWeeks += game["playtime_2weeks"].AsInteger();

                    if (game["playtime_forever"].AsInteger() > mostTime)
                    {
                        mostTime   = game["playtime_forever"].AsInteger();
                        mostTimeIn = game["name"].AsString();
                    }

                    if (game["playtime_2weeks"].AsInteger() > mostWeek)
                    {
                        mostWeek   = game["playtime_2weeks"].AsInteger();
                        mostWeekIn = game["name"].AsString();
                    }
                }

                if (mostWeekIn != "")
                {
                    mostWeekField.Value = $"In App\n**__{mostWeekIn}__**: {mostWeek:#,###} minutes\n{mostWeek / 60:#,###0.0} hours";
                }

                if (mostTimeIn != "")
                {
                    mostTimeField.Value = $"In App\n**__{mostTimeIn}__**: {mostTime:#,###} minutes\n{mostTime / 60:#,###0.0} hours";
                }

                ulong    lastLogOffUnsigned = playerSummaries["lastlogoff"].AsUnsignedLong();
                DateTime lastLogOff         = Util.UnixTimeStampToDateTime(lastLogOffUnsigned);

                ulong    timeCreatedUnsigned = playerSummaries["timecreated"].AsUnsignedLong();
                DateTime timeCreated         = Util.UnixTimeStampToDateTime(timeCreatedUnsigned);

                TimeSpan lastLogOffToNow = DateTime.Now - lastLogOff;
                TimeSpan createdToNow    = DateTime.Now - timeCreated;

                string playing = "";
                if (playerSummaries["gameid"].AsInteger() != 0)
                {
                    playing = $"Currently playing **{ReturnAppName(playerSummaries["gameid"].AsInteger())}**";
                }

                EmbedBuilder embed = Util.Embed.GetDefaultEmbed(Context, $"Steam User: {playerSummaries["personaname"].AsString()} ({id.ToString()})", "Data obtained Steam WebAPI using SteamKit2", Color.DarkBlue);
                embed.ThumbnailUrl = playerSummaries["avatarfull"].AsString();

                if (playerSummaries["communityvisibilitystate"].AsInteger(1) == 3 /* public, don't ask why */)
                {
                    embed.Fields = new List <EmbedFieldBuilder>
                    {
                        new()
                        {
                            Name  = "Current Stats",
                            Value = $"Currently __{GetStatus(playerSummaries["personastate"].AsInteger())}__\n" +
                                    $"Level **{playerLevel["player_level"].AsString()}**\n**" +
                                    $"{ownedGames["game_count"].AsString()}** products\n**" +
                                    $"{GetFriendSlots(playerLevel["player_level"].AsInteger())}** friend slots" +
                                    $"{playing}",
                            IsInline = true
                        },
                        new()
                        {
                            Name     = "Playtime (2 wks)",
                            Value    = $"{twoWeeks:#,##0} minutes\n{twoWeeks / 60:#,###0.0} hours",
                            IsInline = true
                        },
                        new()
                        {
                            Name     = "Playtime (forever)",
                            Value    = $"{forever:#,##0} minutes\n{forever / 60:#,###0.0} hours\n{forever / 1440:#,###0.00} days",
                            IsInline = true
                        },
                        mostWeekField,
                        mostTimeField,
                        new()
                        {
                            Name  = "Last Logoff",
                            Value = $"{lastLogOff.ToShortDateString()} {lastLogOff.ToShortTimeString()}\n(" +
                                    $"{System.Math.Round(lastLogOffToNow.TotalHours*100/100).ToString(CultureInfo.CurrentCulture)} hours)",
                            IsInline = true
                        },
                        new()
                        {
                            Name  = "Time Created",
                            Value = $"{timeCreated.ToShortDateString()} {timeCreated.ToShortTimeString()}\n(" +
                                    $"{createdToNow.TotalDays / 365:#,###.00} years)",
                            IsInline = true
                        }
                    };
                }
                else
                {
                    embed.Fields = new List <EmbedFieldBuilder>
                    {
                        new()
                        {
                            Name     = "Current Stats",
                            Value    = $"**This user's profile is private.**\nCurrently __{GetStatus(playerSummaries["personastate"].AsInteger())}__",
                            IsInline = false
                        },
                        new()
                        {
                            Name  = "Last Logoff",
                            Value = $"{lastLogOff.ToShortDateString()} {lastLogOff.ToShortTimeString()}\n(" +
                                    $"{System.Math.Round(lastLogOffToNow.TotalHours*100/100).ToString(CultureInfo.CurrentCulture)} hours)",
                            IsInline = false
                        }
                    };
                }

                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception ex)
            {
                await Util.Error.BuildError(ex, Context);
            }
        }