Skip to content

Commit

Permalink
Upgrade to net9.0 and update packages
Browse files Browse the repository at this point in the history
  • Loading branch information
ImoutoChan committed Dec 8, 2024
1 parent ab43ff7 commit 4655221
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 66 deletions.
14 changes: 7 additions & 7 deletions CaptchaBot.Tests/CaptchaBot.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<ImplicitUsings>true</ImplicitUsings>
Expand All @@ -10,15 +10,15 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Divergic.Logging.Xunit" Version="4.3.0" />
<PackageReference Include="FakeItEasy" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.4">
<PackageReference Include="Divergic.Logging.Xunit" Version="4.3.1" />
<PackageReference Include="FakeItEasy" Version="8.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
22 changes: 11 additions & 11 deletions CaptchaBot.Tests/WelcomeServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@ public WelcomeServiceTests(ITestOutputHelper outputHelper)
_translationService = new(Options.Create<TranslationSettings>(new()));

_botMock = A.Fake<ITelegramBotClient>();
A.CallTo(() => _botMock.MakeRequestAsync(A<SendMessageRequest>._, A<CancellationToken>._))
A.CallTo(() => _botMock.SendRequest(A<SendMessageRequest>._, A<CancellationToken>._))
.Returns(new Message());

A.CallTo(() => _botMock.MakeRequestAsync(A<GetChatMemberRequest>._, A<CancellationToken>._))
A.CallTo(() => _botMock.SendRequest(A<GetChatMemberRequest>._, A<CancellationToken>._))
.Returns(new ChatMemberMember());

A.CallTo(() => _botMock.MakeRequestAsync(A<GetChatRequest>._, A<CancellationToken>._))
.Returns(new Chat());
A.CallTo(() => _botMock.SendRequest(A<GetChatRequest>._, A<CancellationToken>._))
.Returns(new ChatFullInfo());

A.CallTo(() => _botMock.MakeRequestAsync(A<DeleteMessageRequest>._, A<CancellationToken>._))
A.CallTo(() => _botMock.SendRequest(A<DeleteMessageRequest>._, A<CancellationToken>._))
.Invokes((IRequest<bool> request, CancellationToken _) => _deletedMessages.Add((request as DeleteMessageRequest)!.MessageId));
}

Expand All @@ -50,7 +50,7 @@ private static Task ProcessNewChatMember(
var testUser = new User {Id = userId};
var message = new Message
{
MessageId = joinMessageId,
Id = joinMessageId,
Date = enterTime,
Chat = new Chat(),
From = new User {Id = fromId},
Expand Down Expand Up @@ -86,17 +86,17 @@ public async Task BotShouldProcessEventWithinTimeout()
Assert.Collection(Fake.GetCalls(_botMock),
getChatMember =>
{
Assert.Equal(nameof(ITelegramBotClient.MakeRequestAsync), getChatMember.Method.Name);
Assert.Equal(nameof(ITelegramBotClient.SendRequest), getChatMember.Method.Name);
Assert.IsType<GetChatMemberRequest>(getChatMember.Arguments.First());
},
restrict =>
{
Assert.Equal(nameof(ITelegramBotClient.MakeRequestAsync), restrict.Method.Name);
Assert.Equal(nameof(ITelegramBotClient.SendRequest), restrict.Method.Name);
Assert.IsType<RestrictChatMemberRequest>(restrict.Arguments.First());
},
sendMessage =>
{
Assert.Equal(nameof(ITelegramBotClient.MakeRequestAsync), sendMessage.Method.Name);
Assert.Equal(nameof(ITelegramBotClient.SendRequest), sendMessage.Method.Name);
Assert.IsType<SendMessageRequest>(sendMessage.Arguments.First());
});

Expand Down Expand Up @@ -131,7 +131,7 @@ public async Task BotShouldRestrictTheEnteringUserAndNotTheMessageAuthor()
_ => {},
restrict =>
{
Assert.Equal(nameof(ITelegramBotClient.MakeRequestAsync), restrict.Method.Name);
Assert.Equal(nameof(ITelegramBotClient.SendRequest), restrict.Method.Name);
var restrictedUserId = (RestrictChatMemberRequest)restrict.Arguments[0]!;
Assert.Equal(enteringUserId, restrictedUserId.UserId);
},
Expand All @@ -141,7 +141,7 @@ public async Task BotShouldRestrictTheEnteringUserAndNotTheMessageAuthor()
[Fact]
public async Task BotShouldNotFailIfMessageCouldNotBeDeleted()
{
A.CallTo(() => _botMock.MakeRequestAsync(A<DeleteMessageRequest>._, A<CancellationToken>._))
A.CallTo(() => _botMock.SendRequest(A<DeleteMessageRequest>._, A<CancellationToken>._))
.Throws(new Exception("This exception should not fail the message processing."));

var config = new AppSettings();
Expand Down
7 changes: 3 additions & 4 deletions CaptchaBot/BanHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,9 @@ private async Task BanSlowUsers()

foreach (var newUser in usersToBan)
{
await InvokeSafely(() =>
_telegramBot.BanChatMemberAsync(newUser.ChatId, newUser.Id, DateTime.Now.AddDays(1)));
await InvokeSafely(() => _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.InviteMessageId));
await InvokeSafely(() => _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.JoinMessageId));
await InvokeSafely(() => _telegramBot.BanChatMember(newUser.ChatId, newUser.Id, DateTime.Now.AddDays(1)));
await InvokeSafely(() => _telegramBot.DeleteMessage(newUser.ChatId, newUser.InviteMessageId));
await InvokeSafely(() => _telegramBot.DeleteMessage(newUser.ChatId, newUser.JoinMessageId));
_usersStore.Remove(newUser);

_logger.LogInformation(
Expand Down
16 changes: 8 additions & 8 deletions CaptchaBot/CaptchaBot.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<UserSecretsId>3275cd38-d732-473c-99a2-63aa6423a49f</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<Nullable>enable</Nullable>
Expand All @@ -10,14 +10,14 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Telegram.Bot" Version="19.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Telegram.Bot" Version="22.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.3" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>

Expand Down
4 changes: 2 additions & 2 deletions CaptchaBot/Controllers/UpdateController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ public async Task<IActionResult> Post([FromBody]Update update)
{
try
{
if (update?.Message?.Type == MessageType.ChatMembersAdded)
if (update?.Message?.Type == MessageType.NewChatMembers)
{
await _welcomeService.ProcessNewChatMember(update.Message);
}

if (update?.Type == UpdateType.CallbackQuery)
{
await _welcomeService.ProcessCallback(update.CallbackQuery!);
await _telegramBot.AnswerCallbackQueryAsync(update.CallbackQuery!.Id);
await _telegramBot.AnswerCallbackQuery(update.CallbackQuery!.Id);
}
}
catch (Exception e)
Expand Down
4 changes: 2 additions & 2 deletions CaptchaBot/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY ["CaptchaBot/CaptchaBot.csproj", "CaptchaBot/"]
RUN dotnet restore "CaptchaBot/CaptchaBot.csproj"
Expand Down
52 changes: 25 additions & 27 deletions CaptchaBot/Services/WelcomeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace CaptchaBot.Services;
public class WelcomeService : IWelcomeService
{
private const int ButtonsCount = 8;
private static readonly Random Random = new Random();
private static readonly Random Random = new();

private readonly AppSettings _settings;
private readonly IUsersStore _usersStore;
Expand Down Expand Up @@ -48,7 +48,7 @@ public async Task ProcessCallback(CallbackQuery query)

if (unauthorizedUserAnswer != unauthorizedUser.CorrectAnswer)
{
await _telegramBot.BanChatMemberAsync(
await _telegramBot.BanChatMember(
chatId,
query.From.Id,
DateTime.Now.AddDays(1));
Expand All @@ -66,28 +66,26 @@ await _telegramBot.BanChatMemberAsync(
{
var preBanPermissions = GetPreBanPermissions(unauthorizedUser.ChatMember);

var defaultPermissions = (await _telegramBot.GetChatAsync(chatId)).Permissions;

var postBanPermissions = new ChatPermissions
{
CanAddWebPagePreviews = preBanPermissions.CanAddWebPagePreviews ?? defaultPermissions?.CanAddWebPagePreviews ?? true,
CanChangeInfo = preBanPermissions.CanChangeInfo ?? defaultPermissions?.CanChangeInfo ?? true,
CanInviteUsers = preBanPermissions.CanInviteUsers ?? defaultPermissions?.CanInviteUsers ?? true,
CanPinMessages = preBanPermissions.CanPinMessages ?? defaultPermissions?.CanPinMessages ?? true,
CanSendMessages = preBanPermissions.CanSendMessages ?? defaultPermissions?.CanSendMessages ?? true,
CanSendOtherMessages = preBanPermissions.CanSendOtherMessages ?? defaultPermissions?.CanSendOtherMessages ?? true,
CanSendPolls = preBanPermissions.CanSendPolls ?? defaultPermissions?.CanSendPolls ?? true,
CanManageTopics = preBanPermissions.CanManageTopics ?? defaultPermissions?.CanManageTopics ?? true,
CanSendAudios = preBanPermissions.CanSendAudios ?? defaultPermissions?.CanSendAudios ?? true,
CanSendDocuments = preBanPermissions.CanSendDocuments ?? defaultPermissions?.CanSendDocuments ?? true,
CanSendPhotos = preBanPermissions.CanSendPhotos ?? defaultPermissions?.CanSendPhotos ?? true,
CanSendVideos = preBanPermissions.CanSendVideos ?? defaultPermissions?.CanSendVideos ?? true,
CanSendVideoNotes = preBanPermissions.CanSendVideoNotes ?? defaultPermissions?.CanSendVideoNotes ?? true,
CanSendVoiceNotes = preBanPermissions.CanSendVoiceNotes ?? defaultPermissions?.CanSendVoiceNotes ?? true,
CanAddWebPagePreviews = preBanPermissions.CanAddWebPagePreviews,
CanChangeInfo = preBanPermissions.CanChangeInfo,
CanInviteUsers = preBanPermissions.CanInviteUsers,
CanPinMessages = preBanPermissions.CanPinMessages,
CanSendMessages = preBanPermissions.CanSendMessages,
CanSendOtherMessages = preBanPermissions.CanSendOtherMessages,
CanSendPolls = preBanPermissions.CanSendPolls,
CanManageTopics = preBanPermissions.CanManageTopics,
CanSendAudios = preBanPermissions.CanSendAudios,
CanSendDocuments = preBanPermissions.CanSendDocuments,
CanSendPhotos = preBanPermissions.CanSendPhotos,
CanSendVideos = preBanPermissions.CanSendVideos,
CanSendVideoNotes = preBanPermissions.CanSendVideoNotes,
CanSendVoiceNotes = preBanPermissions.CanSendVoiceNotes

};

await _telegramBot.RestrictChatMemberAsync(
await _telegramBot.RestrictChatMember(
chatId,
query.From.Id,
postBanPermissions);
Expand All @@ -103,13 +101,13 @@ await _telegramBot.RestrictChatMemberAsync(
}

await InvokeSafely(async () =>
await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.InviteMessageId));
await _telegramBot.DeleteMessage(unauthorizedUser.ChatId, unauthorizedUser.InviteMessageId));

if (_settings.DeleteJoinMessages == JoinMessageDeletePolicy.All
|| _settings.DeleteJoinMessages == JoinMessageDeletePolicy.Unsuccessful && !authorizationSuccess)
{
await InvokeSafely(async () =>
await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.JoinMessageId));
await _telegramBot.DeleteMessage(unauthorizedUser.ChatId, unauthorizedUser.JoinMessageId));
}

_usersStore.Remove(unauthorizedUser);
Expand Down Expand Up @@ -184,21 +182,21 @@ public async Task ProcessNewChatMember(Message message)
{
_logger.LogWarning(
"Message about {NewChatMembers} received {Freshness} ago and ignored",
GetPrettyNames(message.NewChatMembers ?? Array.Empty<User>()),
GetPrettyNames(message.NewChatMembers ?? []),
freshness);
return;
}

foreach (var unauthorizedUser in message.NewChatMembers ?? Array.Empty<User>())
foreach (var unauthorizedUser in message.NewChatMembers ?? [])
{
var answer = GetRandomNumber();

var chatUser = await _telegramBot.GetChatMemberAsync(message.Chat.Id, unauthorizedUser.Id);
var chatUser = await _telegramBot.GetChatMember(message.Chat.Id, unauthorizedUser.Id);

if (chatUser == null || chatUser.Status == ChatMemberStatus.Left)
return;

await _telegramBot.RestrictChatMemberAsync(
await _telegramBot.RestrictChatMember(
message.Chat.Id,
unauthorizedUser.Id,
new ChatPermissions
Expand All @@ -224,10 +222,10 @@ await _telegramBot.RestrictChatMemberAsync(
var prettyUserName = GetPrettyName(unauthorizedUser);

var sentMessage = await _telegramBot
.SendTextMessageAsync(
.SendMessage(
message.Chat.Id,
_translationService.GetWelcomeMessage(prettyUserName, answer),
replyToMessageId: message.MessageId,
replyParameters: message.MessageId,
replyMarkup: new InlineKeyboardMarkup(GetKeyboardButtons()));

_usersStore.Add(unauthorizedUser, message, sentMessage.MessageId, prettyUserName, answer, chatUser);
Expand Down
9 changes: 4 additions & 5 deletions CaptchaBot/StartUpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ public static IApplicationBuilder UseTelegramBotWebhook(this IApplicationBuilder
async Task ResetWebHook()
{
logger.LogInformation("Removing webhook");
await services.GetRequiredService<ITelegramBotClient>().DeleteWebhookAsync();
await services.GetRequiredService<ITelegramBotClient>().DeleteWebhook();

logger.LogInformation($"Setting webhook to {address}");
await services.GetRequiredService<ITelegramBotClient>()
.SetWebhookAsync(address, maxConnections: 5);
await services.GetRequiredService<ITelegramBotClient>().SetWebhook(address, maxConnections: 5);
logger.LogInformation($"Webhook is set to {address}");

var webhookInfo = await services.GetRequiredService<ITelegramBotClient>().GetWebhookInfoAsync();
var webhookInfo = await services.GetRequiredService<ITelegramBotClient>().GetWebhookInfo();
logger.LogInformation($"Webhook info: {JsonConvert.SerializeObject(webhookInfo)}");
}

Expand All @@ -39,7 +38,7 @@ await services.GetRequiredService<ITelegramBotClient>()
{
var logger = services.GetRequiredService<ILogger<Startup>>();

services.GetRequiredService<ITelegramBotClient>().DeleteWebhookAsync().Wait();
services.GetRequiredService<ITelegramBotClient>().DeleteWebhook().Wait();
logger.LogInformation("Webhook removed");
});

Expand Down

0 comments on commit 4655221

Please sign in to comment.