Search code examples
c#botstelegram

Create invite button in telegram bot


I want to create invite inline button in my telegram bot.

I use library Telegram.Bot 18.0.0 in C#. I have tried this case

var button = InlineKeyboardButton.WithSwitchInlineQuery("test");

InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(button);

but that's not it. This is how this button looks, it has a plus in the corner.


Solution

  • If the group/channel is open, then just send the invite-link to everyone:

    var inlineButton = InlineKeyboardButton.WithUrl("Join", _inviteLink);
    var replyMarkup = new InlineKeyboardMarkup(inlineButton);
    await botClient.SendTextMessageAsync(update.Message.Chat.Id, "Join button:", replyMarkup: replyMarkup);
    

    If the group/channel is private, you can create an invite link for each user with the necessary createsJoinRequest = true.

    var invite = await botClient.CreateChatInviteLinkAsync(_privateChannelId, update.Message.From.Id.ToString(), DateTime.Now.AddDays(7), null, true, cancellationToken);
    

    In the name of the invitation, you can write a user_Id and automatically check and approve applications:

    if (update.Type == UpdateType.ChatJoinRequest && update.ChatJoinRequest != null)
    {
        if (update.ChatJoinRequest.InviteLink != null && update.ChatJoinRequest.InviteLink.Creator.Id == _myId)
        {
            var userId = update.ChatJoinRequest.From.Id;
    
            if (update.ChatJoinRequest.InviteLink.Name == userId.ToString()))
            {
                var res = await botClient.ApproveChatJoinRequest(_privateChannelId, userId, cancellationToken);
                if (res)
                {
                    await botClient.SendTextMessageAsync(userId, "Welcome.");
                }
            }
        }
    }
    

    PS: this is a simplified code to show the idea and structure.