From 7266036ccfd664b3fd2a666864198185be036af7 Mon Sep 17 00:00:00 2001 From: Dmitriy yawaflua Andreev Date: Sun, 28 Jul 2024 21:47:13 +0300 Subject: [PATCH] Add project files. --- .dockerignore | 30 ++++++++++++ Controllers/ExampleController.cs | 11 +++++ Dockerfile | 24 +++++++++ Program.cs | 15 ++++++ Properties/launchSettings.json | 52 ++++++++++++++++++++ Startup.cs | 54 ++++++++++++++++++++ TG-Bot-Template.csproj | 19 ++++++++ TG-Bot-Template.sln | 25 ++++++++++ TelegramBotService.cs | 84 ++++++++++++++++++++++++++++++++ appsettings.Development.json | 8 +++ appsettings.json | 10 ++++ 11 files changed, 332 insertions(+) create mode 100644 .dockerignore create mode 100644 Controllers/ExampleController.cs create mode 100644 Dockerfile create mode 100644 Program.cs create mode 100644 Properties/launchSettings.json create mode 100644 Startup.cs create mode 100644 TG-Bot-Template.csproj create mode 100644 TG-Bot-Template.sln create mode 100644 TelegramBotService.cs create mode 100644 appsettings.Development.json create mode 100644 appsettings.json diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..fe1152b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,30 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md +!**/.gitignore +!.git/HEAD +!.git/config +!.git/packed-refs +!.git/refs/heads/** \ No newline at end of file diff --git a/Controllers/ExampleController.cs b/Controllers/ExampleController.cs new file mode 100644 index 0000000..781ff24 --- /dev/null +++ b/Controllers/ExampleController.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Mvc; + +namespace TG_Bot_Template.Controllers +{ + [ApiController] + [Route("[controller]")] + public class ExampleController : ControllerBase + { + + } +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c3e03cc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base +USER app +WORKDIR /app +EXPOSE 80 + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["TG-Bot-Template.csproj", "."] +RUN dotnet restore "./TG-Bot-Template.csproj" +COPY . . +WORKDIR "/src/." +RUN dotnet build "./TG-Bot-Template.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "./TG-Bot-Template.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "TG-Bot-Template.dll"] \ No newline at end of file diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..e676b43 --- /dev/null +++ b/Program.cs @@ -0,0 +1,15 @@ + +namespace TG_Bot_Template +{ + public class Program + { + public static void Main(string[] args) + { + new WebHostBuilder() + .UseKestrel(k => k.ListenAnyIP(80)) + .UseStartup() + .Build() + .Run(); + } + } +} diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..6ed8a0d --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,52 @@ +{ + "profiles": { + "http": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5111" + }, + "https": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7134;http://localhost:5111" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Container (Dockerfile)": { + "commandName": "Docker", + "launchBrowser": true, + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger", + "environmentVariables": { + "ASPNETCORE_HTTPS_PORTS": "8081", + "ASPNETCORE_HTTP_PORTS": "8080" + }, + "publishAllPorts": true, + "useSSL": true + } + }, + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:47947", + "sslPort": 44317 + } + } +} \ No newline at end of file diff --git a/Startup.cs b/Startup.cs new file mode 100644 index 0000000..6650ef4 --- /dev/null +++ b/Startup.cs @@ -0,0 +1,54 @@ +using Microsoft.AspNetCore.Hosting.Server; +using System; + +namespace TG_Bot_Template +{ + public class Startup + { + public class Startup + { + private readonly IConfiguration configuration; + + public Startup() + { + configuration = new ConfigurationBuilder() + .AddEnvironmentVariables() + .AddJsonFile("appsettings.json", optional: true) + .Build(); + } + + public void ConfigureServices(IServiceCollection services) + { + services.AddControllers(); + services + .AddSwaggerGen(); + + services + .AddSingleton(configuration) + .AddSingleton(x => x.CreateScope()) + .AddHostedService(); + + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + app.UseSwagger(); + app.UseSwagger(c => + { + c.RouteTemplate = "/swagger/v1/swagger.json"; + }); + } + app.UseStaticFiles(); + app.UseRouting(); + app.UseCors(k => { k.AllowAnyHeader(); k.AllowAnyMethod(); k.AllowAnyOrigin(); k.WithMethods("POST", "GET"); }); + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } + } +} diff --git a/TG-Bot-Template.csproj b/TG-Bot-Template.csproj new file mode 100644 index 0000000..3195c59 --- /dev/null +++ b/TG-Bot-Template.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + TG_Bot_Template + ccd791a8-a7f8-4a86-bcef-1a318801afa4 + Linux + . + + + + + + + + + diff --git a/TG-Bot-Template.sln b/TG-Bot-Template.sln new file mode 100644 index 0000000..141a8a9 --- /dev/null +++ b/TG-Bot-Template.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34728.123 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TG-Bot-Template", "TG-Bot-Template.csproj", "{A715056E-CFED-40D3-906D-AD1BF8C8E5FD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A715056E-CFED-40D3-906D-AD1BF8C8E5FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A715056E-CFED-40D3-906D-AD1BF8C8E5FD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A715056E-CFED-40D3-906D-AD1BF8C8E5FD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A715056E-CFED-40D3-906D-AD1BF8C8E5FD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {20E221A5-4AF6-46FE-AF6C-C8BBDB7663C1} + EndGlobalSection +EndGlobal diff --git a/TelegramBotService.cs b/TelegramBotService.cs new file mode 100644 index 0000000..a416770 --- /dev/null +++ b/TelegramBotService.cs @@ -0,0 +1,84 @@ +using System; +using Telegram.Bot.Types; +using Telegram.Bot; +using Telegram.Bot.Polling; +using Telegram.Bot.Types.Enums; + +namespace TG_Bot_Template +{ + public class TelegramBotService(IConfiguration conf, ILogger logger) : TelegramBotClient(conf.GetValue("tg-token")), IHostedService + { + private static Dictionary _userStates = new Dictionary(); + private static Dictionary _giveawaySettingMessages = new(); + + // For add any property, u should to add it in StartAsync func, like this: + // _PROPERTY_NAME = PROPERTY_NAME_FROM_CLASS + + private static ILogger _logger { get; set; } + + + private static async Task MainHandler(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + _logger.Log( + LogLevel.Information, + $"Received an update: {update.Type}, Caller ID: {update.Message?.From?.Id ?? update.CallbackQuery?.From.Id ?? update.InlineQuery?.From.Id}" + ); + var handler = update switch + { + + { Message: { } message } => HandleUpdateAsync(botClient, message), + //{ EditedMessage: { } message } => BotOnMessageReceived(message, cancellationToken), + { CallbackQuery: { } callbackQuery } => QueryUpdateHandler(botClient, callbackQuery), + { InlineQuery: { } inlineQuery } => InlineUpdateHandler(botClient, inlineQuery), + //{ ChosenInlineResult: { } chosenInlineResult } => BotOnChosenInlineResultReceived(chosenInlineResult, cancellationToken), + _ => Task.CompletedTask + }; + + await handler; + + + } + private static async Task HandleUpdateAsync(ITelegramBotClient botClient, Message message) + { + } + + private static async Task QueryUpdateHandler(ITelegramBotClient botClient, CallbackQuery callbackQuery) + { } + + private static async Task InlineUpdateHandler(ITelegramBotClient botClient, InlineQuery inlineQuery) + { } + + + public async Task StartAsync(CancellationToken cancellationToken) + { + logger.Log(LogLevel.Information, $"Starting build {this.GetType().Name}"); + // StartReceiving does not block the caller thread. Receiving is done on the ThreadPool. + ReceiverOptions receiverOptions = new() + { + AllowedUpdates = [UpdateType.Message, UpdateType.CallbackQuery] // receive all update types except ChatMember related updates + }; + + _logger = logger; + + this.StartReceiving( + updateHandler: MainHandler, + pollingErrorHandler: (k, ex, ctx) => { + Console.WriteLine(ex.Message); + + return Task.CompletedTask; + }, + receiverOptions: receiverOptions, + cancellationToken: cancellationToken + ); + var me = await this.GetMeAsync(cancellationToken: cancellationToken); + logger.Log(LogLevel.Information, $"Start listening bot @{me.Username}"); + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + logger.Log(LogLevel.Information, $"Stopping service {this.GetType().Name}"); + await this.LogOutAsync(cancellationToken); + } + + } +} diff --git a/appsettings.Development.json b/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..c8c4529 --- /dev/null +++ b/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "tg-token": "TOKEN" +}