You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram机器人:识别成员邀新及统计邀新人数(C#开发求助)

Hey there! Let’s break down your two Telegram bot questions specifically for your C# setup—no fancy external plugins needed, just smart use of the Bot API and basic state tracking.

1. Identifying Which Member Invited a New User

Telegram’s Bot API doesn’t directly send an "invite event," but you can track invites using ChatMemberUpdated updates and invite link metadata. Here’s how to make it work:

  • First, ensure your bot has the right admin permissions
    You need to enable Manage Chat and Read Message History for your bot in the group’s admin settings. Without these, the bot won’t receive the join events required to track invites.

  • Handle ChatMemberUpdated events to trace invites
    When a new member joins, the API sends a ChatMemberUpdated object. This update includes an InviteLink property (if the user joined via a tracked link), which has a Creator field pointing to the member who generated the link.

    Here’s a C# snippet using the official Telegram.Bot NuGet package:

    using Telegram.Bot;
    using Telegram.Bot.Types;
    using Telegram.Bot.Types.Enums;
    using System.Threading;
    using System.Threading.Tasks;
    
    async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
    {
        if (update.ChatMember is not ChatMemberUpdated chatMemberUpdate)
            return;
    
        // Check if a user just joined the group
        if (chatMemberUpdate.NewChatMember.Status == ChatMemberStatus.Member)
        {
            var newMember = chatMemberUpdate.NewChatMember.User;
            var inviteLink = chatMemberUpdate.InviteLink;
    
            if (inviteLink != null)
            {
                var inviter = inviteLink.Creator;
                // You now have inviter (X) and new member (Y)
                await botClient.SendTextMessageAsync(
                    chatId: chatMemberUpdate.Chat.Id,
                    text: $"Welcome {newMember.FirstName}! You were invited by {inviter.FirstName}!",
                    cancellationToken: cancellationToken
                );
            }
            else
            {
                // Handle cases where the invite link isn't trackable (e.g., default group link)
                // To fix this, have admins use bot-generated links exclusively
                await botClient.SendTextMessageAsync(
                    chatId: chatMemberUpdate.Chat.Id,
                    text: $"Welcome {newMember.FirstName}! We couldn't track who invited you—ask admins to use bot-generated invite links.",
                    cancellationToken: cancellationToken
                );
            }
        }
    }
    
  • Enforce bot-generated unique links
    To eliminate untrackable joins, let your bot generate unique invite links for each member when they request one. Store a mapping between each link and its creator, so every join via these links can be traced back to the inviter.

2. Tracking Invite Counts per Member

Once you can identify the inviter for each new join, counting invites is just a matter of persisting the data. Here’s how to implement this in C#:

  • In-memory storage (for testing)
    Use a Dictionary<long, int> to track counts temporarily (note: this resets when the bot restarts):

    // Declare this at the class level to persist across updates
    private static readonly Dictionary<long, int> _inviteCounts = new();
    
    // Inside the ChatMember handler above, after confirming the inviter:
    var inviterId = inviter.Id;
    if (_inviteCounts.ContainsKey(inviterId))
        _inviteCounts[inviterId]++;
    else
        _inviteCounts[inviterId] = 1;
    
    // Optional: Notify the inviter of their updated count
    await botClient.SendTextMessageAsync(
        chatId: inviterId,
        text: $"Great job! You've now invited {_inviteCounts[inviterId]} members to the group.",
        cancellationToken: cancellationToken
    );
    
  • Persistent storage (for production)
    For a bot that stays online long-term, use a database like SQLite, PostgreSQL, or SQL Server. With Entity Framework Core, you can create a simple model to store stats:

    public class InviteStat
    {
        public long UserId { get; set; }
        public int InviteCount { get; set; }
    }
    

    Update the count in your database whenever a new member joins via an inviter’s link—this ensures data survives bot restarts.

  • Do you need a plugin?
    No external plugins are required here. All functionality is available via the official Telegram Bot API and the Telegram.Bot NuGet package. The most common reason people think this isn’t possible is missing admin permissions or not leveraging the InviteLink field in ChatMemberUpdated updates.

内容的提问来源于stack exchange,提问作者Hamidreza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:44:27