I am writing a simple VC bot in C #, which answers in the confession on my behalf to the phrase "Eugene, the weather". I do not understand a bit, how to catch the reception of the message? Do not tell me the logic?

There is a messages.GetHistory method that returns N messages. Can I take each timer tick 20 posts after the search and look for this message there and delete it after I found it? It sounds very sub-optimal, but I see no alternative

2 answers 2

The most effective way to catch new personal user messages is Long Poll .

But in general, if you have the opportunity to raise the script on the backend, then you should write bots using communities and their personal messages. For them, additional functionality is provided in the form of a Callback API - a kind of analogue of Webhuk in Telegram. That is, VC itself will send POST requests to inform you when and what your community has written to the LAN.

    Here is an example on the knee using VkApi

    internal class Program { private static VkApi _api; private static void Main() { const string email = "email"; const string pass = "password"; _api = new VkApi(); _api.Authorize(new ApiAuthParams { Login = email, Password = pass, Settings = Settings.Messages, ApplicationId = 0000 // vkAppId }); Thread pollMessagesThread = new Thread(PollUnread) { IsBackground = true, Name = nameof(pollMessagesThread) }; pollMessagesThread.Start(); pollMessagesThread.Join(); // для теста. } private static void PollUnread() { HashSet<string> messages = new HashSet<string>(); // желательно сделать expirableSet или время от времени чистить эту коллекцию while (true /*_shouldStop конечно же*/) { var msgs = _api?.Messages.GetHistory(new MessagesGetHistoryParams { UserId = 00000000 // Id пользователя c которым ведете диалог. }); foreach (var msgsMessage in msgs.Messages) { if (!messages.Contains(msgsMessage.Body)) { messages.Add(msgsMessage.Body); Console.WriteLine(msgsMessage.Body); } } Thread.Sleep(3000); } } } 

    UPD: another method PollUnread can be altered so that it would do something only if there are not read messages:

     private static void PollUnread() { while (true /*_shouldStop конечно же*/) { var msgs = _api?.Messages.GetHistory(new MessagesGetHistoryParams { UserId = 00000000 // Id пользователя c которым ведете диалог. }); if (msgs.Unread > 0) { Console.WriteLine(msgs.Messages); // Unreaded messages. } Thread.Sleep(3000); } }