Skip to content

Commit

Permalink
Support providing different languages in appsettings
Browse files Browse the repository at this point in the history
  • Loading branch information
ImoutoChan committed Dec 11, 2023
1 parent 0479c52 commit daad1c8
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 48 deletions.
15 changes: 10 additions & 5 deletions CaptchaBot.Tests/WelcomeServiceTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.Globalization;
using CaptchaBot.Services;
using CaptchaBot.Services.Translation;
using FakeItEasy;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Telegram.Bot;
using Telegram.Bot.Requests;
using Telegram.Bot.Requests.Abstractions;
Expand All @@ -17,10 +19,13 @@ public class WelcomeServiceTests
private readonly ITelegramBotClient _botMock;
private readonly ILogger<WelcomeService> _logger;
private readonly List<int> _deletedMessages = new();
private readonly TranslationService _translationService;

public WelcomeServiceTests(ITestOutputHelper outputHelper)
{
_logger = outputHelper.BuildLoggerFor<WelcomeService>();
_translationService = new(Options.Create<TranslationSettings>(new()));

_botMock = A.Fake<ITelegramBotClient>();
A.CallTo(() => _botMock.MakeRequestAsync(A<SendMessageRequest>._, A<CancellationToken>._))
.Returns(new Message());
Expand Down Expand Up @@ -73,7 +78,7 @@ private async Task ProcessAnswer(IWelcomeService service, bool successful)
public async Task BotShouldProcessEventWithinTimeout()
{
var config = new AppSettings {ProcessEventTimeout = TimeSpan.FromSeconds(5.0)};
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock);
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService);

const long testUserId = 123L;
await ProcessNewChatMember(welcomeService, testUserId, DateTime.UtcNow);
Expand Down Expand Up @@ -102,7 +107,7 @@ public async Task BotShouldProcessEventWithinTimeout()
public async Task BotShouldNotProcessEventOutsideTimeout()
{
var config = new AppSettings {ProcessEventTimeout = TimeSpan.FromMinutes(5.0)};
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock);
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService);

const int testUserId = 345;
await ProcessNewChatMember(welcomeService, testUserId, DateTime.UtcNow - TimeSpan.FromMinutes(6.0));
Expand All @@ -115,7 +120,7 @@ public async Task BotShouldNotProcessEventOutsideTimeout()
public async Task BotShouldRestrictTheEnteringUserAndNotTheMessageAuthor()
{
var config = new AppSettings();
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock);
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService);

const long enteringUserId = 123L;
const long invitingUserId = 345L;
Expand All @@ -140,7 +145,7 @@ public async Task BotShouldNotFailIfMessageCouldNotBeDeleted()
.Throws(new Exception("This exception should not fail the message processing."));

var config = new AppSettings();
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock);
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService);

const long newUserId = 124L;

Expand All @@ -159,7 +164,7 @@ private async Task DoRemoveJoinTest(
const long userId = 100L;

var config = new AppSettings { DeleteJoinMessages = policy };
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock);
var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService);

await ProcessNewChatMember(welcomeService, userId, DateTime.UtcNow, joinMessageId: joinMessageId);
await ProcessAnswer(welcomeService, successful);
Expand Down
17 changes: 1 addition & 16 deletions CaptchaBot/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,5 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58687/",
"sslPort": 44352
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"CaptchaBot": {
"commandName": "Project",
"launchBrowser": true,
Expand All @@ -31,4 +16,4 @@
"useSSL": true
}
}
}
}
28 changes: 28 additions & 0 deletions CaptchaBot/Services/Translation/TranslationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.Extensions.Options;

namespace CaptchaBot.Services.Translation;

public interface ITranslationService
{
string GetWelcomeMessage(string prettyUserName, in int answer);
}

public class TranslationService : ITranslationService
{
public TranslationService(IOptions<TranslationSettings> options)
{
var settings = options.Value;

NumberTexts = settings.NumberTexts.Split(',');
WelcomeMessageTemplate = settings.WelcomeMessageTemplate;
}

private string[] NumberTexts { get; }

private string WelcomeMessageTemplate { get; }

private string GetRequestedNumberText(in int answer) => NumberTexts[answer];

public string GetWelcomeMessage(string prettyUserName, in int answer)
=> string.Format(WelcomeMessageTemplate, prettyUserName, GetRequestedNumberText(answer));
}
8 changes: 8 additions & 0 deletions CaptchaBot/Services/Translation/TranslationSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace CaptchaBot.Services.Translation;

public class TranslationSettings
{
public string NumberTexts { get; set; } = "ноль,один,два,три,четыре,пять,шесть,семь,восемь";

public string WelcomeMessageTemplate { get; set; } = "Привет, {0}, нажми кнопку {1}, чтобы тебя не забанили!";
}
12 changes: 2 additions & 10 deletions CaptchaBot/Services/UsersStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@ namespace CaptchaBot.Services;

public class UsersStore : IUsersStore
{
private readonly ConcurrentDictionary<ChatUser, NewUser> _users;

public UsersStore()
{
_users = new ConcurrentDictionary<ChatUser, NewUser>();
}
private readonly ConcurrentDictionary<ChatUser, NewUser> _users = new();

public void Add(
User user,
Expand All @@ -34,10 +29,7 @@ public void Add(
_users.AddOrUpdate(key, newValue, (_, _) => newValue);
}

public IReadOnlyCollection<NewUser> GetAll()
{
return _users.Values.ToArray();
}
public IReadOnlyCollection<NewUser> GetAll() => _users.Values.ToArray();

public NewUser? Get(long chatId, long userId)
{
Expand Down
24 changes: 7 additions & 17 deletions CaptchaBot/Services/WelcomeService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text.Json;
using CaptchaBot.Services.Translation;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
Expand All @@ -8,36 +9,27 @@ namespace CaptchaBot.Services;

public class WelcomeService : IWelcomeService
{
private static readonly string[] NumberTexts =
{
"ноль",
"один",
"два",
"три",
"четыре",
"пять",
"шесть",
"семь",
"восемь",
};

private const int ButtonsCount = 8;
private static readonly Random Random = new Random();

private readonly AppSettings _settings;
private readonly IUsersStore _usersStore;
private readonly ILogger<WelcomeService> _logger;
private readonly ITelegramBotClient _telegramBot;
private readonly ITranslationService _translationService;

public WelcomeService(
AppSettings settings,
IUsersStore usersStore,
ILogger<WelcomeService> logger,
ITelegramBotClient telegramBot)
ITelegramBotClient telegramBot,
ITranslationService translationService)
{
_settings = settings;
_usersStore = usersStore;
_logger = logger;
_telegramBot = telegramBot;
_translationService = translationService;
}

public async Task ProcessCallback(CallbackQuery query)
Expand Down Expand Up @@ -234,7 +226,7 @@ await _telegramBot.RestrictChatMemberAsync(
var sentMessage = await _telegramBot
.SendTextMessageAsync(
message.Chat.Id,
$"Привет, {prettyUserName}, нажми кнопку {GetText(answer)}, чтобы тебя не забанили!",
_translationService.GetWelcomeMessage(prettyUserName, answer),
replyToMessageId: message.MessageId,
replyMarkup: new InlineKeyboardMarkup(GetKeyboardButtons()));

Expand All @@ -248,8 +240,6 @@ await _telegramBot.RestrictChatMemberAsync(
}
}

private static string GetText(in int answer) => NumberTexts[answer];

private static string GetPrettyName(User messageNewChatMember)
{
var names = new List<string>(3);
Expand Down
3 changes: 3 additions & 0 deletions CaptchaBot/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using CaptchaBot.Services;
using CaptchaBot.Services.Translation;
using Microsoft.Extensions.Options;
using Telegram.Bot;

Expand All @@ -20,6 +21,7 @@ public void ConfigureServices(IServiceCollection services)

services.AddOptions();
services.Configure<AppSettings>(Configuration.GetSection("Configuration"));
services.Configure<TranslationSettings>(Configuration.GetSection("Translation"));

services.AddTransient(ser => ser.GetRequiredService<IOptions<AppSettings>>().Value);

Expand All @@ -32,6 +34,7 @@ public void ConfigureServices(IServiceCollection services)

services.AddSingleton<IUsersStore, UsersStore>();
services.AddTransient<IWelcomeService, WelcomeService>();
services.AddTransient<ITranslationService, TranslationService>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down

0 comments on commit daad1c8

Please sign in to comment.