示例#1
0
        /// <summary>
        /// Build embed from beatmap and beatmapset information
        /// </summary>
        /// <param name="bm">Beatmap object</param>
        /// <param name="bms">Beatmapset object</param>
        /// <param name="gBeatmap">Beatmap object from gatari (if exists)</param>
        /// <returns></returns>
        public DiscordEmbed BeatmapToEmbed(Beatmap bm, Beatmapset bms, GBeatmap gBeatmap = null)
        {
            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder();

            TimeSpan mapLen = TimeSpan.FromSeconds(bm.total_length);

            DiscordEmoji banchoRankEmoji = osuEmoji.RankStatusEmoji(bm.ranked);
            DiscordEmoji diffEmoji       = osuEmoji.DiffEmoji(bm.difficulty_rating);

            StringBuilder embedMsg = new StringBuilder();

            embedMsg.AppendLine($"{diffEmoji}  **__[{bm.version}]__**\n▸**Difficulty**: {bm.difficulty_rating}★\n▸**CS**: {bm.cs} ▸**HP**: {bm.drain} ▸**AR**: {bm.ar} ▸**OD**: {bm.accuracy}\n\nBancho: {banchoRankEmoji} : [link](https://osu.ppy.sh/beatmapsets/{bms.id}#osu/{bm.id})\nLast updated: {bm.last_updated}");
            if (!(gBeatmap is null))
            {
                DiscordEmoji gatariRankEmoji = osuEmoji.RankStatusEmoji(gBeatmap.ranked);
                embedMsg.AppendLine($"\nGatari: {gatariRankEmoji} : [link](https://osu.gatari.pw/s/{gBeatmap.beatmapset_id}#osu/{gBeatmap.beatmap_id})\nLast updated: {(gBeatmap.ranking_data != 0 ? new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(gBeatmap.ranking_data).ToString() : "")}");
            }

            // Construct embed
            embedBuilder.WithTitle($"{banchoRankEmoji}  {bms.artist} – {bms.title} by {bms.creator}");
            embedBuilder.WithUrl(bm.url);
            embedBuilder.AddField($"Length: {mapLen.Minutes}:{string.Format("{0:00}", mapLen.Seconds)}, BPM: {bm.bpm}",
                                  embedMsg.ToString(),
                                  true);
            embedBuilder.WithThumbnail(bms.covers.List2x);
            embedBuilder.WithFooter(bms.tags);

            return(embedBuilder.Build());
        }
示例#2
0
 public BeatmapsetPackage(Beatmapset beatmapset)
 {
     _beatmapsetId    = beatmapset.BeatmapsetId;
     Beatmapset       = beatmapset;
     Server           = Server.Unset;
     FailedServerList = new List <Server>();
 }
示例#3
0
        /// <summary>
        /// Get beatmapset by it's id
        /// </summary>
        /// <param name="beatmapsetId">Beatmapset id</param>
        /// <returns></returns>
        public Beatmapset GetBeatmapset(int beatmapsetId)
        {
            IRestRequest req = new RestRequest(UrlBase + $@"api/v2/beatmapsets/{beatmapsetId}")
                               .AddHeader(@"Authorization", $@"Bearer {Token}");

            IRestResponse resp = client.Execute(req);

            Beatmapset bm = JsonConvert.DeserializeObject <Beatmapset>(resp.Content);

            return(bm);
        }
示例#4
0
        public override CommonMessageResponse Message_Received(CommonMessage messageObj)
        {
            BllUserRole        bllUserRole = new BllUserRole();
            List <TblUserRole> userInfo    = bllUserRole.GetUserRoleByQq(long.Parse(messageObj.UserId));

            if (userInfo.Count == 0)
            {
                return(new CommonMessageResponse(LoliReply.IdNotBound, messageObj, true));
            }

            var id = userInfo[0].UserId.ToString();

            List <Beatmapset> totalList = new List <Beatmapset>();

            Beatmapset[] tmpArray;
            int          page  = 0;
            const int    count = 10;

            do
            {
                string json = WebRequestUtil.GetResponseString(
                    WebRequestUtil.CreateGetHttpResponse(
                        "https://osu.ppy.sh/users/" + id + "/beatmapsets/graveyard?offset=" + page + "&limit=" + count));
                Logger.Debug("GET JSON");

                tmpArray = JsonConvert.DeserializeObject <Beatmapset[]>(json);
                totalList.AddRange(tmpArray);
                page += count;

                if (tmpArray.Length != count)
                {
                    break;
                }
            } while (tmpArray.Length != 0);

            if (totalList.Count == 0)
            {
                return(new CommonMessageResponse("惊了,你竟然会没坑!", messageObj, true));
            }

            Random     rnd     = new Random();
            Beatmapset beatmap = totalList[rnd.Next(totalList.Count)];
            var        cqMusic = new CustomMusic("https://osu.ppy.sh/s/" + beatmap.Id, $"https://b.ppy.sh/preview/{beatmap.Id}.mp3", beatmap.Title,
                                                 $"{beatmap.Artist}\r\n({beatmap.FavouriteCount} fav)", $"https://b.ppy.sh/thumb/{beatmap.Id}l.jpg");

            return(new CommonMessageResponse(cqMusic.ToString(), messageObj));
        }
        /// <summary>
        /// Начинает отслеживание реакций сообщения с картинкой.
        /// </summary>
        /// <param name="message">Отслеживаемое изображение</param>
        /// <param name="attachment">Картинка</param>
        private async Task ExecuteMessageTrack(DiscordMessage message, DiscordAttachment attachment)
        {
            var res = await queue.QueueTask(() => DownloadAndRecognizeImage(attachment));

            if (res == null)
            {
                return;
            }

            Beatmapset banchoBeatmapset = res.Item1;
            Beatmap    banchoBeatmap    = res.Item2;

            // Ignore beatmap for several minutes
            foreach (var kvp in ignoreList)
            {
                if (DateTime.Now - kvp.Value > TimeSpan.FromMinutes(10))
                {
                    ignoreList.Remove(kvp.Key);
                }
            }

            if (ignoreList.ContainsKey(banchoBeatmap.id))
            {
                logger.LogInformation($"Beatmap is in ignore list {banchoBeatmap.id}");
                return;
            }

            ignoreList.Add(banchoBeatmap.id, DateTime.Now);

            // Contruct message
            DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder();

            TimeSpan mapLen = TimeSpan.FromSeconds(banchoBeatmap.total_length);

            DiscordEmoji banchoRankEmoji = emoji.RankStatusEmoji(banchoBeatmap.ranked);
            DiscordEmoji diffEmoji       = emoji.DiffEmoji(banchoBeatmap.difficulty_rating);

            // Check gatari
            GBeatmap gBeatmap = gapi.TryGetBeatmap(banchoBeatmap.id);

            DiscordEmbed embed = utils.BeatmapToEmbed(banchoBeatmap, banchoBeatmapset, gBeatmap);

            await message.RespondAsync(embed : embed);
        }
示例#6
0
        public static async Task <Beatmapset> GetBeatmapsetsByBidAsync(string bId)
        {
            OsuApiV2Client client = new OsuApiV2Client(OsuApiKey.UserName, OsuApiKey.Password);

            try
            {
                Beatmapset set = await client.GetBeatmapsetByBIdAsync(bId);

                return(set);
            }
            catch (NetworkFailException e)
            {
                if (e.InnerException.Message.Contains("404"))
                {
                    return(null);
                }
                throw;
            }
        }
示例#7
0
        private async Task AnimateRandomizing(Beatmapset selectedBeatmap)
        {
            int index = FindObservableCollectionIndex(BeatmapsetPool, p => p == selectedBeatmap);

            //Animating
            for (int i = 0; i < 5; i++)
            {
                foreach (var item in BeatmapsetPool)
                {
                    item.SetHighlighting(true);
                    await Task.Delay(200 *(i + 1));

                    item.SetHighlighting(false);
                }
            }

            for (int i = 0; i < index; i++)
            {
                var item = BeatmapsetPool[i];

                item.SetHighlighting(true);
                await Task.Delay(1000 *(i + 1));

                item.SetHighlighting(false);
            }

            //Choosing animation
            selectedBeatmap.SetHighlighting(true);
            await Task.Delay(2000);

            for (int i = 0; i < 5; i++)
            {
                selectedBeatmap.SetHighlighting(false);
                await Task.Delay(250);

                selectedBeatmap.SetHighlighting(true);
                await Task.Delay(250);
            }
            await Task.Delay(2000);

            return;
        }
示例#8
0
        static void Main(string[] args)
        {
            Recognizer rec = new Recognizer();

            Settings settings;

            using (StreamReader sr = new StreamReader("credentials.json"))
                settings = JsonConvert.DeserializeObject <Settings>(sr.ReadToEnd());

            BanchoApi api = new BanchoApi(settings.ClientId, settings.Secret);

            Console.WriteLine(api.ReloadToken());

            string[] dirFiles = Directory.GetFiles(@"./testImages/");

            foreach (string path in dirFiles)
            {
                Image img = rec.LoadFromFile(path);

                string[]          recedText = rec.RecognizeTopText(img).Split('\n');
                List <Beatmapset> bms       = api.Search(recedText.First(), WAV_Osu_NetApi.Bancho.QuerryParams.MapType.Any);

                foreach (string s in recedText)
                {
                    Console.WriteLine(s);
                }

                Beatmapset bm = bms?.First();

                if (bm is null)
                {
                    Console.WriteLine("No beatmap found");
                }
                else
                {
                    Console.WriteLine($"{bm.artist} - {bm.title}\n{bm.creator}");
                }
            }
        }
示例#9
0
 public DownloadPackage(Beatmapset beatmapset)
 {
     this.beatmapset = beatmapset;
 }
示例#10
0
 public BeatmapsetPackage(Beatmapset beatmapset, Server server)
 {
     _beatmapsetId    = beatmapset.BeatmapsetId;
     Server           = server;
     FailedServerList = new List <Server>();
 }
示例#11
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;
            }
        }
示例#12
0
        /// <summary>
        /// Начинает распознавание картинки
        /// </summary>
        /// <param name="attachment">Картинка</param>
        private Tuple <Beatmapset, Beatmap> DownloadAndRecognizeImage(DiscordAttachment attachment)
        {
            string webFileName = $"{DateTime.Now.Ticks}-{attachment.FileName}";

            webClient.DownloadFile(attachment.Url, $"downloads/{webFileName}");

            string fileName = $"downloads/{webFileName}";
            Image  image    = Image.FromFile(fileName);

            string[] rawrecedText = recognizer.RecognizeTopText(image).Split('\n');

            sheduler.AddFileDeleteTask(fileName);

            foreach (string s in rawrecedText)
            {
                logger.LogDebug(s);
            }

            // Searching for first non-empty or almost string
            string recedText = string.Empty;

            foreach (string s in rawrecedText)
            {
                if (!string.IsNullOrWhiteSpace(s) && s.Length > 10)
                {
                    recedText = s;
                    break;
                }
            }

            logger.LogDebug($"Recognized text: {recedText}");

            // Cut artist
            int indexStart = recedText.IndexOf('-');

            if (indexStart == -1)
            {
                indexStart = recedText.IndexOf('–');
            }

            if (indexStart != -1)
            {
                logger.LogDebug("Cutting artist");
                recedText = recedText.Substring(indexStart).TrimStart(new char[] { ' ', '-', '–' });
            }

            logger.LogDebug($"Searching for: {recedText}");
            List <Beatmapset> bmsl = api.Search(recedText, WAV_Osu_NetApi.Bancho.QuerryParams.MapType.Any);


            // Get map diff
            indexStart = recedText.IndexOf('[');
            if (indexStart == -1)
            {
                logger.LogInformation($"Coulnd't get map difficulty");
                return(null);
            }

            string diffName = recedText.Substring(indexStart).TrimStart('[').TrimEnd(']');

            logger.LogDebug($"diffName: {diffName}");

            if (bmsl == null || bmsl.Count == 0)
            {
                logger.LogInformation($"Api search return null or empty List");
                return(null);
            }

            string mapper = string.Empty;

            mapper = rawrecedText.Select(x => x)
                     .FirstOrDefault(x =>
            {
                x = x.ToLowerInvariant();
                return(x.Contains("mapped") || x.Contains("beatmap"));
            });


            Beatmapset bms = null;

            if (!string.IsNullOrEmpty(mapper))
            {
                mapper = mapper?.Substring(10);
                logger.LogDebug($"Got mapper: {mapper}. Comparing...");
                List <Tuple <Beatmapset, double> > bsm = bmsl.Select(x => Tuple.Create(x, WAV_Osu_Recognizer.RecStringComparer.Compare(x.creator, mapper)))
                                                         .OrderByDescending(x => x.Item2)
                                                         .ToList();


                foreach (var b in bsm)
                {
                    logger.LogDebug($"{b.Item1.creator}: {b.Item2}");
                }

                if (bsm == null || bsm.Count == 0)
                {
                    bms = bmsl.FirstOrDefault();
                }
                else
                {
                    bms = bsm.First().Item1;
                }
            }
            else
            {
                logger.LogInformation($"Couldn't get mapper");
                bms = bmsl.FirstOrDefault();
            }


            if (bms == null)
            {
                logger.LogInformation($"No matching beatmapsets");
                return(null);
            }
            else
            {
                logger.LogDebug($"Beatmapsets count: {bmsl.Count}");
            }


            List <Tuple <Beatmap, double> > bmds = bms.beatmaps.Select(x => Tuple.Create(x, WAV_Osu_Recognizer.RecStringComparer.Compare(x.version, diffName)))
                                                   .OrderByDescending(x => x.Item2)
                                                   .ToList();

            logger.LogDebug("Comparing beatmap versions:");
            foreach (var k in bmds)
            {
                logger.LogDebug($"{k.Item1.version} {k.Item2}");
            }



            var result = Tuple.Create(bms, bmds.First().Item1);

            logger.LogInformation($"Success. bms_id: {result.Item1.id}, bm_id: {result.Item2.id}");
            return(result);
        }
示例#13
0
 public void Add(Beatmapset beatmapset, Server?server = null)
 {
     Add(new BeatmapsetPackage(beatmapset, server));
 }