C# WTelegramClient Telegram-API How to programmatically click a button in a message from Telegram-Bot

2.3k Views Asked by At

The program communicates with Telegram-Bot. A text message is sent to the bot. The bot responds to the message. The answer contains 3 buttons. Question: How to click on a button programmatically?

Create a Telegram client:

_client = new WTelegram.Client(Config):
_user = await _client.LoginUserIfNeeded();

Finding a bot:

var contacts = await _client.Contacts_Search("@Search_bot", 20);
contacts.users.TryGetValue(1911124859, out peerBot));

Sending a request (message) to the Bot:

var message = await _client.SendMessageAsync(peerBot, "REQUEST");

We get an answer:

var differenceMessages = await _client.Updates_GetDifference(state.pts, state.date, state.qts);

We understand the answer. We find a button. How to send a message to the Bot that we clicked on the button?

TL.Message tLMessage = null;
if (differenceMessages != null)
{
    if(differenceMessages.NewMessages != null)
    {
        foreach (var difference in differenceMessages.NewMessages)
        {
            tLMessage = difference as TL.Message;
            if(tLMessage != null && tLMessage.peer_id.ID == peerBot.ID )
            {
                if (!(tLMessage.reply_markup is ReplyMarkup replyMarkup)) continue;
                TL.ReplyInlineMarkup replyInlineMarkup = (ReplyInlineMarkup)replyMarkup;
                if (replyInlineMarkup.rows[2].buttons[0].Text == "Check text on Button")
                {
                    ***//TODO We want to click on this button!***
                }
            }
        }
    }
}
1

There are 1 best solutions below

1
On

An inline button can be one of several types.
Let's assume you're talking about a Callback button (that sends its callback to the bot)..

Searching through the full list of API methods available, you would quickly find that the right method to proceed to clicking on that button is messages.getBotCallbackAnswer (so Messages_GetBotCallbackAnswer in WTelegramClient naming)

Therefore, in your case, you would write something like this:

    if (msg is TL.Message tlMessage && tlMessage.reply_markup is ReplyInlineMarkup replyInlineMarkup)
    {
        if (replyInlineMarkup.rows[ROW].buttons[COLUMN] is KeyboardButtonCallback btnCallback)
        {
            var answer = await client.Messages_GetBotCallbackAnswer(peerBot, tlMessage.id, data: btnCallback.data);
        }
    }