Esempio n. 1
0
        public DiscordEmbed UserToEmbed(GUser user, GStatistics stats, List <GScore> scores = null)
        {
            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder();

            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"**Server:** gatari");
            sb.AppendLine($"**Rank:** `{stats.rank}` ({user.country} `#{stats.country_rank}`)");
            sb.AppendLine($"**Level:** `{stats.level}` + `{stats.level_progress}%`");
            sb.AppendLine($"**PP:** `{stats.pp} PP` **Acc**: `{Math.Round(stats.avg_accuracy, 2)}%`");
            sb.AppendLine($"**Playcount:** `{stats.playcount}` (`{(Math.Round((double)stats.playtime / 3600))}` hrs)");
            sb.AppendLine($"**Ranks**: {osuEmoji.RankingEmoji("XH")}`{stats.xh_count}` {osuEmoji.RankingEmoji("X")}`{stats.x_count}` {osuEmoji.RankingEmoji("SH")}`{stats.sh_count}` {osuEmoji.RankingEmoji("S")}`{stats.s_count}` {osuEmoji.RankingEmoji("A")}`{stats.a_count}`\n");
            //sb.AppendLine($"**Playstyle:** {user.play string.Join(", ", user.playstyle)}\n");
            sb.AppendLine("Top 5 scores:");

            if (scores != null && scores?.Count != 0)
            {
                double avg_pp = 0;
                for (int i = 0; i < scores.Count; i++)
                {
                    GScore s = scores[i];

                    string mods = string.Join(' ', s.mods);
                    if (string.IsNullOrEmpty(mods))
                    {
                        mods = "NM";
                    }

                    sb.AppendLine($"{i + 1}: __[{s.beatmap.song_name}](https://osu.gatari.pw/b/{s.beatmap.beatmap_id})__ **{mods}** - {s.beatmap.difficulty}★");
                    sb.AppendLine($"▸ {osuEmoji.RankingEmoji(s.ranking)} ▸ `{s.pp} PP` ▸ **[{s.count_300}/{s.count_100}/{s.count_50}]**");

                    avg_pp += s.pp ?? 0;
                }
                sb.AppendLine($"\nAvg: `{Math.Round(avg_pp / 5, 2)} PP`");
            }
            embedBuilder.WithTitle(user.username)
            .WithUrl($"https://osu.gatari.pw/u/{user.id}")
            .WithThumbnail($"https://a.gatari.pw/{user.id}?{new Random().Next(1000, 9999)}")
            .WithDescription(sb.ToString());

            return(embedBuilder.Build());;
        }
Esempio n. 2
0
        /// <summary>
        /// Get user statistics by nickname
        /// </summary>
        /// <param name="user">User's id</param>
        /// <param name="mode">Mode: 0: osu, 1: taiko, 2: ctb, 3: mania</param>
        /// <returns>Profile statistics</returns>
        public GStatistics GetUserStats(string user, int mode = 0)
        {
            IRestRequest req = new RestRequest(UrlBase + $@"user/stats")
                               .AddParameter("u", user)
                               .AddParameter("mode", mode);

            IRestResponse resp = client.Execute(req);

            GStatistics stats = null;

            try
            {
                GUserStatsResponse g_resp = JsonConvert.DeserializeObject <GUserStatsResponse>(resp.Content);
                stats = g_resp?.stats;
            }
            catch (Exception)
            {
                return(null);
            }

            return(stats);
        }
Esempio n. 3
0
        private async Task Client_MessageCreated(DiscordClient sender, DSharpPlus.EventArgs.MessageCreateEventArgs e)
        {
            if (!e.Message.Content.Contains("http"))
                return;

            if (!(e.Channel.Name.Contains("-osu") ||
                  e.Channel.Name.Contains("map-offer") ||
                  e.Channel.Name.Contains("bot-debug") ||
                  e.Channel.Name.Contains("dev-announce") ||
                  e.Channel.Name.Contains("www-register")))
                return;

            // Check, if it is map url from bancho
            Tuple<int, int> BMSandBMid = utils.GetBMandBMSIdFromBanchoUrl(e.Message.Content);
            if (!(BMSandBMid is null))
            {
                int bms_id = BMSandBMid.Item1,
                    bm_id = BMSandBMid.Item2;

                Beatmap bm = api.GetBeatmap(bm_id);
                Beatmapset bms = api.GetBeatmapset(bms_id);
                GBeatmap gbm = gapi.TryGetBeatmap(bm_id);

                if (!(bm is null || bms is null))
                {
                    DiscordEmbed embed = utils.BeatmapToEmbed(bm, bms, gbm);
                    await e.Message.RespondAsync(embed: embed);
                }

                return;
            }

            // Check, if it is beatmapset url from gatari
            int? BMSid = utils.GetBMSIdFromGatariUrl(e.Message.Content);
            if (!(BMSid is null))
            {
                int bms_id = (int)BMSid;

                Beatmapset bms = api.GetBeatmapset(bms_id);

                int bm_id = bms.beatmaps.First().id;

                Beatmap bm = api.GetBeatmap(bm_id);
                GBeatmap gbm = gapi.TryGetBeatmap(bm_id);

                if (!(bm is null || bms is null))
                {
                    DiscordEmbed embed = utils.BeatmapToEmbed(bm, bms, gbm);
                    await e.Message.RespondAsync(embed: embed);
                }

                return;
            }

            // Check, if it is beatmap url from gatari
            int? BMid = utils.GetBMIdFromGatariUrl(e.Message.Content);
            if (!(BMid is null))
            {
                int bm_id = (int)BMid;

                Beatmap bm = api.GetBeatmap(bm_id);
                Beatmapset bms = api.GetBeatmapset(bm.beatmapset_id);
                GBeatmap gbm = gapi.TryGetBeatmap(bm_id);

                if (!(bm is null || bms is null))
                {
                    DiscordEmbed embed = utils.BeatmapToEmbed(bm, bms, gbm);
                    await e.Message.RespondAsync(embed: embed);
                }

                return;
            }

            // Check, if it is user link from bancho
            int? userId = utils.GetUserIdFromBanchoUrl(e.Message.Content);
            if (!(userId is null))
            {
                int user_id = (int)userId;

                User user = null;
                if (!api.TryGetUser(user_id, ref user))
                    return;

                List<Score> scores = api.GetUserBestScores(user_id, 5);

                if (!(scores is null) && scores.Count == 5)
                {
                    DiscordEmbed embed = utils.UserToEmbed(user, scores);
                    await e.Message.RespondAsync(embed: embed);
                }

                return;
            }

            // Check, if it is user link from bancho
            int? guserId = utils.GetUserIdFromGatariUrl(e.Message.Content);
            if (!(guserId is null))
            {
                int guser_id = (int)guserId;

                GUser guser = null;
                if (!gapi.TryGetUser(guser_id, ref guser))
                    return;

                List<GScore> gscores = gapi.GetUserBestScores(guser.id, 5);
                if (gscores is null || gscores.Count == 0)
                    return;

                GStatistics gstats = gapi.GetUserStats(guser.username);
                if (gstats is null)
                    return;

                DiscordEmbed gembed = utils.UserToEmbed(guser, gstats, gscores);
                await e.Message.RespondAsync(embed: gembed);
                return;
            }
        }
Esempio n. 4
0
        public async Task OsuProfile(InteractionContext ctx,
                                     [Option("nickname", "Никнейм юзера")] string nickname,
                                     [Choice("Bancho server", "bancho")]
                                     [Choice("Gatari server", "gatari")]
                                     [Option("server", "Возможные параметры: bancho, gatari")] string args)
        {
            if (!(ctx.Channel.Name.Contains("-bot") || ctx.Channel.Name.Contains("dev-announce")))
            {
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().WithContent("Использование данной команды запрещено в этом текстовом канале. Используйте специально отведенный канал для ботов, связанных с osu!.")
                                              .AsEphemeral(true));

                return;
            }

            if (string.IsNullOrEmpty(nickname))
            {
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().WithContent("Вы ввели пустой никнейм..")
                                              .AsEphemeral(true));

                return;
            }

            if (args.Contains("gatari"))
            {
                GUser guser = null;
                if (!gapi.TryGetUser(nickname, ref guser))
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о пользователе `{nickname}`.")
                                                  .AsEphemeral(true));;
                    return;
                }

                List <GScore> gscores = gapi.GetUserBestScores(guser.id, 5);
                if (gscores is null || gscores.Count == 0)
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о лучших скорах пользователя `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                GStatistics gstats = gapi.GetUserStats(guser.username);
                if (gstats is null)
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить статистику пользователя `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                DiscordEmbed gembed = utils.UserToEmbed(guser, gstats, gscores);
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().AddEmbed(gembed));

                return;
            }

            if (args.Contains("bancho"))
            {
                User user = null;
                if (!api.TryGetUser(nickname, ref user))
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о пользователе `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                List <Score> scores = api.GetUserBestScores(user.id, 5);

                if (scores is null || scores.Count == 0)
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о лучших скорах пользователя `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                DiscordEmbed embed = utils.UserToEmbed(user, scores);
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().AddEmbed(embed));
            }

            await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                          new DiscordInteractionResponseBuilder().WithContent("Введенный сервер не поддерживается или не существует.")
                                          .AsEphemeral(true));
        }
Esempio n. 5
0
        public async Task OsuProfile(CommandContext commandContext,
            [Description("Osu nickname")] string nickname,
            params string[] args)
        {
            if (!(commandContext.Channel.Name.Contains("-bot") || commandContext.Channel.Name.Contains("dev-announce")))
            {
                await commandContext.RespondAsync("Использование данной команды запрещено в этом текстовом канале. Используйте специально отведенный канал для ботов, связанных с osu!.");
                return;
            }

            if (string.IsNullOrEmpty(nickname))
            {
                await commandContext.RespondAsync("Вы ввели пустую строку.");
                return;
            }

            if (args.Contains("-gatari"))
            {
                GUser guser = null;
                if (!gapi.TryGetUser(nickname, ref guser))
                {
                    await commandContext.RespondAsync($"Не удалось получить информацию о пользователе `{nickname}`.");
                    return;
                }

                List<GScore> gscores = gapi.GetUserBestScores(guser.id, 5);
                if (gscores is null || gscores.Count == 0)
                {
                    await commandContext.RespondAsync($"Не удалось получить информацию о лучших скорах пользователя `{nickname}`.");
                    return;
                }

                GStatistics gstats = gapi.GetUserStats(guser.username);
                if (gstats is null)
                {
                    await commandContext.RespondAsync($"Не удалось получить статистику пользователя `{nickname}`.");
                    return;
                }

                DiscordEmbed gembed = utils.UserToEmbed(guser, gstats, gscores);
                await commandContext.RespondAsync(embed: gembed);
                return;
            }

            User user = null;
            if (!api.TryGetUser(nickname, ref user))
            {
                await commandContext.RespondAsync($"Не удалось получить информацию о пользователе `{nickname}`.");
                return;
            }

            List<Score> scores = api.GetUserBestScores(user.id, 5);

            if (scores is null || scores.Count == 0)
            {
                await commandContext.RespondAsync($"Не удалось получить информацию о лучших скорах пользователя `{nickname}`.");
                return;
            }

            DiscordEmbed embed = utils.UserToEmbed(user, scores);
            await commandContext.RespondAsync(embed: embed);

        }