52 lines
1.8 KiB
C#
52 lines
1.8 KiB
C#
using KLHZ.Trader.Core.Common.Messaging.Contracts;
|
|
using KLHZ.Trader.Core.Common.Messaging.Contracts.Messages;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Options;
|
|
using System.Collections.Immutable;
|
|
using System.Threading.Channels;
|
|
using Telegram.Bot;
|
|
using Telegram.Bot.Polling;
|
|
|
|
namespace KLHZ.Trader.Core.TG.Services
|
|
{
|
|
public class BotStarter : IHostedService
|
|
{
|
|
private readonly TelegramBotClient _botClient;
|
|
private readonly IUpdateHandler _updateHandler;
|
|
private readonly Channel<MessageForAdmin> _messages = Channel.CreateUnbounded<MessageForAdmin>();
|
|
private readonly ImmutableArray<long> _admins = [];
|
|
|
|
public BotStarter(IOptions<TgBotConfig> cfg, IUpdateHandler updateHandler, IDataBus dataBus, IOptions<TgBotConfig> options)
|
|
{
|
|
_botClient = new TelegramBotClient(cfg.Value.Token);
|
|
_updateHandler = updateHandler;
|
|
dataBus.AddChannel(_messages);
|
|
_admins = ImmutableArray.CreateRange(options.Value.Admins);
|
|
_ = ProcessMessages();
|
|
}
|
|
|
|
private async Task ProcessMessages()
|
|
{
|
|
while (await _messages.Reader.WaitToReadAsync())
|
|
{
|
|
var message = await _messages.Reader.ReadAsync();
|
|
foreach (var admin in _admins)
|
|
{
|
|
await _botClient.SendMessage(admin, message.Text);
|
|
}
|
|
}
|
|
}
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
_botClient.StartReceiving(_updateHandler);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
return _botClient.Close();
|
|
}
|
|
}
|
|
}
|