PS-Commands/Scripts/Telegram-Bot-Service.ps1
2024-01-18 18:52:30 +03:00

81 lines
No EOL
2.5 KiB
PowerShell

function Get-FromTelegram {
param (
$Token = "687...:AAF...",
[switch]$Date,
[switch]$Last,
[switch]$ChatID
)
$endpoint = "getUpdates"
$url = "https://api.telegram.org/bot$Token/$endpoint"
$result = Invoke-RestMethod -Uri $url
if ($Date) {
$Collections = New-Object System.Collections.Generic.List[System.Object]
foreach ($r in $($result.result)) {
$EpochTime = [DateTime]"1/1/1970"
$TimeZone = Get-TimeZone
$UTCTime = $EpochTime.AddSeconds($r.message.date)
$d = $UTCTime.AddMinutes($TimeZone.BaseUtcOffset.TotalMinutes)
$Collections.Add([PSCustomObject]@{
Message = $r.message.text;
Date = $d
})
}
$Collections
}
else {
if ($Last) {
$result.result.message.text[-1]
}
elseif ($ChatID) {
$Collections = New-Object System.Collections.Generic.List[System.Object]
foreach ($r in $($result.result)) {
$Collections.Add([PSCustomObject]@{
Message = $r.message.text;
UserName = $r.message.chat.username;
ChatID = $r.message.chat.id;
ChatType = $r.message.chat.type
})
}
$Collections
}
else {
$result.result.message.text
}
}
}
function Send-ToTelegram {
param (
[Parameter(Mandatory = $True)]$Text,
$Token = "687...:AAF...",
$Chat = "125468108",
$Keyboard
)
$endpoint = "sendMessage"
$url = "https://api.telegram.org/bot$Token/$endpoint"
$Body = @{
chat_id = $Chat
text = $Text
}
if ($keyboard -ne $null) {
$Body += @{reply_markup = $keyboard}
}
Invoke-RestMethod -Uri $url -Body $Body
}
$LastDate = (Get-FromTelegram -date)[-1].Date
while ($true) {
$LastMessage = (Get-FromTelegram -date)[-1]
Start-Sleep 1
$LastDateTest = $LastMessage.Date
if (($LastMessage.Message -match "/Service") -and ($LastDate -ne $LastDateTest)) {
$ServiceName = $($LastMessage.Message -split " ")[-1]
$Result = $(Get-Service $ServiceName -ErrorAction Ignore).Status
if ($Result) {
Send-ToTelegram -Text $Result
} else {
Send-ToTelegram -Text "Service not found"
}
$LastDate = $LastDateTest
}
}