async Task ProcessMessage(VkMessage msg) { aiConfig.SessionId = "vk_" + msg.UserId.ToString(); var apiAi = new ApiAi(aiConfig); var response = apiAi.TextRequest(msg.Text); string respmsg; if (response.IsError) { respmsg = "Ошибочка..."; } else { respmsg = response.Result.Fulfillment.Speech; } if (string.IsNullOrEmpty(respmsg)) { respmsg = "Хм..."; } await SendMessage(msg.UserId, respmsg); }
async Task RunAsync(CancellationToken ct) { await GetPoolingServerAsync(); while (!ct.IsCancellationRequested) { string updatesRaw; try { using (ct.Register(() => { client.CancelPendingRequests(); })) { updatesRaw = await client.GetStringAsync( $"https://{serverUrl}?act=a_check&ts={ts}&key={key}&version={pollingVersion}&wait={client.Timeout.TotalSeconds}"); } } catch (TaskCanceledException) { continue; } var updates = JObject.Parse(updatesRaw); if (updates["failed"] != null) { var code = (int)updates["failed"]; switch (code) { case 1: ts = (uint)updates["new_ts"]; break; case 2: case 3: await GetPoolingServerAsync(); break; default: throw new Exception(string.Format("Unknown error code has been detected in a long poll response: {0}", code)); } } else { ts = (uint)updates["ts"]; foreach (var update in (JArray)updates["updates"]) { switch ((LongPollMessageCodes)(int)update[0]) { case LongPollMessageCodes.AddMessage: { var updateArr = (JArray)update; var msg = new VkMessage { Id = (int)updateArr[1], Text = (string)updateArr[5], UserId = (int)updateArr[3], //Attachments = (updateArr.Count > 6) ? (JObject)update[6] : null, Flags = (MessageFlags)(int)update[2], }; if (!msg.Flags.HasFlag(MessageFlags.Outbox)) { await ProcessMessage(msg); } break; } } } } } }