C# Telegram Bot Notification



是否有一种方法可以在c#中从bot发送通知给用户(个人消息)?我只找到解决方案发送消息到一个频道/组,我的机器人添加了管理员权限。

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

稍后,我想让用户能够向这个bot发送命令来操作系统中的一些关键功能,例如,但不限于,添加新用户。当然有必要的管理员权限。

经过几个小时的研究和测试,我解决了我自己的问题,所以我在这里发布这个答案。

首先,我创建了一个EventHandler类来处理我的Telegram bot的所有传入消息:

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}");
}
}
}

之后,我在我的启动中注入了这个类:

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();
}

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

一旦任何用户登录-具有web系统内部授予的权限-他们将收到我在Telegram内的bot的个人消息。