├── ngrok-run.ps1 ├── CaptchaBot ├── Services │ ├── ChatUser.cs │ ├── IWelcomeService.cs │ ├── NewUser.cs │ ├── Translation │ │ ├── TranslationSettings.cs │ │ └── TranslationService.cs │ ├── IUsersStore.cs │ ├── UsersStore.cs │ └── WelcomeService.cs ├── Configuration │ └── appsettings.Development.json ├── Properties │ └── launchSettings.json ├── Dockerfile ├── AppSettings.cs ├── Program.cs ├── CaptchaBot.csproj ├── Controllers │ └── UpdateController.cs ├── StartUpExtensions.cs ├── Startup.cs ├── BanHostedService.cs └── SerilogExtensions.cs ├── docker-buils.ps1 ├── docker-compose.yml ├── .dockerignore ├── CaptchaBot.sln.DotSettings ├── README.md ├── LICENSE ├── .github └── workflows │ ├── test.yml │ └── deploy.yml ├── CaptchaBot.Tests ├── CaptchaBot.Tests.csproj └── WelcomeServiceTests.cs ├── CaptchaBot.sln ├── .gitattributes └── .gitignore /ngrok-run.ps1: -------------------------------------------------------------------------------- 1 | choco update ngrok -y 2 | 3 | ngrok http 4430 -------------------------------------------------------------------------------- /CaptchaBot/Services/ChatUser.cs: -------------------------------------------------------------------------------- 1 | namespace CaptchaBot.Services; 2 | 3 | public record struct ChatUser(long ChatId, long UserId); 4 | -------------------------------------------------------------------------------- /docker-buils.ps1: -------------------------------------------------------------------------------- 1 | docker build --tag=imoutochan/captchabot:v1.12.0 -t imoutochan/captchabot . 2 | docker push imoutochan/captchabot:latest 3 | docker push imoutochan/captchabot:v1.12.0 -------------------------------------------------------------------------------- /CaptchaBot/Configuration/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /CaptchaBot/Services/IWelcomeService.cs: -------------------------------------------------------------------------------- 1 | using Telegram.Bot.Types; 2 | 3 | namespace CaptchaBot.Services; 4 | 5 | public interface IWelcomeService 6 | { 7 | Task ProcessCallback(CallbackQuery query); 8 | 9 | Task ProcessNewChatMember(Message message); 10 | } -------------------------------------------------------------------------------- /CaptchaBot/Services/NewUser.cs: -------------------------------------------------------------------------------- 1 | using Telegram.Bot.Types; 2 | 3 | namespace CaptchaBot.Services; 4 | 5 | public record NewUser(long ChatId, 6 | long Id, 7 | DateTimeOffset JoinDateTime, 8 | int InviteMessageId, 9 | int JoinMessageId, 10 | string PrettyUserName, 11 | int CorrectAnswer, 12 | ChatMember ChatMember); -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | captchabot: 5 | image: imoutochan/captchabot:latest 6 | environment: 7 | - ASPNETCORE_ENVIRONMENT=Production 8 | restart: always 9 | volumes: 10 | - ./logs:/app/logs 11 | - ./Configuration:/app/Configuration 12 | ports: 13 | - "127.0.0.1:41460:4430" -------------------------------------------------------------------------------- /CaptchaBot/Services/Translation/TranslationSettings.cs: -------------------------------------------------------------------------------- 1 | namespace CaptchaBot.Services.Translation; 2 | 3 | public class TranslationSettings 4 | { 5 | public string NumberTexts { get; set; } = "ноль,один,два,три,четыре,пять,шесть,семь,восемь"; 6 | 7 | public string WelcomeMessageTemplate { get; set; } = "Привет, {0}, нажми кнопку {1}, чтобы тебя не забанили!"; 8 | } -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.classpath 2 | **/.dockerignore 3 | **/.env 4 | **/.git 5 | **/.gitignore 6 | **/.project 7 | **/.settings 8 | **/.toolstarget 9 | **/.vs 10 | **/.vscode 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /CaptchaBot.sln.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | True 3 | True -------------------------------------------------------------------------------- /CaptchaBot/Services/IUsersStore.cs: -------------------------------------------------------------------------------- 1 | using Telegram.Bot.Types; 2 | 3 | namespace CaptchaBot.Services; 4 | 5 | public interface IUsersStore 6 | { 7 | void Add( 8 | User user, 9 | Message message, 10 | int sentMessageId, 11 | string prettyUserName, 12 | int answer, 13 | ChatMember chatMember); 14 | 15 | IReadOnlyCollection GetAll(); 16 | 17 | NewUser? Get(long chatId, long userId); 18 | 19 | void Remove(NewUser user); 20 | } 21 | -------------------------------------------------------------------------------- /CaptchaBot/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "CaptchaBot": { 4 | "commandName": "Project", 5 | "launchBrowser": false, 6 | "environmentVariables": { 7 | "ASPNETCORE_ENVIRONMENT": "Development" 8 | }, 9 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 10 | }, 11 | "Docker": { 12 | "commandName": "Docker", 13 | "launchBrowser": true, 14 | "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}", 15 | "publishAllPorts": true, 16 | "useSSL": true 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /CaptchaBot/Dockerfile: -------------------------------------------------------------------------------- 1 | #See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. 2 | 3 | FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base 4 | WORKDIR /app 5 | EXPOSE 80 6 | EXPOSE 443 7 | 8 | FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build 9 | WORKDIR /src 10 | COPY ["CaptchaBot/CaptchaBot.csproj", "CaptchaBot/"] 11 | RUN dotnet restore "CaptchaBot/CaptchaBot.csproj" 12 | COPY . . 13 | WORKDIR "/src/CaptchaBot" 14 | RUN dotnet build "CaptchaBot.csproj" -c Release -o /app/build 15 | 16 | FROM build AS publish 17 | RUN dotnet publish "CaptchaBot.csproj" -c Release -o /app/publish 18 | 19 | FROM base AS final 20 | WORKDIR /app 21 | COPY --from=publish /app/publish . 22 | ENTRYPOINT ["dotnet", "CaptchaBot.dll"] 23 | -------------------------------------------------------------------------------- /CaptchaBot/AppSettings.cs: -------------------------------------------------------------------------------- 1 | namespace CaptchaBot; 2 | 3 | public enum JoinMessageDeletePolicy 4 | { 5 | All, 6 | Unsuccessful, 7 | None 8 | } 9 | 10 | public class AppSettings 11 | { 12 | public string BotToken { get; set; } = default!; 13 | public string WebHookAddress { get; set; } = default!; 14 | 15 | /// If this time has been passed since the user enter event, the event won't be processed. 16 | /// 17 | /// Useful for cases when the bot goes offline for a significant amount of time, and receives outdated events 18 | /// after getting back online. 19 | /// 20 | public TimeSpan ProcessEventTimeout { get; set; } = TimeSpan.FromMinutes(1.0); 21 | 22 | public JoinMessageDeletePolicy DeleteJoinMessages { get; set; } = JoinMessageDeletePolicy.All; 23 | } 24 | -------------------------------------------------------------------------------- /CaptchaBot/Program.cs: -------------------------------------------------------------------------------- 1 | namespace CaptchaBot; 2 | 3 | public class Program 4 | { 5 | public static void Main(string[] args) 6 | { 7 | CreateHostBuilder(args).Build().Run(); 8 | } 9 | 10 | public static IHostBuilder CreateHostBuilder(string[] args) => 11 | Host.CreateDefaultBuilder(args) 12 | .ConfigureAppConfiguration( 13 | (_, config) 14 | => config.AddJsonFile("Configuration/appsettings.json", optional: false, reloadOnChange: true)) 15 | .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()) 16 | .ConfigureServices(services => services.AddHostedService()) 17 | .ConfigureSerilog( 18 | (logger, _) 19 | => logger 20 | .WithoutDefaultLoggers() 21 | .WithConsole() 22 | .WithAllRollingFile() 23 | .WithInformationRollingFile()); 24 | } -------------------------------------------------------------------------------- /CaptchaBot/Services/Translation/TranslationService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Options; 2 | 3 | namespace CaptchaBot.Services.Translation; 4 | 5 | public interface ITranslationService 6 | { 7 | string GetWelcomeMessage(string prettyUserName, in int answer); 8 | } 9 | 10 | public class TranslationService : ITranslationService 11 | { 12 | public TranslationService(IOptions options) 13 | { 14 | var settings = options.Value; 15 | 16 | NumberTexts = settings.NumberTexts.Split(','); 17 | WelcomeMessageTemplate = settings.WelcomeMessageTemplate; 18 | } 19 | 20 | private string[] NumberTexts { get; } 21 | 22 | private string WelcomeMessageTemplate { get; } 23 | 24 | private string GetRequestedNumberText(in int answer) => NumberTexts[answer]; 25 | 26 | public string GetWelcomeMessage(string prettyUserName, in int answer) 27 | => string.Format(WelcomeMessageTemplate, prettyUserName, GetRequestedNumberText(answer)); 28 | } 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | GreenCaptchaBot 2 | =============== 3 | 4 | This is a bot that will ask the users coming to a Telegram chat to press a random numbered button. 5 | 6 | Configuration 7 | ------------- 8 | 9 | ```json 10 | { 11 | "Configuration": { 12 | "BotToken": "0000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 13 | "WebHookAddress": "https://yourserver.example.com/api/captchaupdate", 14 | "DeleteJoinMessages": "All" 15 | }, 16 | "Translation": { 17 | "NumberTexts": "zero,one,two,three,four,five,six,seven,eight", 18 | "WelcomeMessageTemplate": "Hi, {0}, press the button {1}, to avoid getting banned!" 19 | } 20 | } 21 | ``` 22 | 23 | `DeleteJoinMessages`: 24 | - `All`: will delete join messages for all users (default) 25 | - `None`: will not delete join messages at all 26 | - `Unsuccessful`: will only delete join messages after unsuccessful captcha solving (i.e. only the messages from the banned users will be deleted) 27 | 28 | `Translation`: 29 | - `NumberTexts` - localized text of numbers 30 | - `WelcomeMessageTemplate` - template of the message that is sent to new users 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 ImoutoChan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | schedule: 10 | - cron: '0 0 * * 6' 11 | 12 | jobs: 13 | main: 14 | runs-on: ${{ matrix.environment }} 15 | strategy: 16 | matrix: 17 | environment: 18 | - macos-12 19 | - ubuntu-20.04 20 | - windows-2019 21 | env: 22 | DOTNET_NOLOGO: 1 23 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 24 | NUGET_PACKAGES: ${{ github.workspace }}/.github/nuget-packages 25 | steps: 26 | - uses: actions/checkout@v2 27 | - name: Setup .NET SDK 28 | uses: actions/setup-dotnet@v1 29 | with: 30 | dotnet-version: 8.0.x 31 | include-prerelease: true 32 | - name: NuGet Cache 33 | uses: actions/cache@v2 34 | with: 35 | path: ${{ env.NUGET_PACKAGES }} 36 | key: ${{ runner.os }}.nuget.${{ hashFiles('**/*.csproj') }} 37 | - name: Build 38 | run: dotnet build --configuration Release 39 | - name: Test 40 | run: dotnet test --configuration Release 41 | -------------------------------------------------------------------------------- /CaptchaBot/CaptchaBot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | 3275cd38-d732-473c-99a2-63aa6423a49f 6 | Linux 7 | enable 8 | true 9 | true 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /CaptchaBot/Services/UsersStore.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using Telegram.Bot.Types; 3 | 4 | namespace CaptchaBot.Services; 5 | 6 | public class UsersStore : IUsersStore 7 | { 8 | private readonly ConcurrentDictionary _users = new(); 9 | 10 | public void Add( 11 | User user, 12 | Message message, 13 | int sentMessageId, 14 | string prettyUserName, 15 | int answer, 16 | ChatMember chatMember) 17 | { 18 | var key = new ChatUser(message.Chat.Id, user.Id); 19 | var newValue = new NewUser( 20 | message.Chat.Id, 21 | user.Id, 22 | DateTimeOffset.Now, 23 | sentMessageId, 24 | message.MessageId, 25 | prettyUserName, 26 | answer, 27 | chatMember); 28 | 29 | _users.AddOrUpdate(key, newValue, (_, _) => newValue); 30 | } 31 | 32 | public IReadOnlyCollection GetAll() => _users.Values.ToArray(); 33 | 34 | public NewUser? Get(long chatId, long userId) 35 | { 36 | if (_users.TryGetValue(new ChatUser(chatId, userId), out var newUser)) 37 | return newUser; 38 | 39 | return null; 40 | } 41 | 42 | public void Remove(NewUser user) 43 | { 44 | _users.TryRemove(new ChatUser(user.ChatId, user.Id), out _); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /CaptchaBot.Tests/CaptchaBot.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | true 7 | true 8 | 9 | false 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | all 23 | runtime; build; native; contentfiles; analyzers; buildtransitive 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /CaptchaBot/Controllers/UpdateController.cs: -------------------------------------------------------------------------------- 1 | using CaptchaBot.Services; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Telegram.Bot; 4 | using Telegram.Bot.Types; 5 | using Telegram.Bot.Types.Enums; 6 | 7 | namespace CaptchaBot.Controllers; 8 | 9 | public class UpdateController : Controller 10 | { 11 | private readonly ITelegramBotClient _telegramBot; 12 | private readonly ILogger _logger; 13 | private readonly IWelcomeService _welcomeService; 14 | 15 | public UpdateController( 16 | ITelegramBotClient telegramBot, 17 | ILogger logger, 18 | IWelcomeService welcomeService) 19 | { 20 | _telegramBot = telegramBot; 21 | _logger = logger; 22 | _welcomeService = welcomeService; 23 | } 24 | 25 | // POST api/update 26 | [HttpPost("api/{url}")] 27 | public async Task Post([FromBody] Update update) 28 | { 29 | try 30 | { 31 | if (update?.Message?.Type == MessageType.NewChatMembers) 32 | { 33 | await _welcomeService.ProcessNewChatMember(update.Message); 34 | } 35 | 36 | if (update?.Type == UpdateType.CallbackQuery) 37 | { 38 | await _welcomeService.ProcessCallback(update.CallbackQuery!); 39 | await _telegramBot.AnswerCallbackQuery(update.CallbackQuery!.Id); 40 | } 41 | } 42 | catch (Exception e) 43 | { 44 | _logger.LogError(e, "Проблемы"); 45 | } 46 | 47 | return Ok(); 48 | } 49 | 50 | [HttpGet("api/{url}")] 51 | public IActionResult Get(string url) 52 | { 53 | return Ok(url + " Ok!"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /CaptchaBot/StartUpExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using Telegram.Bot; 3 | 4 | namespace CaptchaBot; 5 | 6 | public static class StartupExtensions 7 | { 8 | public static IApplicationBuilder UseTelegramBotWebhook(this IApplicationBuilder applicationBuilder) 9 | { 10 | var services = applicationBuilder.ApplicationServices; 11 | 12 | var lifetime = services.GetRequiredService(); 13 | 14 | lifetime.ApplicationStarted.Register( 15 | () => 16 | { 17 | var logger = services.GetRequiredService>(); 18 | var address = services.GetRequiredService().WebHookAddress; 19 | 20 | async Task ResetWebHook() 21 | { 22 | logger.LogInformation("Removing webhook"); 23 | await services.GetRequiredService().DeleteWebhook(); 24 | 25 | logger.LogInformation($"Setting webhook to {address}"); 26 | await services.GetRequiredService().SetWebhook(address, maxConnections: 5); 27 | logger.LogInformation($"Webhook is set to {address}"); 28 | 29 | var webhookInfo = await services.GetRequiredService().GetWebhookInfo(); 30 | logger.LogInformation($"Webhook info: {JsonSerializer.Serialize(webhookInfo)}"); 31 | } 32 | 33 | _ = ResetWebHook(); 34 | }); 35 | 36 | lifetime.ApplicationStopping.Register( 37 | () => 38 | { 39 | var logger = services.GetRequiredService>(); 40 | 41 | services.GetRequiredService().DeleteWebhook().Wait(); 42 | logger.LogInformation("Webhook removed"); 43 | }); 44 | 45 | return applicationBuilder; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /CaptchaBot/Startup.cs: -------------------------------------------------------------------------------- 1 | using CaptchaBot.Services; 2 | using CaptchaBot.Services.Translation; 3 | using Microsoft.Extensions.Options; 4 | using Telegram.Bot; 5 | 6 | namespace CaptchaBot; 7 | 8 | public class Startup 9 | { 10 | public Startup(IConfiguration configuration) 11 | { 12 | Configuration = configuration; 13 | } 14 | 15 | public IConfiguration Configuration { get; } 16 | 17 | // This method gets called by the runtime. Use this method to add services to the container. 18 | public void ConfigureServices(IServiceCollection services) 19 | { 20 | services.AddControllers(); 21 | services.ConfigureTelegramBotMvc(); 22 | 23 | services.AddOptions(); 24 | services.Configure(Configuration.GetSection("Configuration")); 25 | services.Configure(Configuration.GetSection("Translation")); 26 | 27 | services.AddTransient(ser => ser.GetRequiredService>().Value); 28 | 29 | services.AddSingleton( 30 | x => 31 | { 32 | var settings = x.GetRequiredService(); 33 | return new TelegramBotClient(settings.BotToken); 34 | }); 35 | 36 | services.AddSingleton(); 37 | services.AddTransient(); 38 | services.AddTransient(); 39 | } 40 | 41 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 42 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 43 | { 44 | app.UseTelegramBotWebhook(); 45 | 46 | if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); 47 | 48 | app.UseRouting(); 49 | 50 | app.UseAuthorization(); 51 | 52 | app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /CaptchaBot/BanHostedService.cs: -------------------------------------------------------------------------------- 1 | using CaptchaBot.Services; 2 | using Telegram.Bot; 3 | 4 | namespace CaptchaBot; 5 | 6 | public class BanHostedService : IHostedService 7 | { 8 | private readonly ILogger _logger; 9 | private readonly ITelegramBotClient _telegramBot; 10 | private readonly IUsersStore _usersStore; 11 | private Timer? _timer; 12 | 13 | public BanHostedService( 14 | IUsersStore usersStore, 15 | ILogger logger, 16 | ITelegramBotClient telegramBot) 17 | { 18 | _usersStore = usersStore; 19 | _logger = logger; 20 | _telegramBot = telegramBot; 21 | } 22 | 23 | public Task StartAsync(CancellationToken cancellationToken) 24 | { 25 | _timer = new Timer(__ => _ = InvokeSafely(BanSlowUsers), null, 0, 10000); 26 | return Task.CompletedTask; 27 | } 28 | 29 | public Task StopAsync(CancellationToken cancellationToken) 30 | { 31 | _timer?.Change(Timeout.Infinite, 0); 32 | return Task.CompletedTask; 33 | } 34 | 35 | private async Task BanSlowUsers() 36 | { 37 | var users = _usersStore.GetAll(); 38 | 39 | var usersToBan = users.Where( 40 | x => 41 | { 42 | var diff = DateTimeOffset.Now - x.JoinDateTime; 43 | return diff > TimeSpan.FromSeconds(60); 44 | }) 45 | .ToArray(); 46 | 47 | foreach (var newUser in usersToBan) 48 | { 49 | await InvokeSafely(() => _telegramBot.BanChatMember(newUser.ChatId, newUser.Id, DateTime.Now.AddDays(1))); 50 | await InvokeSafely(() => _telegramBot.DeleteMessage(newUser.ChatId, newUser.InviteMessageId)); 51 | await InvokeSafely(() => _telegramBot.DeleteMessage(newUser.ChatId, newUser.JoinMessageId)); 52 | _usersStore.Remove(newUser); 53 | 54 | _logger.LogInformation( 55 | "User {UserId} with name {UserName} was banned after one minute silence", 56 | newUser.Id, 57 | newUser.PrettyUserName); 58 | } 59 | } 60 | 61 | private async Task InvokeSafely(Func func) 62 | { 63 | try 64 | { 65 | await func(); 66 | } 67 | catch (Exception e) 68 | { 69 | _logger.LogWarning(e, "An error occured"); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | workflow_dispatch: 8 | 9 | jobs: 10 | deploy: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Install GitVersion 15 | uses: GitTools/actions/gitversion/setup@a41619580c25efb59dfc062e92990914141abcad # v0.10.2 16 | with: 17 | versionSpec: '5.5.0' 18 | 19 | - uses: actions/setup-dotnet@3447fd6a9f9e57506b15f895c5b76d3b197dc7c2 # v3.2.0 20 | with: 21 | dotnet-version: '3.1.x' 22 | 23 | - name: Set up Docker Buildx 24 | id: buildx 25 | uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0 26 | 27 | - name: Checkout 28 | uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 29 | with: 30 | fetch-depth: 0 31 | 32 | - name: Login to Docker Hub 33 | uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0 34 | with: 35 | username: ${{ secrets.DOCKER_HUB_USERNAME }} 36 | password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} 37 | 38 | - name: Run GitVersion 39 | id: gitversion 40 | uses: GitTools/actions/gitversion/execute@a41619580c25efb59dfc062e92990914141abcad # v0.10.2 41 | 42 | - name: Echo version 43 | run: echo ${{ steps.gitversion.outputs.majorMinorPatch }} 44 | 45 | - name: Build image and push 46 | uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0 47 | with: 48 | context: . 49 | file: ./CaptchaBot/Dockerfile 50 | builder: ${{ steps.buildx.outputs.name }} 51 | push: true 52 | tags: | 53 | ${{ secrets.DOCKER_HUB_USERNAME }}/captchabot:latest 54 | ${{ secrets.DOCKER_HUB_USERNAME }}/captchabot:${{ steps.gitversion.outputs.majorMinorPatch }} 55 | cache-from: type=registry,ref=${{ secrets.DOCKER_HUB_USERNAME }}/captchabot:buildcache 56 | cache-to: type=registry,ref=${{ secrets.DOCKER_HUB_USERNAME }}/captchabot:buildcache,mode=max 57 | 58 | - name: Deploy 59 | uses: appleboy/ssh-action@55dabf81b49d4120609345970c91507e2d734799 # v1.0.0 60 | with: 61 | host: ${{ secrets.HOST }} 62 | username: ${{ secrets.USERNAME }} 63 | key: ${{ secrets.KEY }} 64 | script: ./update.captchabot.sh 65 | -------------------------------------------------------------------------------- /CaptchaBot.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29721.120 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptchaBot", "CaptchaBot\CaptchaBot.csproj", "{780187AC-5B4B-439F-8D1A-EB2160187C17}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CaptchaBot.Tests", "CaptchaBot.Tests\CaptchaBot.Tests.csproj", "{756DC120-FFDD-4DA3-AB13-6447B0D3A519}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{4B7A8DC8-DB8D-4139-AB22-21DBDA609102}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{023EC92B-AD17-4E5B-90E4-C900DCEE0E8B}" 13 | ProjectSection(SolutionItems) = preProject 14 | .github\workflows\deploy.yml = .github\workflows\deploy.yml 15 | .github\workflows\test.yml = .github\workflows\test.yml 16 | EndProjectSection 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EF51B8EE-C330-47EA-AE4E-5AF80CFA4051}" 19 | ProjectSection(SolutionItems) = preProject 20 | README.md = README.md 21 | EndProjectSection 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Release|Any CPU = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 29 | {780187AC-5B4B-439F-8D1A-EB2160187C17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {780187AC-5B4B-439F-8D1A-EB2160187C17}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {780187AC-5B4B-439F-8D1A-EB2160187C17}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {780187AC-5B4B-439F-8D1A-EB2160187C17}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {756DC120-FFDD-4DA3-AB13-6447B0D3A519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {756DC120-FFDD-4DA3-AB13-6447B0D3A519}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {756DC120-FFDD-4DA3-AB13-6447B0D3A519}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {756DC120-FFDD-4DA3-AB13-6447B0D3A519}.Release|Any CPU.Build.0 = Release|Any CPU 37 | EndGlobalSection 38 | GlobalSection(SolutionProperties) = preSolution 39 | HideSolutionNode = FALSE 40 | EndGlobalSection 41 | GlobalSection(ExtensibilityGlobals) = postSolution 42 | SolutionGuid = {63003ED9-7A1A-4663-9049-856679A939CF} 43 | EndGlobalSection 44 | GlobalSection(NestedProjects) = preSolution 45 | {023EC92B-AD17-4E5B-90E4-C900DCEE0E8B} = {4B7A8DC8-DB8D-4139-AB22-21DBDA609102} 46 | EndGlobalSection 47 | EndGlobal 48 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /CaptchaBot/SerilogExtensions.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | using Serilog; 3 | using Serilog.Core; 4 | using Serilog.Events; 5 | 6 | namespace CaptchaBot; 7 | 8 | public static class SerilogExtensions 9 | { 10 | private const string FileTemplate 11 | = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"; 12 | private const string ConsoleTemplate 13 | = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"; 14 | 15 | 16 | public static LoggerConfiguration WithoutDefaultLoggers(this LoggerConfiguration configuration) 17 | => configuration.MinimumLevel.Verbose() 18 | .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) 19 | .MinimumLevel.Override("System", LogEventLevel.Warning); 20 | 21 | public static LoggerConfiguration WithConsole(this LoggerConfiguration configuration) 22 | => configuration.WriteTo.Console( 23 | outputTemplate: ConsoleTemplate, 24 | restrictedToMinimumLevel: LogEventLevel.Verbose); 25 | 26 | public static LoggerConfiguration WithAllRollingFile( 27 | this LoggerConfiguration configuration, 28 | string pathFormat = "logs/{Date}-all.log") 29 | => configuration.WriteTo.RollingFile( 30 | pathFormat: pathFormat, 31 | outputTemplate: FileTemplate, 32 | restrictedToMinimumLevel: LogEventLevel.Verbose); 33 | 34 | public static LoggerConfiguration WithInformationRollingFile( 35 | this LoggerConfiguration configuration, 36 | string pathFormat = "logs/{Date}-information.log") 37 | => configuration.WriteTo.RollingFile( 38 | pathFormat: pathFormat, 39 | outputTemplate: FileTemplate, 40 | restrictedToMinimumLevel: LogEventLevel.Information); 41 | 42 | public static LoggerConfiguration PatchWithConfiguration( 43 | this LoggerConfiguration configuration, 44 | IConfiguration appConfiguration) 45 | => configuration.ReadFrom.Configuration(appConfiguration); 46 | } 47 | 48 | public static class HostBuilderExtensions 49 | { 50 | public static IHostBuilder ConfigureSerilog( 51 | this IHostBuilder hostBuilder, 52 | Action? configureLogger = null) 53 | { 54 | hostBuilder.ConfigureLogging((context, builder) => 55 | { 56 | builder.ClearProviders(); 57 | builder.AddSerilog( 58 | dispose: true, 59 | logger: GetSerilogLogger(context.Configuration, configureLogger)); 60 | }); 61 | 62 | return hostBuilder; 63 | } 64 | 65 | private static Logger GetSerilogLogger( 66 | IConfiguration configuration, 67 | Action? configureLogger) 68 | { 69 | var loggerBuilder = new LoggerConfiguration() 70 | .Enrich.FromLogContext(); 71 | 72 | configureLogger?.Invoke(loggerBuilder, configuration); 73 | 74 | return loggerBuilder.CreateLogger(); 75 | } 76 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | /CaptchaBot/appsettings.json 342 | /CaptchaBot/Configuration/appsettings.json 343 | -------------------------------------------------------------------------------- /CaptchaBot.Tests/WelcomeServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using CaptchaBot.Services; 3 | using CaptchaBot.Services.Translation; 4 | using FakeItEasy; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.Options; 7 | using Telegram.Bot; 8 | using Telegram.Bot.Requests; 9 | using Telegram.Bot.Requests.Abstractions; 10 | using Telegram.Bot.Types; 11 | using Xunit; 12 | using Xunit.Abstractions; 13 | 14 | namespace CaptchaBot.Tests; 15 | 16 | public class WelcomeServiceTests 17 | { 18 | private readonly UsersStore _usersStore = new(); 19 | private readonly ITelegramBotClient _botMock; 20 | private readonly ILogger _logger; 21 | private readonly List _deletedMessages = new(); 22 | private readonly TranslationService _translationService; 23 | 24 | public WelcomeServiceTests(ITestOutputHelper outputHelper) 25 | { 26 | _logger = outputHelper.BuildLoggerFor(); 27 | _translationService = new(Options.Create(new())); 28 | 29 | _botMock = A.Fake(); 30 | A.CallTo(() => _botMock.SendRequest(A._, A._)) 31 | .Returns(new Message()); 32 | 33 | A.CallTo(() => _botMock.SendRequest(A._, A._)) 34 | .Returns(new ChatMemberMember()); 35 | 36 | A.CallTo(() => _botMock.SendRequest(A._, A._)) 37 | .Returns(new ChatFullInfo()); 38 | 39 | A.CallTo(() => _botMock.SendRequest(A._, A._)) 40 | .Invokes((IRequest request, CancellationToken _) => _deletedMessages.Add((request as DeleteMessageRequest)!.MessageId)); 41 | } 42 | 43 | private static Task ProcessNewChatMember( 44 | WelcomeService service, 45 | long userId, 46 | DateTime enterTime, 47 | long fromId = 0L, 48 | int joinMessageId = 0) 49 | { 50 | var testUser = new User {Id = userId}; 51 | var message = new Message 52 | { 53 | Id = joinMessageId, 54 | Date = enterTime, 55 | Chat = new Chat(), 56 | From = new User {Id = fromId}, 57 | NewChatMembers = new[] 58 | { 59 | testUser 60 | } 61 | }; 62 | return service.ProcessNewChatMember(message); 63 | } 64 | 65 | private async Task ProcessAnswer(IWelcomeService service, bool successful) 66 | { 67 | var newUser = _usersStore.GetAll().Single(); 68 | var callback = new CallbackQuery 69 | { 70 | Message = new Message { Chat = new Chat() }, 71 | From = new User { Id = newUser.Id }, 72 | Data = successful ? newUser.CorrectAnswer.ToString(CultureInfo.InvariantCulture) : "10" 73 | }; 74 | await service.ProcessCallback(callback); 75 | } 76 | 77 | [Fact] 78 | public async Task BotShouldProcessEventWithinTimeout() 79 | { 80 | var config = new AppSettings {ProcessEventTimeout = TimeSpan.FromSeconds(5.0)}; 81 | var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService); 82 | 83 | const long testUserId = 123L; 84 | await ProcessNewChatMember(welcomeService, testUserId, DateTime.UtcNow); 85 | 86 | Assert.Collection(Fake.GetCalls(_botMock), 87 | getChatMember => 88 | { 89 | Assert.Equal(nameof(ITelegramBotClient.SendRequest), getChatMember.Method.Name); 90 | Assert.IsType(getChatMember.Arguments.First()); 91 | }, 92 | restrict => 93 | { 94 | Assert.Equal(nameof(ITelegramBotClient.SendRequest), restrict.Method.Name); 95 | Assert.IsType(restrict.Arguments.First()); 96 | }, 97 | sendMessage => 98 | { 99 | Assert.Equal(nameof(ITelegramBotClient.SendRequest), sendMessage.Method.Name); 100 | Assert.IsType(sendMessage.Arguments.First()); 101 | }); 102 | 103 | Assert.Equal(testUserId, _usersStore.GetAll().Single().Id); 104 | } 105 | 106 | [Fact] 107 | public async Task BotShouldNotProcessEventOutsideTimeout() 108 | { 109 | var config = new AppSettings {ProcessEventTimeout = TimeSpan.FromMinutes(5.0)}; 110 | var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService); 111 | 112 | const int testUserId = 345; 113 | await ProcessNewChatMember(welcomeService, testUserId, DateTime.UtcNow - TimeSpan.FromMinutes(6.0)); 114 | 115 | Assert.Empty(Fake.GetCalls(_botMock)); 116 | Assert.Empty(_usersStore.GetAll()); 117 | } 118 | 119 | [Fact] 120 | public async Task BotShouldRestrictTheEnteringUserAndNotTheMessageAuthor() 121 | { 122 | var config = new AppSettings(); 123 | var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService); 124 | 125 | const long enteringUserId = 123L; 126 | const long invitingUserId = 345L; 127 | 128 | await ProcessNewChatMember(welcomeService, enteringUserId, DateTime.UtcNow, invitingUserId); 129 | 130 | Assert.Collection(Fake.GetCalls(_botMock), 131 | _ => {}, 132 | restrict => 133 | { 134 | Assert.Equal(nameof(ITelegramBotClient.SendRequest), restrict.Method.Name); 135 | var restrictedUserId = (RestrictChatMemberRequest)restrict.Arguments[0]!; 136 | Assert.Equal(enteringUserId, restrictedUserId.UserId); 137 | }, 138 | _ => {}); 139 | } 140 | 141 | [Fact] 142 | public async Task BotShouldNotFailIfMessageCouldNotBeDeleted() 143 | { 144 | A.CallTo(() => _botMock.SendRequest(A._, A._)) 145 | .Throws(new Exception("This exception should not fail the message processing.")); 146 | 147 | var config = new AppSettings(); 148 | var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService); 149 | 150 | const long newUserId = 124L; 151 | 152 | await ProcessNewChatMember(welcomeService, newUserId, DateTime.UtcNow); 153 | await ProcessAnswer(welcomeService, true); 154 | 155 | Assert.Empty(_usersStore.GetAll()); 156 | } 157 | 158 | private async Task DoRemoveJoinTest( 159 | JoinMessageDeletePolicy policy, 160 | int joinMessageId, 161 | bool successful, 162 | bool deleted) 163 | { 164 | const long userId = 100L; 165 | 166 | var config = new AppSettings { DeleteJoinMessages = policy }; 167 | var welcomeService = new WelcomeService(config, _usersStore, _logger, _botMock, _translationService); 168 | 169 | await ProcessNewChatMember(welcomeService, userId, DateTime.UtcNow, joinMessageId: joinMessageId); 170 | await ProcessAnswer(welcomeService, successful); 171 | if (deleted) 172 | Assert.Contains(joinMessageId, _deletedMessages); 173 | else 174 | Assert.DoesNotContain(joinMessageId, _deletedMessages); 175 | } 176 | 177 | [Fact] 178 | public Task RemoveJoinMessagesAllMode1() => 179 | DoRemoveJoinTest(JoinMessageDeletePolicy.All, 123, successful: true, deleted: true); 180 | 181 | [Fact] 182 | public Task RemoveJoinMessagesAllMode2() => 183 | DoRemoveJoinTest(JoinMessageDeletePolicy.All, 124, successful: false, deleted: true); 184 | 185 | [Fact] 186 | public Task RemoveJoinMessagesNoneMode1() => 187 | DoRemoveJoinTest(JoinMessageDeletePolicy.None, 321, successful: true, deleted: false); 188 | 189 | [Fact] 190 | public Task RemoveJoinMessagesNoneMode2() => 191 | DoRemoveJoinTest(JoinMessageDeletePolicy.None, 421, successful: false, deleted: false); 192 | 193 | [Fact] 194 | public Task RemoveJoinMessagesUnsuccessfulMode1() => 195 | DoRemoveJoinTest(JoinMessageDeletePolicy.Unsuccessful, 42, successful: true, deleted: false); 196 | 197 | [Fact] 198 | public Task RemoveJoinMessagesUnsuccessfulMode2() => 199 | DoRemoveJoinTest(JoinMessageDeletePolicy.Unsuccessful, 43, successful: false, deleted: true); 200 | } 201 | -------------------------------------------------------------------------------- /CaptchaBot/Services/WelcomeService.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using CaptchaBot.Services.Translation; 3 | using Telegram.Bot; 4 | using Telegram.Bot.Types; 5 | using Telegram.Bot.Types.Enums; 6 | using Telegram.Bot.Types.ReplyMarkups; 7 | 8 | namespace CaptchaBot.Services; 9 | 10 | public class WelcomeService : IWelcomeService 11 | { 12 | private const int ButtonsCount = 8; 13 | private static readonly Random Random = new(); 14 | 15 | private readonly AppSettings _settings; 16 | private readonly IUsersStore _usersStore; 17 | private readonly ILogger _logger; 18 | private readonly ITelegramBotClient _telegramBot; 19 | private readonly ITranslationService _translationService; 20 | 21 | public WelcomeService( 22 | AppSettings settings, 23 | IUsersStore usersStore, 24 | ILogger logger, 25 | ITelegramBotClient telegramBot, 26 | ITranslationService translationService) 27 | { 28 | _settings = settings; 29 | _usersStore = usersStore; 30 | _logger = logger; 31 | _telegramBot = telegramBot; 32 | _translationService = translationService; 33 | } 34 | 35 | public async Task ProcessCallback(CallbackQuery query) 36 | { 37 | var chatId = query.Message!.Chat.Id; 38 | var unauthorizedUser = _usersStore.Get(chatId, query.From.Id); 39 | bool authorizationSuccess; 40 | 41 | if (unauthorizedUser == null) 42 | { 43 | _logger.LogInformation("User with id {UserId} not found", query.From.Id); 44 | return; 45 | } 46 | 47 | var unauthorizedUserAnswer = int.Parse(query.Data!); 48 | 49 | if (unauthorizedUserAnswer != unauthorizedUser.CorrectAnswer) 50 | { 51 | await _telegramBot.BanChatMember( 52 | chatId, 53 | query.From.Id, 54 | DateTime.Now.AddDays(1)); 55 | authorizationSuccess = false; 56 | 57 | _logger.LogInformation( 58 | "User {UserId} with name {UserName} was banned after incorrect answer {UserAnswer}, " + 59 | "while correct one is {CorrectAnswer}", 60 | unauthorizedUser.Id, 61 | unauthorizedUser.PrettyUserName, 62 | unauthorizedUserAnswer, 63 | unauthorizedUser.CorrectAnswer); 64 | } 65 | else 66 | { 67 | var preBanPermissions = GetPreBanPermissions(unauthorizedUser.ChatMember); 68 | 69 | var postBanPermissions = new ChatPermissions 70 | { 71 | CanAddWebPagePreviews = preBanPermissions.CanAddWebPagePreviews, 72 | CanChangeInfo = preBanPermissions.CanChangeInfo, 73 | CanInviteUsers = preBanPermissions.CanInviteUsers, 74 | CanPinMessages = preBanPermissions.CanPinMessages, 75 | CanSendMessages = preBanPermissions.CanSendMessages, 76 | CanSendOtherMessages = preBanPermissions.CanSendOtherMessages, 77 | CanSendPolls = preBanPermissions.CanSendPolls, 78 | CanManageTopics = preBanPermissions.CanManageTopics, 79 | CanSendAudios = preBanPermissions.CanSendAudios, 80 | CanSendDocuments = preBanPermissions.CanSendDocuments, 81 | CanSendPhotos = preBanPermissions.CanSendPhotos, 82 | CanSendVideos = preBanPermissions.CanSendVideos, 83 | CanSendVideoNotes = preBanPermissions.CanSendVideoNotes, 84 | CanSendVoiceNotes = preBanPermissions.CanSendVoiceNotes 85 | 86 | }; 87 | 88 | await _telegramBot.RestrictChatMember( 89 | chatId, 90 | query.From.Id, 91 | postBanPermissions); 92 | authorizationSuccess = true; 93 | 94 | _logger.LogInformation( 95 | "User {UserId} with name {UserName} was authorized with answer {UserAnswer}. " + 96 | "With post ban permissions {PostBanPermissions}", 97 | unauthorizedUser.Id, 98 | unauthorizedUser.PrettyUserName, 99 | unauthorizedUserAnswer, 100 | JsonSerializer.Serialize(postBanPermissions)); 101 | } 102 | 103 | await InvokeSafely(async () => 104 | await _telegramBot.DeleteMessage(unauthorizedUser.ChatId, unauthorizedUser.InviteMessageId)); 105 | 106 | if (_settings.DeleteJoinMessages == JoinMessageDeletePolicy.All 107 | || _settings.DeleteJoinMessages == JoinMessageDeletePolicy.Unsuccessful && !authorizationSuccess) 108 | { 109 | await InvokeSafely(async () => 110 | await _telegramBot.DeleteMessage(unauthorizedUser.ChatId, unauthorizedUser.JoinMessageId)); 111 | } 112 | 113 | _usersStore.Remove(unauthorizedUser); 114 | } 115 | 116 | private ChatPermissions GetPreBanPermissions(ChatMember chatMember) 117 | { 118 | return chatMember switch 119 | { 120 | ChatMemberAdministrator chatMemberAdministrator => new ChatPermissions 121 | { 122 | CanSendMessages = true, 123 | CanSendAudios = true, 124 | CanSendDocuments = true, 125 | CanSendPhotos = true, 126 | CanSendVideos = true, 127 | CanSendVideoNotes = true, 128 | CanSendVoiceNotes = true, 129 | CanSendPolls = true, 130 | CanSendOtherMessages = true, 131 | CanAddWebPagePreviews = true, 132 | CanManageTopics = chatMemberAdministrator.CanManageTopics, 133 | CanChangeInfo = chatMemberAdministrator.CanChangeInfo, 134 | CanInviteUsers = chatMemberAdministrator.CanInviteUsers, 135 | CanPinMessages = chatMemberAdministrator.CanPinMessages 136 | }, 137 | ChatMemberBanned _ => new ChatPermissions(), 138 | ChatMemberLeft _ => new ChatPermissions(), 139 | ChatMemberMember _ => new ChatPermissions(), 140 | ChatMemberOwner _ => new ChatPermissions 141 | { 142 | CanSendMessages = true, 143 | CanManageTopics = true, 144 | CanSendAudios = true, 145 | CanSendDocuments = true, 146 | CanSendPhotos = true, 147 | CanSendVideos = true, 148 | CanSendVideoNotes = true, 149 | CanSendVoiceNotes = true, 150 | CanSendPolls = true, 151 | CanSendOtherMessages = true, 152 | CanAddWebPagePreviews = true, 153 | CanChangeInfo = true, 154 | CanInviteUsers = true, 155 | CanPinMessages = true 156 | }, 157 | ChatMemberRestricted chatMemberRestricted => new ChatPermissions 158 | { 159 | CanSendMessages = chatMemberRestricted.CanSendMessages, 160 | CanManageTopics = chatMemberRestricted.CanManageTopics, 161 | CanSendAudios = chatMemberRestricted.CanSendAudios, 162 | CanSendDocuments = chatMemberRestricted.CanSendDocuments, 163 | CanSendPhotos = chatMemberRestricted.CanSendPhotos, 164 | CanSendVideos = chatMemberRestricted.CanSendVideos, 165 | CanSendVideoNotes = chatMemberRestricted.CanSendVideoNotes, 166 | CanSendVoiceNotes = chatMemberRestricted.CanSendVoiceNotes, 167 | CanSendPolls = chatMemberRestricted.CanSendPolls, 168 | CanSendOtherMessages = chatMemberRestricted.CanSendOtherMessages, 169 | CanAddWebPagePreviews = chatMemberRestricted.CanAddWebPagePreviews, 170 | CanChangeInfo = chatMemberRestricted.CanChangeInfo, 171 | CanInviteUsers = chatMemberRestricted.CanInviteUsers, 172 | CanPinMessages = chatMemberRestricted.CanPinMessages 173 | }, 174 | _ => new ChatPermissions() 175 | }; 176 | } 177 | 178 | public async Task ProcessNewChatMember(Message message) 179 | { 180 | var freshness = DateTime.UtcNow - message.Date.ToUniversalTime(); 181 | if (freshness > _settings.ProcessEventTimeout) 182 | { 183 | _logger.LogWarning( 184 | "Message about {NewChatMembers} received {Freshness} ago and ignored", 185 | GetPrettyNames(message.NewChatMembers ?? []), 186 | freshness); 187 | return; 188 | } 189 | 190 | foreach (var unauthorizedUser in message.NewChatMembers ?? []) 191 | { 192 | var answer = GetRandomNumber(); 193 | 194 | var chatUser = await _telegramBot.GetChatMember(message.Chat.Id, unauthorizedUser.Id); 195 | 196 | if (chatUser == null || chatUser.Status == ChatMemberStatus.Left) 197 | return; 198 | 199 | await _telegramBot.RestrictChatMember( 200 | message.Chat.Id, 201 | unauthorizedUser.Id, 202 | new ChatPermissions 203 | { 204 | CanAddWebPagePreviews = false, 205 | CanChangeInfo = false, 206 | CanInviteUsers = false, 207 | CanPinMessages = false, 208 | CanManageTopics = false, 209 | CanSendAudios = false, 210 | CanSendDocuments = false, 211 | CanSendPhotos = false, 212 | CanSendVideos = false, 213 | CanSendVideoNotes = false, 214 | CanSendVoiceNotes = false, 215 | CanSendMessages = false, 216 | CanSendOtherMessages = false, 217 | CanSendPolls = false 218 | }, 219 | true, 220 | DateTime.Now.AddDays(1)); 221 | 222 | var prettyUserName = GetPrettyName(unauthorizedUser); 223 | 224 | var sentMessage = await _telegramBot 225 | .SendMessage( 226 | message.Chat.Id, 227 | _translationService.GetWelcomeMessage(prettyUserName, answer), 228 | replyParameters: message.MessageId, 229 | replyMarkup: new InlineKeyboardMarkup(GetKeyboardButtons())); 230 | 231 | _usersStore.Add(unauthorizedUser, message, sentMessage.MessageId, prettyUserName, answer, chatUser); 232 | 233 | _logger.LogInformation( 234 | "The new user {UserId} with name {UserName} was detected and trialed. " + 235 | "He has one minute to answer", 236 | unauthorizedUser.Id, 237 | prettyUserName); 238 | } 239 | } 240 | 241 | private static string GetPrettyName(User messageNewChatMember) 242 | { 243 | var names = new List(3); 244 | 245 | if (!string.IsNullOrWhiteSpace(messageNewChatMember.FirstName)) 246 | names.Add(messageNewChatMember.FirstName); 247 | if (!string.IsNullOrWhiteSpace(messageNewChatMember.LastName)) 248 | names.Add(messageNewChatMember.LastName); 249 | if (!string.IsNullOrWhiteSpace(messageNewChatMember.Username)) 250 | names.Add("(@" + messageNewChatMember.Username + ")"); 251 | 252 | return string.Join(" ", names); 253 | } 254 | 255 | private static string GetPrettyNames(IEnumerable users) => string.Join(", ", users.Select(GetPrettyName)); 256 | 257 | private static int GetRandomNumber() => Random.Next(1, ButtonsCount + 1); 258 | 259 | private static IEnumerable GetKeyboardButtons() 260 | { 261 | for (int i = 1; i <= ButtonsCount; i++) 262 | { 263 | var label = i.ToString(); 264 | yield return InlineKeyboardButton.WithCallbackData(label, label); 265 | } 266 | } 267 | 268 | private async Task InvokeSafely(Func func) 269 | { 270 | try 271 | { 272 | await func(); 273 | } 274 | catch (Exception e) 275 | { 276 | _logger.LogWarning(e, "An error occured"); 277 | } 278 | } 279 | } 280 | --------------------------------------------------------------------------------