Home>

What kind of (type) of the project to implement so that in it it would be possible to start a telegram bot on the hosting so that he listened to the bot, received messages and sent them to the API of the already existing ASP.NET Core 3.1 web service?

I wanted to do this using the ASP.NET Core Web-API project, but there works when there is a request to the controller, and how to make it work all the time I do not know. Tell me, if there is an example, you can please reference. This is what tried to do in ASP.NET Core Web-API:

[apicontroller]
[ROUTE ("[Controller]")]
Public Class MessageController: ControllerBase
{
    Private Readonly Ilogger <
MessageController >
 _logger;
    Private readonly httpclient httpclient;
    Private TelegrambotClient TelegrambotClient;
    Private String _Token {Get; SET; }= "1234567890: aabbcdefghijkkkkkkkkkkkkkkkkkkkkkk";
    Private String URL= "XXXXXX";
    Public MessageController (Ilogger <
MessageController >
 Logger)
    {
        _Logger= Logger;
        TelegrambotClient= New TelegrambotClient (_Token);
        httpclient= new httpclient ();
    }
    [HTTPPOST ("SendMessage")]
    Public ASYNC Task SendMessage ([FROMBODY] Messagedata Message)
    {
        //Run a bot for receiving messages
        TelegrambotClient.startReceiving ();
        //receiving messages from the bot
        TelegrambotClient.Onmessage += TelegrambotClient_ONMESSAGE;
        //Test Your API Configured Correctly
        //Var Me= await TelegrambotClient.getmeasync ();
        //Console.writeline($"{ME.userName} started ");
    }
    //here must come from Chat Bot
    Private Async Void TelegrambotClient_ONMESSAGE (Object Sender, Telegram.bot.args.MessageEventArgs e)
    {
        Var Message= E.Message;
        If (Message!= NULL)
        {
            Messagedata RequestMessage= New Messagedata {TextMessage= Message.Text};
            //Sending a request for API Dr. Service
            String JSonRequest= JSonSerializer.serialize (RequestMessage);
            String JsonResponsedata= AWAIT PostRequestHttpasync (URL, JSonRequest);
            Responsemessagedata responsedata= jsonserializer.deserialize <
Responsemessagedata >
(jsonresponsedata);
            //Reply to Chat Bot
            Await TelegrambotClient.sendTextMessageAsync (Message.Chat.ID, ResponSedata.TextMessage, ReplyTomessageID: Message.MessageID);
        }
    }
    //Function sending a request for API Dr. Service
    Public Async Task ≪
String >
 PostRequestHttpasync (String URL, String Json)
    {
        Using HttpContent Content= New StringContent (JSON, Encoding.UTF8, "Application /JSON");
        using httpresponsemessage response= await httpclient.postasync (URL, CONTENT) .configureawait (FALSE);
        Return await response.content.readasstringasync (). Configureawait (False);
    }
}
  • Answer # 1

    Yes, you do not need two ASP.NET Core Webapi projects, one is enough.

    Key -set a hook for a bot in telegrams. For you, the Hook is the usual action of the controller. The telegram itself will twink this method when the message will be received.

    Read the documentation for the creation of bots with telegrams or google, something like this came out: https://tlgrm.ru/docs/bots/api#setWebHook

    using System;
    using System.Threading;
    using system.threading.tasks;
    using mediatr;
    using microsoft.aspnetcore.mvc;
    using newtonsoft.json;
    using Telegram.bot.Types;
    using BotMessage= mycompany.myproj.telegramProcessor.BotMessage;
    namespace mycompany.myproj.webapplication.controllers.
    {
        [Apicontroller]
        [ROUTE ("API /[CONTROLLER] /[ACTION]")]
        Public Class TelegramlistenerController: Controller
        {
            [Httppost]
            Public Async Task ≪
    Object >
     Update ([FROMBODY] UPDATE UPDATE, CANCELLATIONTOKEN CANCELLATIONTOKEN)
            {
            }
        }
    }
    

    Webkuk is set once, here (I myself did a few years ago, probably nothing has changed since then):

    We assign Webhook using this URL:

    We insert it into the address bar of the browser and go through, if Everything went without errors, on the screen you will withdraw this information:

    {"OK": TRUE, "RESULT": TRUE, "Description": "Webhook Was Set"}

    In that service, to which I will be able to edit, I can not, I can only use his API, so I write a separate service

    Vlad-i-mir2021-09-14 12:11:33

    And where did you get this code, there are comments there (a lot for me unfamiliar objects and tools)?

    Vlad-i-mir2021-09-14 12:26:44

    The telegram itself will twink this method when the message will be received. -Where does telegrams know what method does it have to pull?

    Vlad-i-mir2021-09-14 12:33:23

    Telegrams for each bot stores up to 24 hours of communication, he is intended (from chats where bot and from personal users who write the bot). All you need is to tell the telegram "Hay, when there are messages -knock on this url" and that's it. So the mechanism works. How to create a hook -described in the documentation, in fact -you need to send a specially formed request to https://api.telegram.org/botouken.org/botouken}/setWebhook

    A K2021-09-14 13:20:57

    This code uses the MediaTR package to write auxiliary code less. You can not use this library, just look -the UPDATE class is a class of a connected library, and the rest is the usual asynchronous action of a regular ASP.NET controller.

    A K2021-09-14 13:22:46
  • Answer # 2

    Yes, you do not need two ASP.NET Core Webapi projects, one is enough.

    Key -set a hook for a bot in telegrams. For you, the Hook is the usual action of the controller. The telegram itself will twink this method when the message will be received.

    Read the documentation for the creation of bots with telegrams or google, something like this came out: https://tlgrm.ru/docs/bots/api#setWebHook

    using System;
    using System.Threading;
    using system.threading.tasks;
    using mediatr;
    using microsoft.aspnetcore.mvc;
    using newtonsoft.json;
    using Telegram.bot.Types;
    using BotMessage= mycompany.myproj.telegramProcessor.BotMessage;
    namespace mycompany.myproj.webapplication.controllers.
    {
        [Apicontroller]
        [ROUTE ("API /[CONTROLLER] /[ACTION]")]
        Public Class TelegramlistenerController: Controller
        {
            [Httppost]
            Public Async Task ≪
    Object >
     Update ([FROMBODY] UPDATE UPDATE, CANCELLATIONTOKEN CANCELLATIONTOKEN)
            {
            }
        }
    }
    

    Webkuk is set once, here (I myself did a few years ago, probably nothing has changed since then):

    We assign Webhook using this URL:

    We insert it into the address bar of the browser and go through, if Everything went without errors, on the screen you will withdraw this information:

    {"OK": TRUE, "RESULT": TRUE, "Description": "Webhook Was Set"}

    In that service, to which I will be able to edit, I can not, I can only use his API, so I write a separate service

    Vlad-i-mir2021-09-14 12:11:33

    And where did you get this code, there are comments there (a lot for me unfamiliar objects and tools)?

    Vlad-i-mir2021-09-14 12:26:44

    The telegram itself will twink this method when the message will be received. -Where does telegrams know what method does it have to pull?

    Vlad-i-mir2021-09-14 12:33:23

    Telegrams for each bot stores up to 24 hours of communication, he is intended (from chats where bot and from personal users who write the bot). All you need is to tell the telegram "Hay, when there are messages -knock on this url" and that's it. So the mechanism works. How to create a hook -described in the documentation, in fact -you need to send a specially formed request to https://api.telegram.org/botouken.org/botouken}/setWebhook

    A K2021-09-14 13:20:57

    This code uses the MediaTR package to write auxiliary code less. You can not use this library, just look -the UPDATE class is a class of a connected library, and the rest is the usual asynchronous action of a regular ASP.NET controller.

    A K2021-09-14 13:22:46