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.
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 enableManage ChatandRead Message Historyfor your bot in the group’s admin settings. Without these, the bot won’t receive the join events required to track invites.Handle
ChatMemberUpdatedevents to trace invites
When a new member joins, the API sends aChatMemberUpdatedobject. This update includes anInviteLinkproperty (if the user joined via a tracked link), which has aCreatorfield pointing to the member who generated the link.Here’s a C# snippet using the official
Telegram.BotNuGet 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.
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 aDictionary<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 theTelegram.BotNuGet package. The most common reason people think this isn’t possible is missing admin permissions or not leveraging theInviteLinkfield inChatMemberUpdatedupdates.
内容的提问来源于stack exchange,提问作者Hamidreza

