Esempio n. 1
0
        public async Task OsuTrack(string gameModeStr)
        {
            OsuBoundUserDB boundUser = await OsuDB.GetBoundUserBy_DiscordID(Context.Message.Author.ID);

            if (boundUser == null)
            {
                await Context.Channel.SendMessageAsync($"You need to bind your osu account first with `{Context.Discord.PREFIX}OsuBind [player_name]`.");
            }
            else
            {
                OsuGameModes gameMode = OsuGameModesConverter.FromOfficialName(gameModeStr, true);

                OsuGameModeUserDB gameModeUser = await OsuDB.GetGameModeUserBy_OsuID(boundUser.UserID, gameMode);

                if (!boundUser.GameModes.HasFlag(gameMode))
                {
                    OsuUser osuUser = await OsuNetwork.DownloadUser(boundUser.UserID, gameMode);

                    await OsuDB.WriteOsuGameModeUser(osuUser, gameMode);

                    boundUser.GameModes |= gameMode;

                    await OsuDB.UpdateBoundOsuUser(osuUser, boundUser);

                    await Context.Channel.SendMessageAsync($"You are now being tracked for {Enum.GetName(typeof(OsuGameModes), gameMode)} gameplay.");
                }
                else
                {
                    await Context.Channel.SendMessageAsync($"You are already being tracked for {Enum.GetName(typeof(OsuGameModes), gameMode)} gameplay.");
                }
            }
        }
Esempio n. 2
0
        public async Task UserDetails(string osuUsername)
        {
            OsuUser[] _osuUser = _osuClient.GetUser(osuUsername);
            OsuUser   User     = _osuUser[0];

            var builder = new EmbedBuilder()
                          .WithTitle(User.username + " #" + User.pp_rank)
                          .WithDescription(User.osuchan)
                          .WithUrl(User.url)
                          .WithColor(new Color(0xDC98A4))
                          .WithThumbnailUrl(User.image)
                          .AddInlineField("<:osu:518082419195117584>", "o!Standard")
                          .AddInlineField(":taiko:", "o!Mania")
                          .AddInlineField(":ctb:", "o!Taiko")
                          .AddInlineField(":mania:", "o!CTB")

                          .WithTimestamp(DateTimeOffset.FromUnixTimeMilliseconds(1543589102163))
                          .WithFooter(footer => {
                footer
                .WithText("Osu! API")
                .WithIconUrl("https://github.com/Xferno2/CSharpOsu");
            })
            ;
            var embed = builder.Build();
            await Context.Channel.SendMessageAsync("",
                                                   embed : embed)
            .ConfigureAwait(false);

            //Console.WriteLine();
            //await Context.Channel.SendMessageAsync("Osu! API: " + _osuUser[0].username + " " + _osuUser[0].country);
        }
Esempio n. 3
0
        public override object CommandHandler(SocketMessage socketMessage, string input, CommandArguments arguments)
        {
            if (string.IsNullOrEmpty(input) || input.Length <= 3)
            {
                return("Please enter a username to connect to");
            }

            OsuUser osuUser = OsuApi.GetUser(input);

            if (osuUser == null)
            {
                return("Unable to find any user with this username");
            }

            InternalUser internalUser = DatabaseManager.Instance.GetUser(socketMessage.Author.Id);

            if (string.IsNullOrEmpty(internalUser.OsuUserID))
            {
                internalUser.OsuUserID = osuUser.ID.ToString();
                return("Registered '" + osuUser.Name + "' to your profile, " + socketMessage.Author.Mention);
            }
            else
            {
                internalUser.OsuUserID = osuUser.ID.ToString();
                return("Changed connection to '" + osuUser.Name + "' on your profile, " + socketMessage.Author.Mention);
            }
        }
Esempio n. 4
0
        private static async Task <string> FormatBaseScoreUrl(Input input, string api)
        {
            string limit;

            if (input.IsPassOnly || input.IsRecentSorting && input.Command != "top")
            {
                limit = "50";
            }
            else if (input.IsRecentSorting && input.Command == "top")
            {
                limit = "100";
            }
            else if (input.IsList)
            {
                limit = (input.Page * 5).ToString();
            }
            else
            {
                limit = input.Page.ToString();
            }

            OsuUser osuUser = await CheckOsuUser(input);

            return(apiUrl +
                   api +
                   keyParameter +
                   gamemodeParameter + input.Gamemode +
                   userParameter + osuUser.Identifier +
                   typeParameter + osuUser.Type +
                   limitParameter + limit);
        }
Esempio n. 5
0
        private static async Task <OsuUser> CheckOsuUser(Input input)
        {
            if (!string.IsNullOrEmpty(input.AnyString))
            {
                return(new OsuUser()
                {
                    Identifier = input.AnyString,
                    Type = "string"
                });
            }
            else
            {
                string osuName = await Database.GetOsuUser(input.DiscordUserId);

                if (string.IsNullOrEmpty(osuName))
                {
                    throw new Exception("No user provided");
                }

                var osuUser = new OsuUser()
                {
                    Identifier = osuName,
                    Type       = "id"
                };

                return(osuUser);
            }
        }
Esempio n. 6
0
        private async void CheckUserUpdateAsync(OsuUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("Invalid username.", nameof(user));
            }

            if (_oldOsuData != null &&
                _oldOsuData.Rank != user.Rank &&
                Math.Abs(user.PP - _oldOsuData.PP) >= 0.1)
            {
                var rankDiff = user.Rank - _oldOsuData.Rank;
                var ppDiff   = user.PP - _oldOsuData.PP;

                var formatted = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", Math.Abs(ppDiff));
                var totalPP   = user.PP.ToString(CultureInfo.InvariantCulture);

                var rankMessage = $"{Math.Abs(rankDiff)} ranks (#{user.Rank}). ";
                var ppMessage   = $"PP: {(ppDiff < 0 ? "-" : "+")}{formatted}pp ({totalPP}pp)";

                var newRankMessage = new IrcMessage($"{user.Username} just {(rankDiff < 0 ? "gained" : "lost")} {rankMessage} {ppMessage}");

                await _twitch.SendMessageAsync(newRankMessage);
            }

            _oldOsuData = user;
        }
Esempio n. 7
0
 public VerifyEmbed(SocketGuildUser user, OsuUser osuUser)
 {
     Title       = $"Hi {user.Username}!";
     Description = $"Verify your osu! account to get cool roles on {user.Guild.Name}!";
     AddField("Link", osuUser.Url);
     ThumbnailUrl = "https://osufriends.ovh/img/favicon.gif";
     Color        = EmbedColors.Important;
 }
        //Prepare a new session
        public void PrepareSession(Session session = null)
        {
            SessionThread?.Join();

            if (session == null)
            {
                CurrentSession = new Session
                {
                    Username = SettingsManager.Instance.Settings["api"]["user"]
                };
            }
            else
            {
                CurrentSession = session;
            }

            if (CurrentSession.ReadOnly)
            {
                OsuUser currentUserData = null;
                try
                {
                    currentUserData = OsuApi.GetUser(CurrentSession.Username, (OsuMode)Enum.Parse(typeof(OsuMode), SettingsManager.Instance.Settings["api"]["gamemode"]));
                }
                catch (Exception)
                {
                    BrowserViewModel.Instance.SendNotification(NotificationType.Danger, StringStorage.Get("Message.UserDataError"));
                    return;
                }
                BrowserViewModel.Instance.ApplySession(CurrentSession);
                BrowserViewModel.Instance.ApplyUser(currentUserData);

                StopProgressHandler();
                BrowserViewModel.Instance.AttachedJavascriptWrapper.Hide("#sessionProgressTime");
                BrowserViewModel.Instance.AttachedJavascriptWrapper.Show("#sessionProgressReadonly");

                string startDate = DateTimeOffset.FromUnixTimeSeconds(CurrentSession.SessionDate).ToString("MMMM dd yyyy HH:mm:ss");
                string endDate   = DateTimeOffset.FromUnixTimeSeconds(CurrentSession.SessionEndDate).ToString("MMMM dd yyyy HH:mm:ss");

                BrowserViewModel.Instance.AttachedJavascriptWrapper.SetHtml("#sessionProgressReadonlyText", startDate + " to " + endDate);
            }
            else
            {
                SessionThread = new ExtendedThread(() => OnUpdate(), Convert.ToInt32(SettingsManager.Instance.Settings["api"]["updateRate"]));

                lastIteration = DateTimeOffset.Now.ToUnixTimeSeconds();
                nextIteration = DateTimeOffset.Now.ToUnixTimeSeconds() + SessionThread.SleepTime;

                StartProgressHandler();
                SessionThread.Start();

                BrowserViewModel.Instance.AttachedJavascriptWrapper.Hide("#sessionProgressReadonly");

                if (SettingsManager.Instance.Settings["display"]["showTimer"] == "true")
                {
                    BrowserViewModel.Instance.AttachedJavascriptWrapper.Show("#sessionProgressTime");
                }
            }
        }
Esempio n. 9
0
 public static int GetUser(string osuId, out OsuUser user)
 {
     OsuUser[] list = GetUserList(osuId);
     if (list.Length == 0)
     {
         user = null;
         return 0;
     }
     user = list[0];
     return list.Length;
 }
Esempio n. 10
0
 public int GetUser(UserComponent nameOrId, out OsuUser user)
 {
     OsuUser[] list = GetUserList(nameOrId);
     if (list.Length == 0)
     {
         user = null;
         return(0);
     }
     user = list[0];
     return(list.Length);
 }
        private async Task <OsuUser> CreateOsuUserFromUserDataAsync(UserData userData)
        {
            OsuUser osuUser = _osuFriends.CreateUser(userData.OsuFriendsKey);
            Status? status  = await osuUser.GetStatusAsync();

            _logger.LogTrace("OsuDb Status: {status}", status);
            if (status != Status.Completed)
            {
                return(null);
            }
            return(osuUser);
        }
        private async Task <OsuUser> CreateOsuUserAsync()
        {
            for (int tries = 0; tries < 30; tries++)
            {
                OsuUser osuUser = _osuFriends.CreateUser();
                Status? status  = await osuUser.GetStatusAsync();

                _logger.LogTrace("Verification Status: {status}", status);

                if (status == Status.Invalid)
                {
                    return(osuUser);
                }
            }
            return(null);
        }
Esempio n. 13
0
        public async Task <OsuUserDetails> GetDetailsAsync(OsuUser user)
        {
            UriBuilder uriBuilder = new UriBuilder(url);

            uriBuilder.Path += "details/";

            NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query["key"]     = user.Key.ToString();
            query["secret"]  = _token;
            uriBuilder.Query = query.ToString();

            HttpResponseMessage response = await _httpClient.GetAsync(uriBuilder.Uri).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            return(JsonConvert.DeserializeObject <OsuUserDetails>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)));
        }
Esempio n. 14
0
        protected void ApplyPlayer(ulong DiscordID, string input)
        {
            _osuUser = null;
            if (string.IsNullOrEmpty(input))
            {
                InternalUser internalUser = DatabaseManager.Instance.GetUser(DiscordID);
                if (!string.IsNullOrEmpty(internalUser.OsuUserID))
                {
                    _osuUser = OsuApi.GetUser(internalUser.OsuUserID, _osuMode);
                }
            }

            if (_osuUser == null)
            {
                string username = HttpUtility.HtmlEncode(input); // Test value
                _osuUser = OsuApi.GetUser(username, _osuMode);
            }
        }
        private async Task <bool> WaitForVerificationStatusAsync(OsuUser osuUser)
        {
            bool success = false;

            for (int retry = 0; retry < 60; retry++)
            {
                Status?status = await osuUser.GetStatusAsync();

                _logger.LogTrace("Verification Status: {@status}", status);
                if (status == Status.Completed)
                {
                    success = true;
                    break;
                }
                await Task.Delay(TimeSpan.FromSeconds(3));
            }
            return(success);
        }
Esempio n. 16
0
        public async Task OsuBindUser([Remainder] string input)
        {
            OsuBoundUserDB bound = await OsuDB.GetBoundUserBy_DiscordID(Context.Message.Author.ID);

            string[] args = input.Split(' ');

            if (args[0].ToLower() == "mainmode")
            {
                if (bound == null)
                {
                    await Context.Channel.SendMessageAsync("You need to bind your osu user first. `OsuBind [username]`");
                }
                else
                {
                    if (args.Length == 1)
                    {
                        await Context.Channel.SendMessageAsync("You need to specify a Game Mode type. It defaults to `standard`.");
                    }
                    else
                    {
                        OsuGameModes gameMode = OsuGameModesConverter.FromOfficialName(input.Substring(args[0].Length + 1), true);
                        bound.MainMode = gameMode;
                        await OsuDB.UpdateBoundOsuUser(bound);

                        await Context.Channel.SendMessageAsync($"Main mode has been successfully changed to **{OsuGameModesConverter.GameModeName(gameMode)}**!");
                    }
                }
            }
            else
            {
                OsuUser osuUser = await OsuNetwork.DownloadUser(input, OsuGameModes.STD);

                if (bound == null)
                {
                    await OsuDB.RegisterBoundOsuUser(osuUser, Context.Message.Author.ID);

                    await Context.Channel.SendMessageAsync($"Binded {input} to `{OsuSQL.table_name}`");
                }
                else
                {
                    await Context.Channel.SendMessageAsync($"{input} is already binded.");
                }
            }
        }
        private void OnUpdate()
        {
            if (!NetworkManager.Instance.HasConnection())
            {
                BrowserViewModel.Instance.SendNotification(NotificationType.Warning, StringStorage.Get("Message.NoInternet"));
                return;
            }

            //BrowserViewModel.Instance.SendNotification(NotificationType.Success, "Test: session iteration");
            OsuUser currentUserData = null;

            try
            {
                currentUserData = OsuApi.GetUser(CurrentSession.Username, (OsuMode)Enum.Parse(typeof(OsuMode), SettingsManager.Instance.Settings["api"]["gamemode"]));
            }
            catch (Exception)
            {
                BrowserViewModel.Instance.SendNotification(NotificationType.Danger, StringStorage.Get("Message.UserDataError"));
            }

            if (currentUserData != null)
            {
                if (CurrentSession.InitialData == null)
                {
                    CurrentSession.InitialData = SessionData.FromUser(currentUserData);
                }

                CurrentSession.CurrentData    = SessionData.FromUser(currentUserData);
                CurrentSession.DifferenceData = CurrentSession.CurrentData - CurrentSession.InitialData;

                BrowserViewModel.Instance.ApplySession(CurrentSession);
                BrowserViewModel.Instance.ApplyUser(currentUserData);

                int updateRate = Convert.ToInt32(SettingsManager.Instance.Settings["api"]["updateRate"]);
                if (updateRate != SessionThread.SleepTime)
                {
                    SessionThread.SleepTime = updateRate;
                }
            }

            lastIteration = DateTimeOffset.Now.ToUnixTimeSeconds();
            nextIteration = DateTimeOffset.Now.ToUnixTimeSeconds() + SessionThread.SleepTime;
        }
Esempio n. 18
0
        public static async Task <ScoreData[]> Score(Input input)
        {
            if (string.IsNullOrEmpty(input.BeatmapId))
            {
                throw new Exception("No beatmap ID provided");
            }

            string _modsParameter = "";

            if (input.ModRequestNumber.HasValue)
            {
                _modsParameter = modsParameter + input.ModRequestNumber;
            }

            OsuUser osuUser = await CheckOsuUser(input);

            string url = apiUrl +
                         "get_scores" +
                         keyParameter +
                         gamemodeParameter + input.Gamemode +
                         userParameter + osuUser.Identifier +
                         typeParameter + osuUser.Type +
                         beatmapIdParameter + input.BeatmapId +
                         _modsParameter;

            string html = await Mitty.Api.Call(url);

            ScoreData[] scores = JsonConvert.DeserializeObject <ScoreData[]>(html, settings);

            if (scores.Length == 0)
            {
                throw new Exception("No score found.");
            }

            if (input.IsRecentSorting)
            {
                return(scores.OrderByDescending(x => x.Date).ToArray());
            }
            else
            {
                return(scores);
            }
        }
Esempio n. 19
0
        internal async Task <OsuUserDetails> GetDetailsAsync(OsuUser user)
        {
            UriBuilder uriBuilder = new UriBuilder(Url);

            uriBuilder.Path += "details/";

            NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query["key"]     = user.Key.ToString();
            query["secret"]  = _token;
            uriBuilder.Query = query.ToString();

            _logger.LogTrace("Request details for {key}", user.Key);
            HttpResponseMessage response = await _httpClient.GetAsync(uriBuilder.Uri).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            _logger.LogTrace("Details of {key}: {details}", user.Key, content);
            return(JsonConvert.DeserializeObject <OsuUserDetails>(content));
        }
Esempio n. 20
0
        public static async Task <ScoreData[]> UserTop(Input input)
        {
            OsuUser osuUser = await CheckOsuUser(input);

            string url = apiUrl +
                         "get_user_best" +
                         keyParameter +
                         gamemodeParameter + input.Gamemode +
                         userParameter + osuUser.Identifier +
                         typeParameter + osuUser.Type +
                         limitParameter + "100";
            string html = await Mitty.Api.Call(url);

            ScoreData[] scores = JsonConvert.DeserializeObject <ScoreData[]>(html, settings);

            if (scores.Length == 0)
            {
                throw new Exception("No score found.");
            }

            return(scores);
        }
 public void ApplyUser(OsuUser user)
 {
     if (displayedUser == null || displayedUser.ID != user.ID)
     {
         BrowserViewModel.Instance.AttachedBrowser.ExecuteScriptAsyncWhenPageLoaded("$(\"#tab_session_loader_view\").show();");
         BrowserViewModel.Instance.AttachedBrowser.ExecuteScriptAsyncWhenPageLoaded("$(\"#tab_session_default_view\").hide();");
         RegionInfo countryInfo = new RegionInfo(user.CountryCode);
         string     query       = "" +
                                  "$('#sessionUsername').html('" + user.Name + "');" +
                                  //"$('#sessionFlag').attr('src', './img/flags/" + user.CountryCode + ".png');" +
                                  //"$('#sessionFlag').attr('data-original-title', '" + (countryInfo.DisplayName) + "');" +
                                  "$('#sessionFlag').html('<i data-toggle=\"tooltip\" title=\"" + countryInfo.DisplayName + "\" class=\"material-tooltip-main twf twf-s twf-" + user.CountryCode.ToLower() + "\"></i>');" +
                                  "$('#sessionProfileImage').attr('src', 'https://a.ppy.sh/" + user.ID + "');" +
                                  "$('#sessionHeaderImage').attr('src', '" + ApiHelper.GetOsuUserHeaderUrl("https://osu.ppy.sh/users/" + user.ID) + "');" +
                                  "$('[data-toggle=\"tooltip\"]').tooltip();" +
                                  "";
         AttachedBrowser.ExecuteScriptAsyncWhenPageLoaded(query);
         BrowserViewModel.Instance.AttachedBrowser.ExecuteScriptAsyncWhenPageLoaded("$(\"#tab_session_loader_view\").hide();");
         BrowserViewModel.Instance.AttachedBrowser.ExecuteScriptAsyncWhenPageLoaded("$(\"#tab_session_default_view\").show();");
         displayedUser = user;
     }
 }
Esempio n. 22
0
        public async Task Add([Remainder] string command = null)
        {
            if (command == null)
            {
                await Context.Channel.SendMessageAsync("닉네임을 입력해주세요!");

                return;
            }

            OsuUser[] Player = _client.GetUser(command);
            OsuUser   player = Player[0];
            Dictionary <string, string> pairs;

            if (player.pp_rank < 30000)
            {
                string json = File.ReadAllText("Resources/gbr.json");
                var    data = JsonConvert.DeserializeObject <dynamic>(json);

                pairs = data.ToObject <Dictionary <string, string> >();
                pairs.Add(player.username, player.pp_rank.ToString());
                string datas = JsonConvert.SerializeObject(pairs, Formatting.Indented);
                File.WriteAllText("Resources/gbr.json", datas);

                await Context.Channel.SendMessageAsync("GBR에 추가되었습니다.");
            }
            else
            {
                string json = File.ReadAllText("Resources/gbrc.json");
                var    data = JsonConvert.DeserializeObject <dynamic>(json);

                pairs = data.ToObject <Dictionary <string, string> >();
                pairs.Add(player.username, player.pp_rank.ToString());
                string datas = JsonConvert.SerializeObject(pairs, Formatting.Indented);
                File.WriteAllText("Resources/gbrc.json", datas);

                await Context.Channel.SendMessageAsync("GBRC에 추가되었습니다.");
            }
        }
Esempio n. 23
0
        public static async Task <UserData> User(Input input)
        {
            OsuUser osuUser = await CheckOsuUser(input);

            string url = apiUrl +
                         "get_user" +
                         keyParameter +
                         gamemodeParameter + input.Gamemode +
                         userParameter + osuUser.Identifier +
                         typeParameter + osuUser.Type +
                         eventDaysParameter + 31;

            string html = await Mitty.Api.Call(url);

            UserData[] userData = JsonConvert.DeserializeObject <UserData[]>(html, settings);

            if (userData.Length == 0)
            {
                throw new Exception("User not found");
            }

            return(userData[0]);
        }
Esempio n. 24
0
        public async Task Participate([Remainder] string command = null)
        {
            OsuUser[] Player = _client.GetUser(command);
            OsuUser   player = Player[0];

            if (player == null)
            {
                await Context.Channel.SendMessageAsync("닉네임을 입력해주세요!");
            }
            else
            {
                Dictionary <string, string> pairs = new Dictionary <string, string>();
                pairs.Add(Context.User.Username.ToString(), player.pp_rank.ToString());
                string data = JsonConvert.SerializeObject(pairs, Formatting.Indented);

                if (player.pp_rank < 30000)
                {
                    string json = "Resources/gbr.json";
                    File.WriteAllText(json, data);
                    var user = Context.User;
                    var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == "GBR PLAYER");
                    await Context.Channel.SendMessageAsync("GBR 신청이 완료되었습니다!");

                    await(user as IGuildUser).AddRoleAsync(role);
                }
                else
                {
                    string json = "Resources/gbrc.json";
                    File.WriteAllText(json, data);
                    var user = Context.User;
                    var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == "GBRC PLAYER");
                    await Context.Channel.SendMessageAsync("GBRC 신청이 완료되었습니다!");

                    await(user as IGuildUser).AddRoleAsync(role);
                }
            }
        }
Esempio n. 25
0
        private async Task MessageReceived(SocketMessage message)
        {
            if (message.Content.Contains("https://osu.ppy.sh/u"))
            {
                string    mes       = message.ToString();
                string[]  username  = mes.Split(new string[] { "sh/" }, StringSplitOptions.None);
                string[]  username2 = username[1].Split('/');
                OsuUser[] Player    = _osuclient.GetUser(username2[1]);
                OsuUser   player    = Player[0];

                if (player == null)
                {
                    await message.Channel.SendMessageAsync("올바른 유저페이지를 입력해주세요.");
                }
                else if (player.pp_rank < 30000)
                {
                    await message.Channel.SendMessageAsync($"**{player.username}** 님의 랭킹은 **#{player.pp_rank}**이며, GBR에 참가하실 수 있습니다.");

                    if (player.pp_rank < 10)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.2**로, 최종 배율은 **x0.8**으로 계산됩니다.");
                    }
                    else if (player.pp_rank < 30)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.19**로, 최종 배율은 **x0.81**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 60)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.18**으로, 최종 배율은 **x0.82**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 100)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.175**로, 최종 배율은 **x0.825**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 200)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.17**으로, 최종 배율은 **x0.83**으로 계산됩니다.");
                    }
                    else if (player.pp_rank < 400)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.165**로, 최종 배율은 **x0.835**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 700)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.15**로, 최종 배율은 **x0.85**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 1000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.12**로, 최종 배율은 **x0.88**으로 계산됩니다.");
                    }
                    else if (player.pp_rank < 2000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.095**로, 최종 배율은 **x0.905**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 4000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.065**로, 최종 배율은 **x0.935**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 7000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티는 **-0.04**로, 최종 배율은 **x0.96**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 10000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 패널티나 베네핏이 없습니다. 최종 배율은 **x1.00**으로 계산됩니다.");
                    }
                    else if (player.pp_rank < 15000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 베네핏은 **0.125**로, 최종 배율은 **x1.125**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 20000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 베네핏은 **0.25**로, 최종 배율은 **x1.25**로 계산됩니다.");
                    }
                    else if (player.pp_rank < 25000)
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 베네핏은 **0.375**로, 최종 배율은 **x1.375**로 계산됩니다.");
                    }
                    else
                    {
                        await message.Channel.SendMessageAsync("랭킹에 해당하는 베네핏은 **0.5**로, 최종 배율은 **x1.5**로 계산됩니다.");
                    }
                }
                else
                {
                    await message.Channel.SendMessageAsync($"**{player.username}** 님의 랭킹은 **#{player.pp_rank}**이며, GBRC에 참가하실 수 있습니다.");
                }
            }
            else
            {
                return;
            }
        }
        private async Task <(List <SocketRole>, OsuUserDetails)> GrantUserRolesAsync(SocketGuildUser user, OsuUser osuUser)
        {
            OsuUserDetails osuUserDetails = await osuUser.GetDetailsAsync();

            _logger.LogTrace("Details: {@details}", osuUserDetails);
            IReadOnlyCollection <SocketRole> guildRoles = user.Guild.Roles;
            // Find roles that user should have
            List <SocketRole> roles = OsuRoles.FindUserRoles(guildRoles, osuUserDetails);
            // Remove roles that user shouldn't have
            await user.RemoveRolesAsync(OsuRoles.FindAllRoles(guildRoles).Where(role => user.Roles.Contains(role) && !roles.Contains(role)));

            // Add roles that user should have
            await user.AddRolesAsync(roles.Where(role => !user.Roles.Contains(role)));

            // Change user nickname to that from game

            // Ignore if can't change nickname
            try
            {
                await user.ModifyAsync(properties => properties.Nickname = osuUserDetails.Username);
            }
            catch (HttpException)
            {
            }

            return(roles, osuUserDetails);
        }
        public async Task <RuntimeResult> VerifyAsync(SocketGuildUser user, SocketCommandContext context = null)
        {
            _logger.LogTrace("Verifying user: {username}", user.Username);

            try
            {
                bool isVeryfying = AddVerifyingUser(user);
                if (isVeryfying)
                {
                    return(new VerificationLockError());
                }
                UserData dbUser = _dbUserData.FindById(user.Id);
                _logger.LogTrace("DbUser : {@dbUser} | Id : {@user} | Username: {@username}", dbUser, user.Id, user.Username);

                OsuUser osuUser = null;

                if (dbUser.OsuFriendsKey != null)
                {
                    osuUser = await CreateOsuUserFromUserDataAsync(dbUser);
                }

                if (osuUser == null)
                {
                    // If user doesn't exist in db
                    osuUser = await CreateOsuUserAsync();

                    if (osuUser == null)
                    {
                        return(new VerificationUserIdError());
                    }
                    await user.SendMessageAsync(embed : new VerifyEmbed(user, osuUser).Build());

                    // Retry
                    bool success = await WaitForVerificationStatusAsync(osuUser);

                    if (!success)
                    {
                        RemoveVerifyingUser(user);
                        return(new VerificationTimeoutError(user.Guild));
                    }
                    // Verification Success
                    dbUser.OsuFriendsKey = osuUser.Key;
                }
                // Success for both
                (List <SocketRole> grantedRoles, OsuUserDetails osuUserDetails) = await GrantUserRolesAsync(user, osuUser);
                await SendEmbedMsg(user, context, embed : new GrantedRolesEmbed(user, grantedRoles, osuUserDetails, dbUser).Build());

                dbUser.Std   = osuUserDetails.Std;
                dbUser.Taiko = osuUserDetails.Taiko;
                dbUser.Ctb   = osuUserDetails.Ctb;
                dbUser.Mania = osuUserDetails.Mania;
                _dbUserData.Upsert(dbUser);
            }
            catch (HttpException e)
            {
                RemoveVerifyingUser(user);
                _logger.LogTrace("httpCode: {httpCode} | discordCode: {discordCode}", e.HttpCode, e.DiscordCode);
                switch (e.DiscordCode)
                {
                case 50007:
                    return(new DirectMessageError());

                default:
                    break;
                }
                throw;
            }
            catch
            {
                RemoveVerifyingUser(user);
                throw;
            }
            RemoveVerifyingUser(user);
            return(new SuccessResult());
        }
Esempio n. 28
0
 public static string GetUsernameByUid(string uid)
 {
     OsuUser userObj = GetUserList(uid).FirstOrDefault(k => k.user_id == uid);
     return userObj == null ? uid : userObj.username;
 }
Esempio n. 29
0
 public static string GetUidByUsername(string username)
 {
     OsuUser userObj = GetUserList(username).FirstOrDefault(k => k.username == username);
     return userObj?.user_id;
 }
Esempio n. 30
0
        public async Task Calculator([Remainder] string mes)
        {
            string[] spl   = mes.Split();
            float    score = float.Parse(spl[1]);

            OsuUser[] Player = _client.GetUser(spl[0]);
            OsuUser   player = Player[0];

            if (player.pp_rank < 10)
            {
                score *= 0.8f;
            }
            else if (player.pp_rank < 30)
            {
                score *= 0.81f;
            }
            else if (player.pp_rank < 60)
            {
                score *= 0.82f;
            }
            else if (player.pp_rank < 100)
            {
                score *= 0.825f;
            }
            else if (player.pp_rank < 200)
            {
                score *= 0.83f;
            }
            else if (player.pp_rank < 400)
            {
                score *= 0.835f;
            }
            else if (player.pp_rank < 700)
            {
                score *= 0.85f;
            }
            else if (player.pp_rank < 1000)
            {
                score *= 0.88f;
            }
            else if (player.pp_rank < 2000)
            {
                score *= 0.905f;
            }
            else if (player.pp_rank < 4000)
            {
                score *= 0.935f;
            }
            else if (player.pp_rank < 7000)
            {
                score *= 0.96f;
            }
            else if (player.pp_rank < 10000)
            {
            }
            else if (player.pp_rank < 15000)
            {
                score *= 1.125f;
            }
            else if (player.pp_rank < 20000)
            {
                score *= 1.25f;
            }
            else if (player.pp_rank < 25000)
            {
                score *= 1.375f;
            }
            else if (player.pp_rank < 30000)
            {
                score *= 1.5f;
            }
            else
            {
            }

            await Context.Channel.SendMessageAsync(score.ToString());
        }