Skip to content

Commit

Permalink
Simplify Webhook.Controllers, harmonize stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
wiz0u committed Jul 3, 2024
1 parent c261ac4 commit 45ecd75
Show file tree
Hide file tree
Showing 26 changed files with 127 additions and 234 deletions.
4 changes: 2 additions & 2 deletions Console.Advanced/Console.Advanced.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
</ItemGroup>

<ItemGroup>
<None Update="Files\tux.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<None Update="Files\bot.gif">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

Expand Down
Binary file added Console.Advanced/Files/bot.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed Console.Advanced/Files/tux.png
Binary file not shown.
2 changes: 1 addition & 1 deletion Console.Advanced/Services/UpdateHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async Task<Message> SendPhoto(Message msg)
{
await _bot.SendChatActionAsync(msg.Chat, ChatAction.UploadPhoto);
await Task.Delay(2000); // simulate a long task
await using var fileStream = new FileStream("Files/tux.png", FileMode.Open, FileAccess.Read);
await using var fileStream = new FileStream("Files/bot.gif", FileMode.Open, FileAccess.Read);
return await _bot.SendPhotoAsync(msg.Chat, fileStream, caption: "Read https://telegrambots.github.io/book/");
}

Expand Down
2 changes: 1 addition & 1 deletion Console.Advanced/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
}
},
"BotConfiguration": {
"BotToken": "{BOT_TOKEN}"
"BotToken": "YOUR_BOT_TOKEN",
}
}
4 changes: 2 additions & 2 deletions FSharp.Example/FSharp.Example.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<None Include="Files\tux.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<None Include="Files\bot.gif">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
Expand Down
Binary file added FSharp.Example/Files/bot.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed FSharp.Example/Files/tux.png
Binary file not shown.
2 changes: 1 addition & 1 deletion FSharp.Example/Services/Internal/UpdateHandlerFuncs.fs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ module UpdateHandlerFuncs =
cancellationToken = cts)
|> Async.AwaitTask |> ignore

let filePath = @"Files/tux.png"
let filePath = @"Files/bot.gif"
let fileName =
filePath.Split(Path.DirectorySeparatorChar)
|> Array.last
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"profiles": {
"Mock Lambda Test Tool": {
"commandName": "Executable",
"commandLineArgs": "--port 5050",
"workingDirectory": ".\\bin\\$(Configuration)\\netcoreapp3.1",
"executablePath": "C:\\Users\\%USERNAME%\\.dotnet\\tools\\dotnet-lambda-test-tool-3.1.exe"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"profiles": {
"AzureFunctions_IsolatedProcess_Webhook": {
"commandName": "Project",
"commandLineArgs": "--port 7071",
"launchBrowser": false
}
}
}
6 changes: 6 additions & 0 deletions Webhook.Controllers/BotConfiguration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
public class BotConfiguration
{
public string BotToken { get; init; } = default!;
public Uri BotWebhookUrl { get; init; } = default!;
public string SecretToken { get; init; } = default!;
}
30 changes: 20 additions & 10 deletions Webhook.Controllers/Controllers/BotController.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Telegram.Bot;
using Telegram.Bot.Filters;

Check failure on line 4 in Webhook.Controllers/Controllers/BotController.cs

View workflow job for this annotation

GitHub Actions / build

The type or namespace name 'Filters' does not exist in the namespace 'Telegram.Bot' (are you missing an assembly reference?)

Check failure on line 4 in Webhook.Controllers/Controllers/BotController.cs

View workflow job for this annotation

GitHub Actions / build

The type or namespace name 'Filters' does not exist in the namespace 'Telegram.Bot' (are you missing an assembly reference?)
using Telegram.Bot.Services;
using Telegram.Bot.Types;
using Webhook.Controllers.Services;

namespace Telegram.Bot.Controllers;
namespace Webhook.Controllers.Controllers;

public class BotController : ControllerBase
[ApiController]
[Route("[controller]")]
public class BotController(IOptions<BotConfiguration> Config) : ControllerBase
{
[HttpGet("setWebhook")]
public async Task<string> SetWebHook([FromServices] TelegramBotClient bot, CancellationToken ct)
{
var webhookUrl = Config.Value.BotWebhookUrl.AbsoluteUri;
await bot.SetWebhookAsync(webhookUrl, allowedUpdates: [], secretToken: Config.Value.SecretToken, cancellationToken: ct);
return $"Webhook set to {webhookUrl}";
}

[HttpPost]
[ValidateTelegramBot]
public async Task<IActionResult> Post(
[FromBody] Update update,
[FromServices] UpdateHandler handleUpdateService,
CancellationToken cancellationToken)
public async Task<IActionResult> Post([FromBody] Update update, [FromServices] UpdateHandler handleUpdateService, CancellationToken ct)
{
if (Request.Headers["X-Telegram-Bot-Api-Secret-Token"] != Config.Value.SecretToken)
return Forbid();
try
{
await handleUpdateService.HandleUpdateAsync(update, cancellationToken);
await handleUpdateService.HandleUpdateAsync(update, ct);
}
catch (Exception exception)
{
await handleUpdateService.HandleErrorAsync(exception, Polling.HandleErrorSource.HandleUpdateError, cancellationToken);
await handleUpdateService.HandleErrorAsync(exception, ct);
}
return Ok();
}
Expand Down
31 changes: 0 additions & 31 deletions Webhook.Controllers/Extensions.cs

This file was deleted.

Binary file added Webhook.Controllers/Files/bot.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed Webhook.Controllers/Files/tux.png
Binary file not shown.
52 changes: 0 additions & 52 deletions Webhook.Controllers/Filters/ValidateTelegramBotRequestAttribute.cs

This file was deleted.

64 changes: 15 additions & 49 deletions Webhook.Controllers/Program.cs
Original file line number Diff line number Diff line change
@@ -1,59 +1,25 @@
using Telegram.Bot;
using Telegram.Bot.Controllers;
using Telegram.Bot.Services;

var builder = WebApplication.CreateBuilder(args);

// Setup Bot configuration
var botConfigurationSection = builder.Configuration.GetSection(BotConfiguration.Configuration);
builder.Services.Configure<BotConfiguration>(botConfigurationSection);

var botConfiguration = botConfigurationSection.Get<BotConfiguration>();

// Register named HttpClient to get benefits of IHttpClientFactory
// and consume it with ITelegramBotClient typed client.
// More read:
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests#typed-clients
// https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
builder.Services.AddHttpClient("telegram_bot_client")
.AddTypedClient<ITelegramBotClient>((httpClient, sp) =>
{
BotConfiguration? botConfig = sp.GetConfiguration<BotConfiguration>();
TelegramBotClientOptions options = new(botConfig.BotToken);
return new TelegramBotClient(options, httpClient);
});

// Dummy business-logic service
builder.Services.AddScoped<UpdateHandler>();

// There are several strategies for completing asynchronous tasks during startup.
// Some of them could be found in this article https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-part-1/
// We are going to use IHostedService to add and later remove Webhook
builder.Services.AddHostedService<ConfigureWebhook>();
// Setup bot configuration
var botConfigSection = builder.Configuration.GetSection("BotConfiguration");
builder.Services.Configure<BotConfiguration>(botConfigSection);
builder.Services.AddHttpClient("tgwebhook").RemoveAllLoggers().AddTypedClient(
httpClient => new TelegramBotClient(botConfigSection.Get<BotConfiguration>()!.BotToken, httpClient));
builder.Services.AddScoped<Webhook.Controllers.Services.UpdateHandler>();
builder.Services.ConfigureTelegramBotMvc();

builder.Services.AddControllers();

// The Telegram.Bot library heavily depends on System.Text.Json library with special Json
// settings to deserialize incoming webhook updates and send serialized responses back.
builder.Services.ConfigureTelegramBotMvc();

var app = builder.Build();
// Construct webhook route from the Route configuration parameter
// It is expected that BotController has single method accepting Update
app.MapBotWebhookRoute<BotController>(route: botConfiguration.Route);

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();
app.Run();

#pragma warning disable CA1050 // Declare types in namespaces
#pragma warning disable RCS1110 // Declare type inside namespace.
public class BotConfiguration
#pragma warning restore RCS1110 // Declare type inside namespace.
#pragma warning restore CA1050 // Declare types in namespaces
{
public static readonly string Configuration = "BotConfiguration";

public string BotToken { get; init; } = default!;
public string HostAddress { get; init; } = default!;
public string Route { get; init; } = default!;
public string SecretToken { get; init; } = default!;
}
app.Run();
41 changes: 41 additions & 0 deletions Webhook.Controllers/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5131",
"sslPort": 44315
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "bot/setWebhook",
"applicationUrl": "http://localhost:5227",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "bot/setWebhook",
"applicationUrl": "https://localhost:7057;http://localhost:5227",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "bot/setWebhook",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
54 changes: 0 additions & 54 deletions Webhook.Controllers/Services/ConfigureWebhook.cs

This file was deleted.

Loading

0 comments on commit 45ecd75

Please sign in to comment.