Initialize service

This commit is contained in:
Sergey Nazarov 2024-03-19 19:51:45 +04:00
parent 066d42abab
commit 6b0958c34c
16 changed files with 257 additions and 0 deletions

View File

@ -1,6 +1,8 @@
<Project>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<MicrosoftVersion>8.0.0</MicrosoftVersion>
<InsightTelegramBotVersion>0.16.0</InsightTelegramBotVersion>
</PropertyGroup>
@ -15,5 +17,6 @@
<PackageVersion Include="Serilog.Settings.Configuration" Version="8.0.0"/>
</ItemGroup>
<ItemGroup Label="Microsoft">
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="$(MicrosoftVersion)"/>
</ItemGroup>
</Project>

View File

@ -8,9 +8,29 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nocr.TelegramClient.Core", "src\Nocr.TelegramClient.Core\Nocr.TelegramClient.Core.csproj", "{3E87693C-78DF-469B-BAA3-CB103F8EA80B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nocr.TelegramClient.AppServices", "src\Nocr.TelegramClient.AppServices\Nocr.TelegramClient.AppServices.csproj", "{5CCB085C-860A-4C4C-907C-10183ABCEA9B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nocr.TelegramClient.Host", "src\Nocr.TelegramClient.Host\Nocr.TelegramClient.Host.csproj", "{58D5C9FD-75A9-4FFB-9FBD-BE8E9FCE3016}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3E87693C-78DF-469B-BAA3-CB103F8EA80B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E87693C-78DF-469B-BAA3-CB103F8EA80B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E87693C-78DF-469B-BAA3-CB103F8EA80B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E87693C-78DF-469B-BAA3-CB103F8EA80B}.Release|Any CPU.Build.0 = Release|Any CPU
{5CCB085C-860A-4C4C-907C-10183ABCEA9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5CCB085C-860A-4C4C-907C-10183ABCEA9B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CCB085C-860A-4C4C-907C-10183ABCEA9B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CCB085C-860A-4C4C-907C-10183ABCEA9B}.Release|Any CPU.Build.0 = Release|Any CPU
{58D5C9FD-75A9-4FFB-9FBD-BE8E9FCE3016}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{58D5C9FD-75A9-4FFB-9FBD-BE8E9FCE3016}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58D5C9FD-75A9-4FFB-9FBD-BE8E9FCE3016}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58D5C9FD-75A9-4FFB-9FBD-BE8E9FCE3016}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,31 @@
using Insight.TelegramBot;
using Insight.TelegramBot.Models;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace Nocr.TelegramClient.AppServices;
public sealed class BotClient : Bot
{
private readonly ILogger<BotClient> _logger;
public BotClient(ILogger<BotClient> logger, ITelegramBotClient client) : base(client)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public override Task<Message> SendMessageAsync(TextMessage message,
CancellationToken cancellationToken = default)
{
try
{
return base.SendMessageAsync(message, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Bot can't initiate conversation with a user: {message}", message);
throw;
}
}
}

View File

@ -0,0 +1,28 @@
using Insight.TelegramBot;
using Insight.TelegramBot.Handling.Handlers;
using Insight.TelegramBot.Models;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Nocr.TelegramClient.AppServices.Handlers.Messages;
public class StartMessageHandler : IMatchingUpdateHandler<StartMessageMatcher>
{
private readonly IBot _bot;
public StartMessageHandler(IBot bot)
{
_bot = bot ?? throw new ArgumentNullException(nameof(bot));
}
public Task Handle(Update update, CancellationToken cancellationToken = default)
{
var message = new TextMessage(update.Message.Chat)
{
Text = "Привет! Я _bot_name_",
ParseMode = ParseMode.Html
};
return _bot.SendMessageAsync(message, cancellationToken);
}
}

View File

@ -0,0 +1,11 @@
using Insight.TelegramBot.Handling.Matchers.TextMatchers;
namespace Nocr.TelegramClient.AppServices.Handlers.Messages;
public sealed class StartMessageMatcher : TextStartWithUpdateMatcher
{
public StartMessageMatcher()
{
Template = "/start";
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Insight.TelegramBot" />
<PackageReference Include="Insight.TelegramBot.Handling" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
namespace Nocr.TelegramClient.Core.Dates;
public sealed class DefaultCurrentDateProvider : ICurrentDateProvider
{
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
}

View File

@ -0,0 +1,6 @@
namespace Nocr.TelegramClient.Core.Dates;
public interface ICurrentDateProvider
{
public DateTimeOffset UtcNow { get; }
}

View File

@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk" />

View File

@ -0,0 +1,24 @@
using Serilog;
namespace Nocr.TelegramClient.Host.Infrastructure;
public class HostBuilderFactory<TStartup> where TStartup : class
{
public IHostBuilder CreateHostBuilder(string[] args, string? baseDirectory = null)
{
var builder = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((_, configurationBuilder) =>
{
if (!string.IsNullOrWhiteSpace(baseDirectory))
configurationBuilder.SetBasePath(baseDirectory);
})
.ConfigureWebHostDefaults(host => { host.UseStartup<TStartup>(); })
.UseSerilog((ctx, logBuilder) =>
{
logBuilder.ReadFrom.Configuration(ctx.Configuration)
.Enrich.FromLogContext();
});
return builder;
}
}

View File

@ -0,0 +1,37 @@
using System.Data;
using Insight.TelegramBot.Handling.Infrastructure;
using Insight.TelegramBot.Hosting.DependencyInjection.Infrastructure;
using Insight.TelegramBot.Hosting.Polling.ExceptionHandlers;
using Microsoft.Extensions.Options;
using Nocr.TelegramClient.AppServices;
using Nocr.TelegramClient.Core.Dates;
namespace Nocr.TelegramClient.Host.Infrastructure;
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICurrentDateProvider, DefaultCurrentDateProvider>();
services.AddTelegramBot(bot =>
bot.WithBot<BotClient>(ServiceLifetime.Transient)
.WithTelegramBotClient(client => client
.WithLifetime(ServiceLifetime.Singleton)
.WithMicrosoftHttpClientFactory())
.WithOptions(opt => opt.FromConfiguration(Configuration))
.WithPolling(polling => polling.WithExceptionHandler<LoggingPollingExceptionHandler>()));
services.AddTelegramBotHandling(typeof(BotClient).Assembly);
}
public void Configure(IApplicationBuilder app)
{
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Insight.TelegramBot.Hosting.DependencyInjection" />
<PackageReference Include="Serilog.AspNetCore" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Nocr.TelegramClient.AppServices\Nocr.TelegramClient.AppServices.csproj" />
<ProjectReference Include="..\Nocr.TelegramClient.Core\Nocr.TelegramClient.Core.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,7 @@
using Nocr.TelegramClient.Host.Infrastructure;
var host = new HostBuilderFactory<Startup>()
.CreateHostBuilder(args)
.Build();
await host.RunAsync();

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Level:u3}] {Timestamp:MM-dd HH:mm:ss} {TraceId} {SourceContext:l} {Message:lj}{NewLine}{Exception}"
}
}
]
},
"TelegramBotOptions": {
"WebHook": {
"UseWebHook": false,
"WebHookBaseUrl": "http://localhost",
"WebHookPath": "update/TokenPartAfterDoubleDot"
},
"Token": ""
}
}

View File

@ -0,0 +1,25 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Level:u3}] {Timestamp:MM-dd HH:mm:ss} {TraceId} {SourceContext:l} {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "/var/log/nocr/telegram-client/nocr-telegram-client-.log",
"outputTemplate": "[{Level:u3}] {Timestamp:dd-MM-yyyy HH:mm:ss} {TraceId} {SourceContext:l} {Message:lj}{NewLine}{Exception}",
"fileSizeLimitBytes": 104857600,
"rollingInterval": "Day",
"rollOnFileSizeLimit": true
}
}
]
}
}

View File

@ -0,0 +1,12 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"Microsoft.AspNetCore": "Error",
"System.Net.Http.HttpClient": "Warning"
}
}
}
}