A
A
Alexey Fedorov2019-10-28 22:35:02
ASP.NET
Alexey Fedorov, 2019-10-28 22:35:02

VK chatbot is not responding. What could be the problem?

Wrote a simple chat bot in ASP.NET Core. As planned, the bot should respond with the same message, but there is no response.
5db7423aa09d8759253250.png
I can’t understand what the problem is, because the Callback method successfully sent an acknowledgment, but at the same time, there is no response to the messages.
5db742623cf90570531976.png
Added processing of a GET request, in which one of the messages I sent is deserialized - everything works. When I go to the address of the controller, I receive a message from the group. What could be the problem?

Controller code
[Route("api/[controller]")]
[ApiController]
public class CallbackController : ControllerBase
{
    /// <summary>
    /// Конфигурация приложения
    /// </summary>
    private readonly IConfiguration _configuration;

    private readonly IVkApi _vkApi;

    public CallbackController (IConfiguration configuration, IVkApi vkApi)
    {
        _configuration = configuration;
        _vkApi = vkApi;
    }

    [HttpPost]
    public IActionResult Callback ([FromBody] VkEvent vkEvent)
    {
        // Проверяем, что находится в поле "type" 
        switch (vkEvent.Type)
        {
            // Если это уведомление для подтверждения адреса
            case "confirmation":
                // Отправляем строку для подтверждения 
                return Ok(_configuration["Config:Confirmation"]);
            case "message_new":
                {
                    // Десериализация
                    var msg = Message.FromJson(new VkResponse(vkEvent.Object));

                    // Отправим в ответ полученный от пользователя текст
                    _vkApi.Messages.Send(new MessagesSendParams
                    {
                        RandomId = new DateTime().Millisecond,
                        PeerId = msg.PeerId.Value,
                        Message = string.Format("Vk ChatBot Test App\nYour message: {0}", msg.Text)
                    });
                    // Возвращаем "ok" серверу Callback API
                    return Ok("ok");
                }
        }

        // Возвращаем "ok" серверу Callback API
        return Ok("ok");
    }

    [HttpGet]
    public IActionResult GetActionResult()
    {
        var jsonmsg = @"{""type"":""message_new"",""object"":{""date"":1572209977,""from_id"":19435491,""id"":40,""out"":0,""peer_id"":19435491,""text"":""Hello"",""conversation_message_id"":9,""fwd_messages"":[],""important"":false,""random_id"":0,""attachments"":[],""is_hidden"":false},""group_id"":172942884}";
            

        var vkEvent = JsonConvert.DeserializeObject<VkEvent>(jsonmsg);

        var msg = Message.FromJson(new VkResponse(vkEvent.Object));
        // Отправим в ответ полученный от пользователя текст
        _vkApi.Messages.Send(new MessagesSendParams
        {
            RandomId = new DateTime().Millisecond,
            PeerId = msg.PeerId.Value,
            Message = msg.Text
        });

        return Ok(msg.Text);

    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Fedorov, 2020-02-08
@FedorovAlexey

I remembered my bot after 3.5 months.
The VkEvent class uses Newtonsoft.Json for serialization.

VkEvent class

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace ChatBotTesting.Models
{
    [Serializable]
    public class VkEvent
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("object")]
        public JObject Object { get; set; }
        
        [JsonProperty("group_id")]
        public long GroupId { get; set; }
    }
}


When an event came from VK, the application threw an exception System.NotSupportedException: The collection type 'Newtonsoft.Json.Linq.JToken' is not supported. In order for the application to support Newtonsoft.Json, you need to do 2 things:
  1. Install package Microsoft.AspNetCore.Mvc.NewtonsoftJson from NuGet
  2. In the Startup.ConfigureServices method write : services.AddControllers().AddNewtonsoftJson();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question