public void DepthTest() { HttpApiClient httpApiClient = new HttpApiClient(BinanceDexEnvironment.TEST_NET); MarketDepth marketDepth = httpApiClient.Depth("PND-943_BNB"); Assert.NotNull(marketDepth); }
static async void RunIUserApi() { var watch = new Stopwatch(); watch.Start(); using (var client = HttpApiClient.Create <IMyWebApi>()) { //登陆 await client.LognWithFormAsync(new UserInfo { j_username = "", j_password = "" }); //队列空则停止 while (!ltid.IsEmpty) { try { await RunApisAsync(client); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } watch.Stop(); Console.WriteLine($"总共耗时:{watch.Elapsed}"); }
public async Task ProcessAsync(MessageContext context, HttpApiClient api) { string url = "https://rsshub.app/pixiv/ranking/day"; var xmlReader = XmlReader.Create(url); var feed = SyndicationFeed.Load(xmlReader); var tuple = feed.Items.Select(i => { var doc = new HtmlDocument(); doc.LoadHtml(i.Summary.Text); return(item: i, nodes: doc.DocumentNode.SelectNodes("//p/img")); }).Randomize().FirstOrDefault(t => t.nodes.Count == 1); var(item, imgNode) = (tuple.item, tuple.nodes?.First()); if (imgNode != null) { var imgUrl = imgNode.Attributes["src"].Value; if (await api.SendMessageAsync( endpoint: context.Endpoint, message: new Message(item.Title.Text + "\r\n") + Message.NetImage(imgUrl) + new Message("\r\n" + item.Links.FirstOrDefault().Uri) ) == null) { await api.SendMessageAsync(context.Endpoint, "图片发送失败。"); } } else { await api.SendMessageAsync(context.Endpoint, "没有符合要求的图片。"); } }
public async Task OnMessageAsync(MessageContext message, HttpApiClient api) { if (!s_baicaiCommands.Any(c => message.Content.Text.Contains(c))) { return; } var uid = await _dataProvider.GetOsuIdAsync(message.UserId).ConfigureAwait(false); Mode?mode = null; // TODO: Use binding from mothership database first. if (uid != null) { if (mode != null) { await _dataMaintainer.UpdateAsync(uid.Value, mode.Value).ConfigureAwait(false); } else { foreach (Mode m in Enum.GetValues(typeof(Mode))) { await _dataMaintainer.UpdateAsync(uid.Value, m).ConfigureAwait(false); } } } }
/// <summary> /// 查询客户-物资 /// </summary> /// <param name="input">条件参数</param> /// <returns></returns> public async Task <PaginatedList <Desc_Customer_Material_AppOutputDto> > GetAllListAsync(Desc_Customer_Material_AppGetAllInputDto input) { try { //查询客户拥有的物资 string dto = JsonUtils.SerializeObject(input); var result = await _dataRepository.GetDescCustomerMaterialOutputListAsync(dto); var dataOutputList = Mapper.Map <List <Desc_Customer_Material_AppOutputDto> >(result.DataSource); if (dataOutputList != null && dataOutputList.Count > 0) { //调用ims服务 //物资信息服务 var client = new HttpApiClient(_options.Value?.IMSUri); var materialService = client.Create <IMaterialInterface>(); var response = await materialService.GetAllPptMaterial(input.TenantId, input.Warehouseid); var materialList = JsonUtils.DeserializeNezadaJsonDto <List <MaterialInfo> >(response); foreach (var item in dataOutputList) { item.Materialname = materialList.Find(d => d.Id == item.Materialid)?.Name; item.Skuid = materialList.Find(d => d.Id == item.Materialid)?.Skuid; } } return(new PaginatedList <Desc_Customer_Material_AppOutputDto>(input.PageNo, input.PageSize, result.TotalCount, dataOutputList)); } catch (Exception ex) { throw ex; } }
public static async Task <HttpData <T[]> > GetDataAsync <T>(this HttpApiClient client, string library, string method, object[] values) { T[] result = null; HttpData <string> data = await client.GetRawDataAsync(library, method, values); if (CheckDataContent(data)) { DataDto <T> dto = null; try { dto = JsonConvert.DeserializeObject <DataDto <T> >(data.Content); } catch (Exception ex) { client.OnErrorOccured(new HttpErrorEventArgs( ex, data.RequestUri.ToString(), HttpVerb.Get, "Invalid response format. JSON expected.")); data.SetSuccessFlag(false); } if (dto != null && dto.Data != null) { result = dto.Data; } } return(new HttpData <T[]>(data, result)); }
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://toyokeizai.net/sp/visual/tko/covid19/en.html").ConfigureAwait(false); await page.WaitForSelectorAsync("#main-block > div:nth-child(2) > div:nth-child(1) > div > div.charts-wrapper > div.main-chart-wrapper > div > canvas").ConfigureAwait(false); var element = await page.QuerySelectorAsync("#main-block > div:nth-child(2)").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); }
public CloundMusicApiManager() { HttpApiConfig httpApiConfig = new HttpApiConfig(); httpApiConfig.HttpHost = new Uri("http://music.rexhuang.top/"); MusicApi = HttpApiClient.Create <IMusicApi>(httpApiConfig); }
private void InitClient() { var config = new HttpApiConfig(); config.GlobalFilters.Add(filter); client = HttpApiClient.Create <IRongCloudApi>(config); }
public void PeersTest() { HttpApiClient client = new HttpApiClient(BinanceDexEnvironment.TEST_NET); var peers = client.Peers(); Assert.NotNull(peers[0].Id); }
public void TxTest() { HttpApiClient httpApiClient = new HttpApiClient(BinanceDexEnvironment.TEST_NET); Transaction transaction = httpApiClient.Tx("D726ACEEE1AC98815A206EBEB2EE0280BFAE6EEB53A0E3F564175443E31B8A5D"); Assert.True(transaction.Ok); }
public void ValidatorsTest() { HttpApiClient client = new HttpApiClient(BinanceDexEnvironment.TEST_NET); var validator = client.Validators(); Assert.NotNull(validator.Validators[0].Address); }
public void NodeInfoTest() { HttpApiClient client = new HttpApiClient(BinanceDexEnvironment.TEST_NET); var infos = client.NodeInfo(); Assert.NotNull(infos.NodeInfo); }
public void KLinesTest() { HttpApiClient httpApiClient = new HttpApiClient(BinanceDexEnvironment.TEST_NET); List <List <object> > klines = httpApiClient.KLines("PND-943_BNB", "5m"); Assert.NotEmpty(klines); }
public static async Task <JToken[]> GetDataListAsync(this HttpApiClient client, string library, string method, object[] values) { JToken[] result = null; HttpData <string> data = await client.GetRawDataAsync(library, method, values); if (CheckDataContent(data)) { // Parse the JSON string JObject jObject = null; try { jObject = JObject.Parse(data.Content); } catch (Exception ex) { client.OnErrorOccured(new HttpErrorEventArgs( ex, data.RequestUri.ToString(), HttpVerb.Get, "Invalid response format. JSON expected.")); } // Get "data" object as enumerable try { result = GetDataArray(jObject); } catch (Exception ex) { client.OnErrorOccured(new HttpErrorEventArgs( ex, data.RequestUri.ToString(), HttpVerb.Get, "Invalid 'data' object.")); } } return(result); }
public void InitChainId(HttpApiClient client) { Infos info = client.NodeInfo(); ChainId = info.NodeInfo.Network; chainIds.Add(Env, ChainId); }
public static async Task <HttpData <string> > GetRawDataAsync(this HttpApiClient client, string library, string method, object[] values) { Uri uri = MakeSpecialRequestUri(client, library, method, values); return(await client.GetAsync(uri)); }
/// <summary> /// 查询客户 /// </summary> /// <param name="input">条件参数</param> /// <returns></returns> public async Task <PaginatedList <Ppt_Customer_AppOutputDto> > GetAllListAsync(Ppt_Customer_AppGetAllInputDto input) { try { string dto = JsonUtils.SerializeObject(input); var result = await _dataRepository.GetPptCustomerOutputListAsync(dto); var dataOutputList = Mapper.Map <List <Ppt_Customer_AppOutputDto> >(result.DataSource); var client = new HttpApiClient(_options.Value.WConfigurationUri); var userService = client.Create <IUserInterface>(); var response = await userService.GetAllUserList(input.TenantId); var userList = JsonUtils.DeserializeNezadaJsonDto <List <SelectedItem> >(response); foreach (var dataOutput in dataOutputList) { dataOutput.CreatorUserId = userList.Find(d => d.Id == dataOutput.CreatorUserId)?.Text; } return(new PaginatedList <Ppt_Customer_AppOutputDto>(input.PageNo, input.PageSize, result.TotalCount, dataOutputList)); } catch (Exception ex) { throw ex; } }
public override async Task <ExternalAuthUserInfo> GetUserInfo(string accessCode) { var client = HttpApiClient.Create <IWeChatH5Api>(); //拿code换accessToken var token = await client.AuthCodeAsync(ProviderInfo.ClientId, ProviderInfo.ClientSecret, accessCode); //获取用户信息 var user = await client.GetUserInfoAsync(token.access_token, token.openid); return(new WechatH5AuthUserInfo { EmailAddress = $"{user.openid}@SmartCanteen.com", Name = $"{user.openid}", Provider = ProviderInfo.Name, ProviderKey = user.openid, Surname = user.openid, AccessToken = token.access_token, RefreshToken = token.refresh_token, City = user.city, Province = user.province, Country = user.country, Gender = user.sex == 1 ? Gender.Male : Gender.Female, HeadLogo = user.headimgurl, NickName = user.nickname, OpenId = token.openid, UnionId = user.unionid }); }
public async Task ProcessAsync(Sisters.WudiLib.Posts.Message message, HttpApiClient api) { // TODO 验证用户名是否合法 var(success, userInfo) = await OsuApi.GetUserInfoAsync(_userName, OsuMixedApi.Mode.Standard); if (!success) { await api.SendMessageAsync(message.Endpoint, "网络错误。"); return; } if (userInfo == null) { await api.SendMessageAsync(message.Endpoint, "没有此用户。"); return; } var dbResult = await Database.AddNewBindAsync(message.UserId, userInfo.Id, userInfo.Name, "自己绑定", message.UserId, userInfo.Name); if (dbResult.Success) { await api.SendMessageAsync(message.Endpoint, $"成功绑定为{userInfo.Name}。"); } else if (dbResult.Exception is DbUpdateException && dbResult.Exception.InnerException?.Message.Contains("Duplicate", StringComparison.Ordinal) == true) { await api.SendMessageAsync(message.Endpoint, "在已绑定的情况下不允许修改,如需修改请联系 bleatingsheep。"); } else { await api.SendMessageAsync(message.Endpoint, "数据库访问错误。"); FLogger.LogException(dbResult.Exception); } }
private async Task Init(MessageContext context, HttpApiClient api) { var sb = new StringBuilder(); if (s_cache.TryGetValue(context.UserId, out ExecuteInfo exec)) { sb.AppendLine("当前游戏正在进行。"); } else { exec = s_cache.Set(context.UserId, new ExecuteInfo(), new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); } sb.Append("你有").Append(Max).Append("枚重量各不相同的金币,编号为1-").Append(Max).Append(@",和一个天平。你可以用天平比较两枚金币的重量。 你的目标是:称最少的次数(").Append(Max).Append(" 枚金币 ").Append(Best).Append(@" 次),将这些金币按从轻到重排序 你可以使用指令“称xy”来比较两枚金币的重量,其中x、y都是金币编号。 例如:称12 你无须提交排序结果,消防栓会自动检测你能否排出来。 ------ "); string info = GetInfo(exec.GetKnown(out _)); sb.Append(info); string message = sb.ToString(); await api.SendMessageAsync(context.Endpoint, message).ConfigureAwait(false); }
public override async Task <ExternalAuthUserInfo> GetUserInfo(string accessCode) { var client = HttpApiClient.Create <IWeChatApi>(); var authResult = await client.AuthCodeAsync(ProviderInfo.ClientId, ProviderInfo.ClientSecret, accessCode); if (authResult.errcode == 0) { return(new WechatAuthUserInfo { EmailAddress = $"{authResult.openid}@AbpProjectName.com", Name = $"{authResult.openid}", Provider = ProviderInfo.Name, ProviderKey = authResult.openid, Surname = authResult.openid, SessionKey = authResult.session_key, OpenId = authResult.openid }); } else { Logger.Error($"{GetType().FullName}:{authResult.errcode},{authResult.errmsg}"); throw new AbpProjectNameBusinessException(ErrorCode.WechatAuthByCodeFailed); } }
static async Task <string> TestAsync() { var client = HttpApiClient.Create <IMyWebApi>(); var news = await client.GetNews(7); return(news); }
public void FeesTest() { HttpApiClient httpApiClient = new HttpApiClient(BinanceDexEnvironment.TEST_NET); List <FeeData> fees = httpApiClient.Fees(); Assert.NotEmpty(fees); }
private static void ListeningTest(HttpApiClient httpApi) { Console.WriteLine("input listening port"); string port = Console.ReadLine(); ApiPostListener listener = new ApiPostListener(); listener.ApiClient = httpApi; listener.PostAddress = $"http://127.0.0.1:{port}/"; listener.ForwardTo = "http://[::1]:10202"; listener.StartListen(); listener.FriendRequestEvent += Friend; listener.FriendRequestEvent += ApiPostListener.ApproveAllFriendRequests; listener.GroupInviteEvent += Group; listener.GroupInviteEvent += ApiPostListener.ApproveAllGroupRequests; listener.GroupRequestEvent += Group; listener.GroupRequestEvent += ApiPostListener.ApproveAllGroupRequests; //listener.MessageEvent += ApiPostListener.RepeatAsync; listener.MessageEvent += PrintRaw; listener.GroupNoticeEvent += ApiPostListener.RepeatAsync; listener.AnonymousMessageEvent += ApiPostListener.RepeatAsync; listener.AnonymousMessageEvent += PrintRaw; //listener.MessageEvent += ApiPostListener.Say("good"); var listener2 = new ApiPostListener(); listener2.PostAddress = "http://[::1]:10202"; listener2.StartListen(); listener2.MessageEvent += (api, message) => { Console.WriteLine(message.Time); Console.WriteLine(message.Content.Raw); }; }
public async Task ProcessAsync(MessageContext context, HttpApiClient api) { using var page = await Chrome.OpenNewPageAsync().ConfigureAwait(false); await page.SetViewportAsync(new ViewPortOptions { DeviceScaleFactor = 3.5, Width = 800, Height = 1000, }).ConfigureAwait(false); await page.GoToAsync("https://www.investing.com/indices/us-spx-500-futures").ConfigureAwait(false); const string selector = "#quotes_summary_current_data"; var element = await page.QuerySelectorAsync(selector).ConfigureAwait(false); var data = await element.ScreenshotDataAsync(new ScreenshotOptions { Type = ScreenshotType.Png, }).ConfigureAwait(false); bool inLoop = true; int retry = 3; do { var mesResponse = await api.SendMessageAsync(context.Endpoint, Message.ByteArrayImage(data)).ConfigureAwait(false); inLoop = mesResponse == null; } while (inLoop && --retry > 0); }
public async Task OnMessageAsync(MessageContext message, HttpApiClient api) { if (s_stopwatch == null) { s_stopwatch = Stopwatch.StartNew(); } if (s_nextCheck < s_stopwatch.ElapsedMilliseconds) { const int IntervalMilliseconds = 10 * 60_000; s_nextCheck = s_stopwatch.ElapsedMilliseconds + IntervalMilliseconds; var cmbc = await HttpApi.Resolve <ICmbcCreditRate>().GetRates().ConfigureAwait(false); var cmbcJson = JsonSerializer.Serialize(cmbc); if (cmbcJson != s_cmbcJson) { s_cmbcJson = cmbcJson; _logger.LogInformation($"CMBC Changed: {cmbcJson}"); } var cib = await HttpApi.Resolve <ICibRate>().GetRates().ConfigureAwait(false); var cibJson = JsonSerializer.Serialize(cib); if (cibJson != s_cibJson) { s_cibJson = cibJson; _logger.LogInformation($"CIB Changed: {cibJson}"); } } }
public async Task Refresh() { var client = HttpApiClient.Create <IWeChatMiniApi>(); var appId = _appConfiguration["Authentication:WechatMini:AppId"]; var appSecret = _appConfiguration["Authentication:WechatMini:AppSecret"]; if (_appConfiguration["Authentication:WechatH5:IsEnabled"].ToLower() == bool.TrueString.ToLower()) { appId = _appConfiguration["Authentication:WechatH5:AppId"]; appSecret = _appConfiguration["Authentication:WechatH5:AppSecret"]; } var accessToken = await client.GetAccessTokenAsync(appId, appSecret); //获取access token,写入缓存,缓存有效期以expire_in为准 if (accessToken != null) { var tokenCache = _cacheManager.GetCache <string, string>(WechatMiniConsts.WechatCacheName); tokenCache.Set(WechatMiniConsts.AccessTokenCacheKey , accessToken.access_token , TimeSpan.FromSeconds(accessToken.expires_in) , TimeSpan.FromSeconds(accessToken.expires_in)); } else { throw new AbpProjectNameBusinessException(ErrorCode.WechatAccessTokenIsEmpty); } }
public async Task ProcessAsync(MessageContext context, HttpApiClient api) { var bi = await _newbieContext.Bindings.Where(b => b.UserId == context.UserId).FirstOrDefaultAsync().ConfigureAwait(false); if (bi == null) { return; } var osuId = bi.OsuId; var best = await _osuApiClient.GetUserBest(osuId).ConfigureAwait(false); var sb = new StringBuilder(); foreach (var b in best.Take(4)) { sb.Append("根据您的 BP b/").Append(b.BeatmapId).Append(" + ").Append(b.EnabledMods.Display()).AppendLine(" 推荐:"); var id = RecommendationBeatmapId.Create(b, Mode.Standard); var rec = await _newbieContext.Recommendations .Where(r => r.Left == id) .OrderByDescending(r => r.RecommendationDegree) .Take(4) .ToListAsync().ConfigureAwait(false); _ = rec.Aggregate(sb, (sb, r) => sb.Append("b/").Append(r.Recommendation.BeatmapId).Append(" + ").AppendLine(r.Recommendation.ValidMods.Display())); } await api.SendMessageAsync(context.Endpoint, sb.ToString()).ConfigureAwait(false); }
private async void MainPage_Loaded(object sender, RoutedEventArgs e) { var client = HttpApiClient.Create <IBaiduApi>(); var html = await client.HomeAsync(); this.Html.Text += html; }
public TelegramBotApi([NotNull] string token, string apiBase = "https://api.telegram.org/") { if (string.IsNullOrEmpty(token)) throw new ArgumentNullException(nameof(token)); if (string.IsNullOrEmpty(apiBase)) throw new ArgumentNullException(nameof(apiBase)); _api = new HttpApiClient(new Uri(apiBase), token); }