Skip to content

Commit 124e192

Browse files
committed
Add authorization for /help command and handler setup
- Updated `HomeController.cs` to include two new methods for handling the `/help` command, one authorized and one not. - Modified `Program.cs` to include `TelegramBot.Extensions` namespace and use an authorization handler. - Added `AuthorizationHandler.cs` to define `AuthorizationHandler` class implementing `IBotAuthorizationHandler` for user ID-based authorization.
1 parent 3fe9df0 commit 124e192

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using Telegram.Bot.Types;
2+
using TelegramBot.Abstractions;
3+
using TelegramBot.ActionResults;
4+
5+
namespace TelegramBot.ConsoleTest
6+
{
7+
internal class AuthorizationHandler : IBotAuthorizationHandler
8+
{
9+
public bool Authorize(User authorizingUser)
10+
{
11+
return authorizingUser.Id == 1234567890;
12+
}
13+
14+
public IActionResult HandleUnauthorized(User authorizingUser)
15+
{
16+
return new TextResult("You are not authorized to use this bot.");
17+
}
18+
}
19+
}

Sources/TelegramBot.ConsoleTest/Controllers/HomeController.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,20 @@ public IActionResult HandleLanguageAsync(string lang)
2828
_logger.LogInformation("Language command received.");
2929
return Text($"Language set to {lang}.");
3030
}
31+
32+
[TextCommand("/help")]
33+
public IActionResult HandleHelpAsync(int page = 1)
34+
{
35+
_logger.LogInformation("Help command received.");
36+
return Text("Help message: page " + page);
37+
}
38+
39+
[Authorize]
40+
[TextCommand("/help")]
41+
public IActionResult HandleHelpAsync()
42+
{
43+
_logger.LogInformation("Help command received.");
44+
return Text("Help message.");
45+
}
3146
}
3247
}

Sources/TelegramBot.ConsoleTest/Program.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using TelegramBot.Builders;
2+
using TelegramBot.Extensions;
23
using Microsoft.EntityFrameworkCore;
34
using TelegramBot.ConsoleTest.Database;
45
using Microsoft.Extensions.DependencyInjection;
@@ -12,9 +13,12 @@ public static void Main(string[] args)
1213
BotBuilder builder = new BotBuilder(args)
1314
.UseApiKey(x => x.FromConfiguration());
1415

15-
builder.Services.AddDbContext<AppDbContext>(x => x.UseSqlite("Data Source=app.db"));
16+
builder.Services
17+
.AddDbContext<AppDbContext>(x => x.UseSqlite("Data Source=app.db"))
18+
.UseAuthorizationHandler<AuthorizationHandler>();
1619
var app = builder.Build();
1720
app.MapControllers();
21+
1822
app.Run();
1923
}
2024
}

0 commit comments

Comments
 (0)