-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
119 lines (99 loc) · 4.41 KB
/
Program.cs
File metadata and controls
119 lines (99 loc) · 4.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using DotNetEnv;
using Microsoft.EntityFrameworkCore;
using Telegram.Bot;
using Telegram.Bot.Polling;
using MyLinuxBot.Data;
using MyLinuxBot.Interfaces;
using MyLinuxBot.Services;
using MyLinuxBot.Commands;
using MyLinuxBot.Workers;
using MyLinuxBot.Handlers;
// Load environment variables from .env file
Env.Load();
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddEnvironmentVariables();
var botToken = builder.Configuration["TELEGRAM_BOT_TOKEN"];
if (string.IsNullOrWhiteSpace(botToken) || botToken == "your_bot_token_here")
{
Console.WriteLine("Warning: TELEGRAM_BOT_TOKEN is missing or not configured. Set it in the .env file.");
}
// 1. Register Database (SQLite)
builder.Services.AddDbContextFactory<BotDbContext>(options =>
{
// Use a local SQLite database
options.UseSqlite($"Data Source=MyLinuxBot.db");
});
// 2. Register Telegram Bot Components
var client = new TelegramBotClient(botToken ?? "dummy_token_to_allow_build");
builder.Services.AddSingleton<ITelegramBotClient>(client);
builder.Services.AddSingleton<IUpdateHandler, BotUpdateHandler>();
builder.Services.AddHostedService<BotHostedService>();
// 3. Register Domain Services
builder.Services.AddSingleton<IShellService, ShellService>();
builder.Services.AddSingleton<IAiToolboxService, AiToolboxService>();
builder.Services.AddHttpClient<IGeminiService, GeminiService>();
builder.Services.AddScoped<IJobScannerService, JobScannerService>();
builder.Services.AddHostedService<JobScannerWorker>();
builder.Services.AddHttpClient<IN8nIntegrationService, N8nIntegrationService>();
builder.Services.AddHttpClient<IWhisperService, WhisperService>(client =>
{
client.BaseAddress = new Uri("http://localhost:8000");
});
// 4. Register Commands (Command Pattern)
builder.Services.AddTransient<ITelegramCommand, ShellCommand>();
builder.Services.AddTransient<ITelegramCommand, K8sCommand>();
builder.Services.AddTransient<ITelegramCommand, AskCommand>();
builder.Services.AddTransient<ITelegramCommand, UploadCommand>();
builder.Services.AddTransient<ITelegramCommand, StatsCommand>();
builder.Services.AddTransient<ITelegramCommand, PowerCommand>();
builder.Services.AddTransient<ITelegramCommand, ProcessCommand>();
builder.Services.AddTransient<ITelegramCommand, ScreenCommand>();
builder.Services.AddTransient<ITelegramCommand, ScanCommand>();
var app = builder.Build();
// Initialize Database schema
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<BotDbContext>();
dbContext.Database.EnsureCreated();
}
// 5. Minimal API webhook endpoint integration
app.MapPost("/webhook/n8n", async (ILogger<Program> logger, IConfiguration config, ITelegramBotClient bot) =>
{
logger.LogInformation("Webhook invoked from n8n.");
var allowedChatId = config.GetValue<long>("ALLOWED_CHAT_ID");
if (allowedChatId != 0)
{
try
{
await bot.SendMessage(allowedChatId, "Alert: Webhook received from n8n!");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to send webhook notification.");
}
}
return Results.Ok(new { success = true });
});
// 6. API Endpoint for n8n Agent Actions
app.MapPost("/api/execute", async (HttpContext context, IConfiguration config, IShellService shellService) =>
{
var apiKey = config["N8N_API_KEY"];
if (!context.Request.Headers.TryGetValue("X-API-Key", out var extractedApiKey) || extractedApiKey != apiKey)
{
return Results.Unauthorized();
}
using var streamReader = new StreamReader(context.Request.Body);
var body = await streamReader.ReadToEndAsync();
var payload = System.Text.Json.JsonSerializer.Deserialize<ExecutePayload>(body, new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (payload == null || string.IsNullOrWhiteSpace(payload.Command))
{
return Results.BadRequest(new { error = "Command payload is missing or invalid." });
}
string? workingDirectory = payload.Type?.ToLower() == "k8s"
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Documents/Documents/K8s/Setup")
: null;
var result = await shellService.ExecuteCommandAsync(payload.Command, workingDirectory);
return Results.Ok(new { success = true, output = result });
});
app.Run();
public class ExecutePayload { public string? Command { get; set; } public string? Type { get; set; } }