C# Telegram 机器人通知

C# Telegram Bot Notification

C# 中有没有一种方法可以从机器人向用户发送通知(个人消息)?我只找到了将消息发送到 channel/group 的解决方案,我的机器人在其中添加了管理员权限。

我想在登录/系统通知时从我的系统向用户发送通知 - 如果允许的话。

稍后我想让用户能够向此机器人发送命令以执行系统中的一些关键功能,例如但不限于添加新用户。当然有必要的管理员权限。

我发布这个答案是因为我在经过几个小时的研究和测试后解决了我自己的问题。

首先,我创建了一个 EventHandler class 来处理所有传入我的 Telegram 机器人的消息:

    public class TelegramBotEvents
    {
        private readonly TelegramBotClient _telegramBotClient;
        private readonly ODWorkflowDBContext _context;

        public TelegramBotEvents(
            ODWorkflowDBContext context,
            TelegramBotClient telegramBotClient
        )
        {
            this._context = context ?? throw new ArgumentNullException(nameof(context));

            this._telegramBotClient = telegramBotClient ?? throw new ArgumentNullException(nameof(telegramBotClient));

#pragma warning disable CS0618 // Type or member is obsolete. TODO: Implement Polling
            this._telegramBotClient.StartReceiving();
            this._telegramBotClient.OnMessage += (sender, eventArg) =>
            {
                if (eventArg.Message != null)
                {
                    MessageReceive(eventArg.Message);
                }
            };
#pragma warning restore CS0618 // Type or member is obsolete. TODO: Implement Polling
        }

        public void MessageReceive(Message message)
        {
            try
            {
                if (message.Type == MessageType.Text)
                {
                    if (message.Text.ToLower() == "/register")
                    {
                        var userThirdPartyNotification = this._context.UserThirdPartyNotifications.FirstOrDefault(e =>
                            e.UserThirdPartyNotificationActive &&
                            e.UserThirdPartyNotificationUserName == message.From.Username);

                        userThirdPartyNotification.UserThirdPartyNotificationChatId = message.From.Id;

                        this._context.UserThirdPartyNotifications.Update(userThirdPartyNotification);
                        this._context.SaveChanges();

                        this._telegramBotClient.SendTextMessageAsync(message.From.Id, "You have successfully opted in to receive notifications via Telegram.");
                    }
                }
                else
                {
                    this._telegramBotClient.SendTextMessageAsync(message.From.Id, $"\"{message.Text}\" was not found. Please try again.");
                }
            }
            catch (Exception ex)
            {
                this._telegramBotClient.SendTextMessageAsync(message.From.Id, $"Failure processing your message: {ex.Message}");
            }

        }
    }

在上述之后我在我的启动中注入了这个class:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession();

            #region Dependency_Injections
            services.AddScoped<IPasswordEncrypt, PasswordEncrypt>();
            services.AddScoped<IHelperFunctions, HelperFunctions>();
            services.AddScoped<IEncryptor, Encryptor>();
            services.AddTransient(typeof(ILogging<>), typeof(Logging<>));

            services.AddSingleton(new TelegramBotClient(Configuration["ArtificialConfigs:TelegramBotToken"]));

            services.AddScoped(p => 
                new TelegramBotEvents(
                    (DBContext)p.GetService(typeof(DBContext)), 
                    (TelegramBotClient)p.GetService(typeof(TelegramBotClient))));
            #endregion

            services.AddControllersWithViews();
            services.AddRazorPages();
        }

在这两个步骤之后,我可以从向我的机器人发送任何消息的用户那里捕获客户端 ID。

一旦任何用户登录 - 并在网络系统内授予权限 - 他们将在 Telegram 中收到来自我的机器人的个人消息。