telegram: update dependency

This commit is contained in:
Alexey Bannov 2022-05-17 18:27:34 +03:00
parent d0525e298c
commit 7e6f8db8d9
9 changed files with 70 additions and 43 deletions

View File

@ -60,7 +60,8 @@
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.4" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
<PackageReference Include="Telegram.Bot" Version="15.7.1" />
<PackageReference Include="Telegram.Bot" Version="17.0.0" />
<PackageReference Include="Telegram.Bot.Extensions.Polling" Version="1.0.2" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="protos\create_client_proto.proto" />

View File

@ -30,7 +30,7 @@ public class TelegramUser : BaseEntity
{
public Guid PortalUserId { get; set; }
public int TenantId { get; set; }
public int TelegramUserId { get; set; }
public long TelegramUserId { get; set; }
public override object[] GetKeys()
{
return new object[] { TenantId, PortalUserId };

View File

@ -114,7 +114,7 @@ public class CachedTelegramDao
return users;
}
public void RegisterUser(Guid userId, int tenantId, int telegramId)
public void RegisterUser(Guid userId, int tenantId, long telegramId)
{
TgDao.RegisterUser(userId, tenantId, telegramId);

View File

@ -58,7 +58,7 @@ public class TelegramDao
TelegramDbContext = dbContextManager.Value;
}
public void RegisterUser(Guid userId, int tenantId, int telegramId)
public void RegisterUser(Guid userId, int tenantId, long telegramId)
{
var user = new TelegramUser
{

View File

@ -39,17 +39,20 @@ public class TelegramHelper
private readonly ConsumerFactory _consumerFactory;
private readonly CachedTelegramDao _cachedTelegramDao;
private readonly TelegramServiceClient _telegramServiceClient;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILog _logger;
public TelegramHelper(
ConsumerFactory consumerFactory,
IOptionsSnapshot<CachedTelegramDao> cachedTelegramDao,
TelegramServiceClient telegramServiceClient,
IHttpClientFactory httpClientFactory,
ILog logger)
{
_consumerFactory = consumerFactory;
_cachedTelegramDao = cachedTelegramDao.Value;
_telegramServiceClient = telegramServiceClient;
_httpClientFactory = httpClientFactory;
_logger = logger;
}
@ -169,6 +172,10 @@ public class TelegramHelper
public TelegramBotClient InitClient(string token, string proxy)
{
return string.IsNullOrEmpty(proxy) ? new TelegramBotClient(token) : new TelegramBotClient(token, new WebProxy(proxy));
var httpClient = _httpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(proxy);
return string.IsNullOrEmpty(proxy) ? new TelegramBotClient(token) : new TelegramBotClient(token, httpClient);
}
}

View File

@ -129,7 +129,7 @@ public class CommandModule
return parsedParams.ToArray();
}
public async Task HandleCommand(Message msg, TelegramBotClient client, int tenantId)
public async Task HandleCommand(Message msg, ITelegramBotClient client, int tenantId)
{
try
{

View File

@ -30,6 +30,7 @@ public class TenantTgClient
{
public string Token { get; set; }
public TelegramBotClient Client { get; set; }
public CancellationTokenSource CancellationTokenSource { get; set; }
public string Proxy { get; set; }
public int TokenLifeSpan { get; set; }
public int TenantId { get; set; }

View File

@ -54,3 +54,6 @@ global using Telegram.Bot.Args;
global using Telegram.Bot.Types;
global using ASC.EventBus.Abstractions;
global using ASC.TelegramService.IntegrationEvents.EventHandling;
global using Telegram.Bot.Exceptions;
global using Telegram.Bot.Types.Enums;

View File

@ -43,23 +43,11 @@ public class TelegramHandler
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
}
public Task SendMessage(NotifyMessage msg)
public async Task SendMessage(NotifyMessage msg)
{
if (string.IsNullOrEmpty(msg.Reciever))
{
return Task.CompletedTask;
}
if (string.IsNullOrEmpty(msg.Reciever)) return;
if (!_clients.ContainsKey(msg.TenantId)) return;
if (!_clients.ContainsKey(msg.TenantId))
{
return Task.CompletedTask;
}
return InternalSendMessage(msg);
}
private async Task InternalSendMessage(NotifyMessage msg)
{
var scope = _scopeFactory.CreateScope();
var cachedTelegramDao = scope.ServiceProvider.GetService<IOptionsSnapshot<CachedTelegramDao>>().Value;
@ -76,7 +64,8 @@ public class TelegramHandler
}
var chat = await client.GetChatAsync(tgUser.TelegramUserId);
await client.SendTextMessageAsync(chat, msg.Content, Telegram.Bot.Types.Enums.ParseMode.Markdown);
await client.SendTextMessageAsync(chat, msg.Content, ParseMode.MarkdownV2);
}
catch (Exception e)
{
@ -86,13 +75,16 @@ public class TelegramHandler
public void DisableClient(int tenantId)
{
if (!_clients.ContainsKey(tenantId))
{
return;
}
if (!_clients.ContainsKey(tenantId)) return;
var client = _clients[tenantId];
client.Client.StopReceiving();
if (client.CancellationTokenSource != null)
{
client.CancellationTokenSource.Cancel();
client.CancellationTokenSource.Dispose();
client.CancellationTokenSource = null;
}
_clients.Remove(tenantId);
}
@ -117,7 +109,12 @@ public class TelegramHandler
}
}
client.Client.StopReceiving();
if (client.CancellationTokenSource != null)
{
client.CancellationTokenSource.Cancel();
client.CancellationTokenSource.Dispose();
client.CancellationTokenSource = null;
}
BindClient(newClient, tenantId, stoppingToken);
@ -161,26 +158,44 @@ public class TelegramHandler
MemoryCache.Default.Set(token, userKey, dateExpires);
}
private Task OnMessage(object sender, MessageEventArgs e, TelegramBotClient client, int tenantId)
private void BindClient(TelegramBotClient client, int tenantId, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(e.Message.Text) || e.Message.Text[0] != '/')
var cts = new CancellationTokenSource();
_clients[tenantId].CancellationTokenSource = cts;
var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
client.StartReceiving(updateHandler: (botClient, exception, cancellationToken) => HandleUpdateAsync(botClient, exception, cancellationToken, tenantId),
errorHandler: HandleErrorAsync,
cancellationToken: linkedCts.Token);
}
async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken, int tenantId)
{
if (update.Type != UpdateType.Message) return;
if (update.Message.Type != MessageType.Text) return;
if (String.IsNullOrEmpty(update.Message.Text) || update.Message.Text[0] != '/') return;
await _command.HandleCommand(update.Message, botClient, tenantId);
}
Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
String errorMessage;
if (exception is ApiRequestException)
{
return Task.CompletedTask;
errorMessage = String.Format("Telegram API Error:\n[{0}]\n{1}", ((ApiRequestException)exception).ErrorCode, ((ApiRequestException)exception).Message);
}
else
{
errorMessage = exception.ToString();
}
return InternalOnMessage(sender, e, client, tenantId);
}
_log.Error(errorMessage);
private async Task InternalOnMessage(object sender, MessageEventArgs e, TelegramBotClient client, int tenantId)
{
await _command.HandleCommand(e.Message, client, tenantId);
}
private void BindClient(TelegramBotClient client, int tenantId, CancellationToken stoppingToken)
{
client.OnMessage += async (sender, e) => { await OnMessage(sender, e, client, tenantId); };
client.StartReceiving(cancellationToken: stoppingToken);
return Task.CompletedTask;
}
private string UserKey(string userId, int tenantId)