Skip to content

Commit

Permalink
Proxmox VE 8.2
Browse files Browse the repository at this point in the history
  • Loading branch information
franklupo committed May 2, 2024
1 parent 73371b8 commit e6ea804
Show file tree
Hide file tree
Showing 19 changed files with 228 additions and 264 deletions.
7 changes: 0 additions & 7 deletions .editorconfig

This file was deleted.

3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -329,4 +329,5 @@ ASALocalRun/
# MFractors (Xamarin productivity tool) working folder
.mfractor/

*.Parm
*.Parm
artifacts_nupkg/
16 changes: 7 additions & 9 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
// Usare IntelliSense per individuare gli attributi esistenti per il debug C#
// Usa il passaggio del mouse per la descrizione degli attributi esistenti
// Per ulteriori informazioni, visitare https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/src/Corsinvest.ProxmoxVE.TelegramBot/bin/Debug/net6.0/cv4pve-botgram.dll",
"args": [
"@Parm.Parm"
],
// Se i framework di destinazione sono stati modificati, assicurarsi di aggiornare il percorso del programma.
"program": "${workspaceFolder}/src/Corsinvest.ProxmoxVE.TelegramBot/bin/Debug/net8.0/cv4pve-botgram.dll",
"args": [],
"cwd": "${workspaceFolder}/src/Corsinvest.ProxmoxVE.TelegramBot",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
// Per ulteriori informazioni sul campo 'console', vedere https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
Expand Down
10 changes: 5 additions & 5 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
"type": "process",
"args": [
"build",
"${workspaceFolder}/src/Corsinvest.ProxmoxVE.TelegramBot/Corsinvest.ProxmoxVE.TelegramBot.csproj",
"${workspaceFolder}/Corsinvest.ProxmoxVE.TelegramBot.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
Expand All @@ -19,9 +19,9 @@
"type": "process",
"args": [
"publish",
"${workspaceFolder}/src/Corsinvest.ProxmoxVE.TelegramBot/Corsinvest.ProxmoxVE.TelegramBot.csproj",
"${workspaceFolder}/Corsinvest.ProxmoxVE.TelegramBot.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
Expand All @@ -33,7 +33,7 @@
"watch",
"run",
"--project",
"${workspaceFolder}/src/Corsinvest.ProxmoxVE.TelegramBot/Corsinvest.ProxmoxVE.TelegramBot.csproj"
"${workspaceFolder}/Corsinvest.ProxmoxVE.TelegramBot.sln"
],
"problemMatcher": "$msCompile"
}
Expand Down
48 changes: 23 additions & 25 deletions README.MD
Original file line number Diff line number Diff line change
@@ -1,38 +1,35 @@
# cv4pve-botgram

[![License](https://img.shields.io/github/license/Corsinvest/cv4pve-botgram.svg)](LICENSE.md) [![AppVeyor branch](https://img.shields.io/appveyor/ci/franklupo/cv4pve-botgram/master.svg)](https://ci.appveyor.com/project/franklupo/cv4pve-botgram)
[![License](https://img.shields.io/github/license/Corsinvest/cv4pve-botgram.svg)](LICENSE.md)

[ProxmoxVE Api](https://pve.proxmox.com/pve-docs/api-viewer/)

```text
______ _ __
/ ____/___ __________(_)___ _ _____ _____/ /_
/ / / __ \/ ___/ ___/ / __ \ | / / _ \/ ___/ __/
/ /___/ /_/ / / (__ ) / / / / |/ / __(__ ) /_
\____/\____/_/ /____/_/_/ /_/|___/\___/____/\__/
______ _ __
/ ____/___ __________(_)___ _ _____ _____/ /_
/ / / __ \/ ___/ ___/ / __ \ | / / _ \/ ___/ __/
/ /___/ /_/ / / (__ ) / / / / |/ / __(__ ) /_
\____/\____/_/ /____/_/_/ /_/|___/\___/____/\__/
Telegram bot for Proxmox VE (Made in Italy)
Usage: cv4pve-botgram [options]
Telegram bot for Proxmox VE (Made in Italy)
cv4pve-botgram is a part of suite cv4pve.
For more information visit https://www.corsinvest.it/cv4pve
Usage:
cv4pve-botgram [options]
Options:
-?|-h|--help Show help information
--version Show version information
--host The host name host[:port],host1[:port],host2[:port]
--api-token Api token format 'USER@REALM!TOKENID=UUID'. Require Proxmox VE 6.2 or later
--username User name <username>@<realm>
--password The password. Specify 'file:path_file' to store password in file.
--token Telegram API token bot
--chatsId Telegram Chats Id valid for communication (comma separated)
Commands:
app-check-update Check update application
app-upgrade Upgrade application
Run 'cv4pve-botgram [command] --help' for more information about a command.
cv4pve-botgram is a part of suite cv4pve-tools.
For more information visit https://www.cv4pve-tools.com
--api-token <api-token> Api token format 'USER@REALM!TOKENID=UUID'. Require Proxmox VE 6.2 or later
--username <username> User name <username>@<realm>
--password <password> The password. Specify 'file:path_file' to store password in file.
--validate-certificate Validate SSL Certificate Proxmox VE node.
--host <host> (REQUIRED) The host name host[:port],host1[:port],host2[:port]
--token <token> (REQUIRED) Telegram API token bot
--chatsId <chatsId> Telegram Chats Id valid for communication (comma separated)
--version Show version information
-?, -h, --help Show help and usage information
```

## Copyright and License
Expand Down Expand Up @@ -71,6 +68,7 @@ this software aims to simplify the management of Proxmox VE single node or clust
* Complex output to document in chat
* Valid ChatsId for communication
* Use Api token --api-token parameter
* Validate certificate SSL, default not validate

## Api token

Expand Down
77 changes: 39 additions & 38 deletions src/Corsinvest.ProxmoxVE.TelegramBot.Api/BotManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Corsinvest.ProxmoxVE.Api.Extension.Utils;
using Corsinvest.ProxmoxVE.TelegramBot.Commands.Api;
using Corsinvest.ProxmoxVE.TelegramBot.Helpers.Api;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
Expand All @@ -26,15 +27,17 @@ namespace Corsinvest.ProxmoxVE.TelegramBot.Api;
/// </summary>
public class BotManager
{
private readonly TelegramBotClient _client;
private readonly long[] _chatsIdValid;
private readonly TextWriter _out;
private readonly Dictionary<long, (Message Message, Command Command)> _lastCommandForChat;
private CancellationTokenSource Cts;
private Dictionary<long, string> _chats;
private static string _pveUsername;
private static string _pvePassword;
private static string _pveApiToken;
private readonly string _pveUsername;
private readonly string _pvePassword;
private readonly bool _pveValidateCertificate;
private readonly ILoggerFactory _loggerFactory;
private readonly string _pveApiToken;
internal TelegramBotClient BotClient { get; private set; }

/// <summary>
/// Constructor
Expand All @@ -43,13 +46,17 @@ public class BotManager
/// <param name="pveApiToken">Proxmox VE Api Token</param>
/// <param name="pveUsername">Proxmox VE username</param>
/// <param name="pvePassword">Proxmox VE password</param>
/// <param name="pveValidateCertificate"></param>
/// <param name="loggerFactory"></param>
/// <param name="token">Token Telegram Bot</param>
/// <param name="chatsIdValid">Valid chats Id</param>
/// <param name="out">Output write</param>
public BotManager(string pveHostAndPortHA,
string pveApiToken,
string pveUsername,
string pvePassword,
bool pveValidateCertificate,
ILoggerFactory loggerFactory,
string token,
long[] chatsIdValid,
TextWriter @out)
Expand All @@ -58,42 +65,36 @@ public BotManager(string pveHostAndPortHA,
_pveApiToken = pveApiToken;
_pveUsername = pveUsername;
_pvePassword = pvePassword;
_pveValidateCertificate = pveValidateCertificate;
_loggerFactory = loggerFactory;

_chatsIdValid = chatsIdValid;
_out = @out;
_lastCommandForChat = new Dictionary<long, (Message, Command)>();

_chats = new();
_lastCommandForChat = [];
_chats = [];

//create telegram
_client = new TelegramBotClient(token);
BotClient = new TelegramBotClient(token);
}

internal static string PveHostAndPortHA { get; set; }
internal string PveHostAndPortHA { get; set; }

/// <summary>
/// Get client
/// </summary>
/// <returns></returns>
internal static async Task<PveClient> GetPveClient()
{
var client = ClientHelper.GetClientFromHA(PveHostAndPortHA);
if (string.IsNullOrWhiteSpace(_pveApiToken))
{
await client.Login(_pveUsername, _pvePassword);
}
else
{
client.ApiToken = _pveApiToken;
}

return client;
}
internal async Task<PveClient> GetPveClientAsync()
=> await ClientHelper.GetClientAndTryLoginAsync(PveHostAndPortHA,
_pveUsername,
_pvePassword,
_pveApiToken,
_pveValidateCertificate,
_loggerFactory);

/// <summary>
/// Bot Id
/// </summary>
public long? BootId => _client.BotId;
public long? BootId => BotClient.BotId;

/// <summary>
/// Chat username
Expand All @@ -106,30 +107,30 @@ internal static async Task<PveClient> GetPveClient()
/// </summary>
/// <param name="chatId"></param>
/// <param name="message"></param>
public async Task SendMessageAsync(long chatId, string message) => await _client.SendTextMessageAsync(chatId, message);
public async Task SendMessageAsync(long chatId, string message) => await BotClient.SendTextMessageAsync(chatId, message);

/// <summary>
/// Chat info
/// </summary>
public IReadOnlyDictionary<long,string> Chats => _chats;
public IReadOnlyDictionary<long, string> Chats => _chats;

/// <summary>
/// Start chat
/// </summary>
public void StartReceiving()
{
Cts = new CancellationTokenSource();
_chats = new();
_chats = [];

_client.StartReceiving(updateHandler: HandleUpdateAsync,
BotClient.StartReceiving(updateHandler: HandleUpdateAsync,
pollingErrorHandler: HandlePollingErrorAsync,
receiverOptions: new ReceiverOptions
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types
},
cancellationToken: Cts.Token);

var result = _client.GetMeAsync().Result;
var result = BotClient.GetMeAsync().Result;
Username = result.Username;

_out.WriteLine($@"Start listening
Expand All @@ -149,7 +150,7 @@ public void StopReceiving()
//Send cancellation request to stop bot
Cts.Cancel();
Cts = null;
_chats = new();
_chats = [];
}

private async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
Expand Down Expand Up @@ -181,27 +182,27 @@ private async Task ProcessCallbackQuery(CallbackQuery callbackQuery)
await _out.WriteLineAsync($"OnCallbackQuery: {callbackQuery.Data}");

var chatId = callbackQuery.Message.Chat.Id;
await _client.DeleteMessageAsync(chatId, callbackQuery.Message.MessageId);
await BotClient.DeleteMessageAsync(chatId, callbackQuery.Message.MessageId);

try
{
if (_lastCommandForChat.TryGetValue(chatId, out var value))
{
if (await value.Command.Execute(value.Message, callbackQuery, _client))
if (await value.Command.Execute(value.Message, callbackQuery, this))
{
_lastCommandForChat.Remove(chatId);
}
}
else
{
_lastCommandForChat.Remove(chatId);
await _client.SendTextMessageAsyncNoKeyboard(chatId, $"Data not recognized '{callbackQuery.Data}'");
await BotClient.SendTextMessageAsyncNoKeyboard(chatId, $"Data not recognized '{callbackQuery.Data}'");
}
}
catch (Exception ex)
{
await _out.WriteLineAsync(ex.StackTrace);
await _client.SendTextMessageAsyncNoKeyboard(chatId, $"Error CallbackQuery! {ex.Message}");
await BotClient.SendTextMessageAsyncNoKeyboard(chatId, $"Error CallbackQuery! {ex.Message}");
}
}

Expand All @@ -216,14 +217,14 @@ private async Task ProcessMessage(Message message)
$" User: '{message.Chat.Username}'" +
$" - '{message.Chat.FirstName} {message.Chat.LastName}'" +
$" Msg Type: '{message.Type}'";
if (message.Type == MessageType.Text) { log += $"=> '{message.Text}'"; }
if (message.Type == MessageType.Text) { log += $" => '{message.Text}'"; }
await _out.WriteLineAsync(log);

//check security Chat
if (_chatsIdValid.Any() && !_chatsIdValid.Contains(chatId))
{
await _out.WriteLineAsync($"Security: Chat Id '{chatId}' - Username '{message.Chat.Username}' not permitted access!");
await _client.SendTextMessageAsync(chatId, "You not have permission in this Chat!");
await BotClient.SendTextMessageAsync(chatId, "You not have permission in this Chat!");
return;
}

Expand All @@ -241,7 +242,7 @@ private async Task ProcessMessage(Message message)

try
{
if (await command.Execute(message, _client))
if (await command.Execute(message, this))
{
_lastCommandForChat.Remove(chatId);
}
Expand All @@ -250,7 +251,7 @@ private async Task ProcessMessage(Message message)
{
_lastCommandForChat.Remove(chatId);
await _out.WriteLineAsync(ex.StackTrace);
await _client.SendTextMessageAsyncNoKeyboard(chatId, $"Error execute command! {ex.Message}");
await BotClient.SendTextMessageAsyncNoKeyboard(chatId, $"Error execute command! {ex.Message}");
}
}
}
Loading

0 comments on commit e6ea804

Please sign in to comment.