Ejemplo n.º 1
0
 public bool ShouldResponse(MessageContext message)
 {
     if (message is GroupMessage g && g.GroupId == 712603531)
     {
         return(false); // ignored in newbie group.
     }
     if (message.Content.TryGetPlainText(out string text))
     {
         var match = Regex.Match(text);
         if (match.Success)
         {
             _other = match.Groups[1].Value;
             _mode  = match.Groups[2].Value;
             return(true);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
    public async Task ProcessAsync(MessageContext context, HttpApiClient api)
    {
        using var page = await Chrome.OpenNewPageAsync().ConfigureAwait(false);

        await page.SetViewportAsync(new ViewPortOptions
        {
            DeviceScaleFactor = 3,
            Width             = 360,
            Height            = 8000,
        }).ConfigureAwait(false);

        await page.GoToAsync("https://en.wikipedia.org/wiki/Template:COVID-19_pandemic_data/Canada_medical_cases_by_province").ConfigureAwait(false);

        var element = await page.QuerySelectorAsync("#mw-content-text > div.mw-parser-output > table").ConfigureAwait(false);

        await page.SetViewportAsync(new ViewPortOptions
        {
            DeviceScaleFactor = 2,
            Width             = 1024,
            Height            = 4000,
        }).ConfigureAwait(false);

        var data2 = await element.ScreenshotDataAsync(new ScreenshotOptions
        {
            Type    = ScreenshotType.Jpeg,
            Quality = 100,
        }).ConfigureAwait(false);

        await api.SendMessageAsync(context.Endpoint, Message.ByteArrayImage(data2)).ConfigureAwait(false);
    }
Ejemplo n.º 3
0
        public async Task ProcessAsync(MessageContext context, HttpApiClient api)
        {
            string @base;
            string amountString;

            if (s_regex.Match(_text) is { Success : true } match)
            {
                @base        = match.Groups[1].Value;
                amountString = match.Groups[2].Value;
            }
Ejemplo n.º 4
0
    public async Task ProcessAsync(MessageContext context, HttpApiClient api)
    {
        var load         = File.ReadAllText("/proc/loadavg");
        var loadArray    = load.Split();
        var messageArray = new string[3];

        messageArray[0] = $"{loadArray[0]} {loadArray[1]} {loadArray[2]}";
        messageArray[1] = context.MessageId.ToString(CultureInfo.InvariantCulture);
        messageArray[2] = context.Time.ToOffset(TimeSpan.FromHours(9)).ToString("H:mm:ss");
        await api.SendMessageAsync(context.Endpoint, string.Join("\r\n", messageArray)).ConfigureAwait(false);
    }
Ejemplo n.º 5
0
    public async Task ProcessAsync(MessageContext context, HttpApiClient api)
    {
        using var page = await Chrome.OpenNewPageAsync().ConfigureAwait(false);

        await page.SetViewportAsync(new ViewPortOptions
        {
            DeviceScaleFactor = 3,
            Width             = 360,
            Height            = 8000,
        }).ConfigureAwait(false);

        await page.GoToAsync("https://www.nytimes.com/interactive/2021/us/covid-cases.html").ConfigureAwait(false);

        await page.WaitForSelectorAsync("#us-covid-cases > div > div > main > div.g-columns-outer.svelte-hfvvmm > div:nth-child(2) > section:nth-child(1)").ConfigureAwait(false);

        var deleteElement = await page.QuerySelectorAsync("#standalone-footer > div > div").ConfigureAwait(false);

        await deleteElement.EvaluateFunctionAsync("b => b.remove()").ConfigureAwait(false);

        var element = await page.QuerySelectorAsync("#us-covid-cases > div > div > main > div.g-columns-outer.svelte-hfvvmm > div:nth-child(2) > section:nth-child(1)").ConfigureAwait(false);

        await page.SetViewportAsync(new ViewPortOptions
        {
            DeviceScaleFactor = 2,
            Width             = 1024,
            Height            = 4000,
        }).ConfigureAwait(false);

        var data2 = await element.ScreenshotDataAsync(new ScreenshotOptions
        {
            Type    = ScreenshotType.Jpeg,
            Quality = 100,
        }).ConfigureAwait(false);

        await api.SendMessageAsync(context.Endpoint, Message.ByteArrayImage(data2)).ConfigureAwait(false);
    }
 private static async Task <bool> AllowMulti(MessageContext context)
 => !(context.Endpoint is GroupEndpoint g) ||
Ejemplo n.º 7
0
        public async Task ProcessAsync(MessageContext superContext, HttpApiClient api)
        {
            var context      = superContext as GroupMessage;
            var groupMembers = await api.GetGroupMemberListAsync(context.GroupId);

            Logger.Debug($"群 {context.GroupId} 开启今日高光,成员共 {groupMembers.Length} 名。");

            var stopwatch = Stopwatch.StartNew();

            using (var dbContext = new NewbieContext())
            {
                //var bindings = await (from b in dbContext.Bindings
                //                      join mi in groupMembers on b.UserId equals mi.UserId
                //                      select new { Info = mi, Binding = b.OsuId }).ToListAsync();
                ////var history = (from bi in bindings.AsQueryable()
                ////               join ui in motherShip.Userinfo on bi.Binding equals ui.UserId into histories
                ////               select new { bi.Info, bi.Binding, History = histories.OrderByDescending(ui => ui.QueryDate).First() }).ToList();
                //var osuIds = bindings.Select(b => b.Binding).Distinct().ToList();
                var qqs    = groupMembers.Select(mi => mi.UserId).ToList();
                var osuIds = await dbContext.Bindings.Where(bi => qqs.Contains(bi.UserId)).Select(bi => bi.OsuId).Distinct().ToListAsync();

                Logger.Debug($"找到 {osuIds.Count} 个绑定信息,耗时 {stopwatch.ElapsedMilliseconds}ms。");

                Bleatingsheep.Osu.Mode mode = 0;
                if (!string.IsNullOrEmpty(ModeString))
                {
                    try
                    {
                        mode = Bleatingsheep.Osu.ModeExtensions.Parse(ModeString);
                    }
                    catch (FormatException)
                    {
                        // ignore
                    }
                }

                stopwatch = Stopwatch.StartNew();
                List <UserSnapshot> history = await GetHistories(osuIds, mode).ConfigureAwait(false);

                Logger.Debug($"找到 {history.Count} 个历史信息,耗时 {stopwatch.ElapsedMilliseconds}ms。");

                // Using ConcurrentBag is enough here. ConcurrentDictionary is unnecessary and costly.
                var nowInfos = new ConcurrentDictionary <int, UserInfo>(10, history.Count);
                var fails    = new BlockingCollection <int>();
                stopwatch = Stopwatch.StartNew();
                var fetchIds          = history.Select(h => (int)h.UserId).Distinct().ToList();
                int completes         = 0;
                var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token;
                var tasks             = fetchIds.Concat(fails.GetConsumingEnumerable()).Select(async bi =>
                {
                    var(success, userInfo) = await GetCachedUserInfo(bi, (Bleatingsheep.Osu.Mode)mode).ConfigureAwait(false);
                    if (!success)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            fails.CompleteAdding();
                        }
                        if (!fails.IsAddingCompleted)
                        {
                            try
                            {
                                fails.Add(bi);
                            }
                            catch (InvalidOperationException)
                            {
                            }
                        }
                    }
                    else
                    {
                        Interlocked.Increment(ref completes);
                        if (completes == fetchIds.Count)
                        {
                            fails.CompleteAdding();
                        }
                        if (userInfo != null)
                        {
                            nowInfos[bi] = userInfo;
                        }
                    }
                }).ToArray();
                await Task.WhenAll(tasks).ConfigureAwait(false);

                Logger.Debug($"查询 API 花费 {stopwatch.ElapsedMilliseconds}ms,失败 {fails.Count} 个。");

                var cps = (from his in history
                           join now in nowInfos on his.UserId equals now.Key
                           where his.UserInfo.PlayCount != now.Value.PlayCount
                           orderby now.Value.Performance - his.UserInfo.Performance descending
                           select new { Old = his.UserInfo, New = now.Value, Meta = his }).ToList();

                if (fails.Count > 0)
                {
                    await api.SendGroupMessageAsync(context.GroupId, $"失败了 {fails.Count} 人。");
                }
                if (cps.Count == 0)
                {
                    await api.SendMessageAsync(context.Endpoint, "你群根本没有人屙屎。");

                    return;
                }
                else
                {
                    var increase = cps.Find(cp => cp.Old.Performance != 0 && cp.New.Performance != cp.Old.Performance);
                    var mostPlay = cps.OrderByDescending(cp => cp.New.TotalHits - cp.Old.TotalHits).First();
                    var sb       = new StringBuilder(100);
                    sb.AppendLine("最飞升:");
                    if (increase != null)
                    {
                        // sb.AppendLine($"{increase.New.Name} 增加了 {increase.New.Performance - increase.Old.Performance:#.##} PP。")
                        sb.Append(increase.New.Name).Append(" 增加了 ").AppendFormat("{0:#.##}", increase.New.Performance - increase.Old.Performance).AppendLine(" PP。")
                        // .AppendLine($"({increase.Old.Performance:#.##} -> {increase.New.Performance:#.##})");
                        .Append('(').AppendFormat("{0:#.##}", increase.Old.Performance).Append(" -> ").AppendFormat("{0:#.##}", increase.New.Performance).AppendLine(")");
                    }
                    else
                    {
                        sb.AppendLine("你群没有人飞升。");
                    }
                    sb.AppendLine("最肝:")
                    // .Append($"{mostPlay.New.Name} 打了 {mostPlay.New.TotalHits - mostPlay.Old.TotalHits} 下。");
                    .Append(mostPlay.New.Name).Append(" 打了 ").Append(mostPlay.New.TotalHits - mostPlay.Old.TotalHits).Append(" 下。");


                    await api.SendMessageAsync(context.Endpoint, sb.ToString());
                }
            }
        }
Ejemplo n.º 8
0
 public bool ShouldResponse(MessageContext context)
 => context is GroupMessage g &&
Ejemplo n.º 9
0
 private static void PrintRaw(HttpApiClient api, MessageContext message)
 {
     Console.WriteLine(message.Content.Raw);
 }
Ejemplo n.º 10
0
 public bool ShouldResponse(MessageContext context)
 => context.Content.TryGetPlainText(out var text) && "美国完了吗".Equals(text, StringComparison.Ordinal);
Ejemplo n.º 11
0
        public async Task ProcessAsync(Sisters.WudiLib.Posts.Message message, HttpApiClient api)
        {
            dynamic query;

            if (!string.IsNullOrWhiteSpace(queryUser))
            {
                bool success;
                (success, query) = await GetUserKey(queryUser);

                if (!success)
                {
                    await api.SendMessageAsync(message.Endpoint, "查询失败。");

                    return;
                }
                if (query is null)
                {
                    await api.SendMessageAsync(message.Endpoint, "查无此人。");

                    return;
                }
            }
            else
            {
                var(success, userId) = await DataProvider.GetBindingIdAsync(message.UserId);

                if (!success)
                {
                    await api.SendMessageAsync(message.Endpoint, "查询绑定账号失败。");

                    return;
                }
                if (userId == null)
                {
                    await api.SendMessageAsync(message.Endpoint, "未绑定。请发送“绑定”后跟你的用户名进行绑定。");

                    return;
                }
                query = userId.Value;
            }
            try
            {
                var userPlus = (UserPlus)await s_spider.GetUserPlusAsync(query);

                if (userPlus == null)
                {
                    await api.SendMessageAsync(message.Endpoint, string.IsNullOrWhiteSpace(queryUser)? "被办了。" : "查无此人。");

                    return;
                }

                var oldQuery = await Database.GetRecentPlusHistory(userPlus.Id);

                if (!oldQuery.Success)
                {
                    await api.SendMessageAsync(message.Endpoint, "无法找到历史数据。");

                    _logger.LogError(oldQuery.Exception, "{}", oldQuery.Exception.Message);
                }

                var old = oldQuery.EnsureSuccess().Result;

                var responseMessage = old == null
                    ? $@"{userPlus.Name} 的 PP+ 数据
Performance: {userPlus.Performance}
Aim (Jump): {userPlus.AimJump}
Aim (Flow): {userPlus.AimFlow}
Precision: {userPlus.Precision}
Speed: {userPlus.Speed}
Stamina: {userPlus.Stamina}
Accuracy: {userPlus.Accuracy}"
                    : $@"{userPlus.Name} 的 PP+ 数据
Performance: {userPlus.Performance}{userPlus.Performance - old.Performance: (+#); (-#); ;}
Aim (Jump): {userPlus.AimJump}{userPlus.AimJump - old.AimJump: (+#); (-#); ;}
Aim (Flow): {userPlus.AimFlow}{userPlus.AimFlow - old.AimFlow: (+#); (-#); ;}
Precision: {userPlus.Precision}{userPlus.Precision - old.Precision: (+#); (-#); ;}
Speed: {userPlus.Speed}{userPlus.Speed - old.Speed: (+#); (-#); ;}
Stamina: {userPlus.Stamina}{userPlus.Stamina - old.Stamina: (+#); (-#); ;}
Accuracy: {userPlus.Accuracy}{userPlus.Accuracy - old.Accuracy: (+#); (-#); ;}";
                if (message is GroupMessage g && g.GroupId == 758120648)
                {
                    //responseMessage += $"\r\n化学式没付钱指数:{C8Mod.CostOf(userPlus):0.0}";
                    responseMessage = C8Mod.ModPerformancePlus(responseMessage, old, userPlus);
                }
                await api.SendMessageAsync(message.Endpoint, responseMessage);

                if (old == null)
                {
                    var addResult = await Database.AddPlusHistoryAsync(userPlus);

                    if (!addResult.Success)
                    {
                        _logger.LogError(addResult.Exception, "{}", addResult.Exception.Message);
                    }
                }
            }
            catch (ExceptionPlus)
            {
                await api.SendMessageAsync(message.Endpoint, "查询PP+失败。");

                return;
Ejemplo n.º 12
0
 public bool ShouldResponse(MessageContext context)
 => context.UserId == 962549599 && context.Content.TryGetPlainText(out var text) && "loadavg".Equals(text, StringComparison.OrdinalIgnoreCase);
Ejemplo n.º 13
0
        public async Task ProcessAsync(MessageContext context, HttpApiClient api)
        {
            //await api.SendMessageAsync(context.Endpoint, $"[DEBUG] 比较:{_other};模式:{_mode}");

            var id = await DataProvider.EnsureGetBindingIdAsync(context.UserId).ConfigureAwait(false);

            //var browser = GetBrowser();

            byte[] data = null;
            var    mode = Bleatingsheep.Osu.Mode.Standard;

            try
            {
                if (!string.IsNullOrEmpty(_mode))
                {
                    mode = Bleatingsheep.Osu.ModeExtensions.Parse(_mode);
                }
            }
            catch
            {
                await api.SendMessageAsync(context.Endpoint, "模式识别失败,fallback 到 Standard。").ConfigureAwait(false);
            }

            var url = $"http://hydrantweb/pptth/mini/{id}?height=350&mode={(int)mode}";

            if (!string.IsNullOrEmpty(_other))
            {
                var(_, user) = await OsuApi.GetUserInfoAsync(_other, mode);

                if (user == null)
                {
                    ExecutingException.Ensure(false, "对比玩家错误");
                }
                url += $"&compared={user.Id}";
            }
            using (var page = await Chrome.OpenNewPageAsync().ConfigureAwait(false))
            {
                await page.SetViewportAsync(new ViewPortOptions
                {
                    DeviceScaleFactor = 1.15,
                    Width             = 640,
                    Height            = 350,
                }).ConfigureAwait(false);

                await page.GoToAsync(url).ConfigureAwait(false);

                await Task.Delay(0).ConfigureAwait(false);

                data = await page.ScreenshotDataAsync(new ScreenshotOptions
                {
                    FullPage = true,
                    //Type = ScreenshotType.Jpeg,
                    //Quality = 100,
                }).ConfigureAwait(false);
            }

            var stopwatch    = Stopwatch.StartNew();
            var sendResponse = await api.SendMessageAsync(context.Endpoint, Message.ByteArrayImage(data)).ConfigureAwait(false);

            var elapsedTime = stopwatch.ElapsedMilliseconds;
            var failed      = sendResponse is null;

            if (failed)
            {
                await api.SendMessageAsync(context.Endpoint, "图片发送失败(确定)").ConfigureAwait(false);
            }
            (failed ? FailedElapsed : SuccessfulElapsed).Add(elapsedTime);
        }