通过 Telegram 机器人发送文档

sendDocument via Telegram bot

sendDocument 需要 multipart/form-data.

$path    = 'C:\file.txt'
$userId  = 12345
$token   = "ABC123"
$url     = "https://api.telegram.org/-/sendDocument?chat_id=+"

[net.servicepointmanager]::securityprotocol = 'ssl3,tls,tls11,tls12'
$url = $url.Replace("-",$token).Replace("+",$userId)
$Response = Iwr -Uri $url -Method Post -InFile $path -ContentType "multipart/form-data"
$Response.Content

但是我得到了错误:400。如何正确发送文件?

我不太了解它,但我最近在 Telegram 上阅读了一些内容,我知道有一个名为 PoShGram 的模块可以让您与之交互。你可以找到它here

乍一看,它可能具有您需要的功能。读我说:

The goal of this project to abstract that complexity away in favor of simple and direct PowerShell commands.

通过 PowerShell 使用 Telegram 机器人发送文件需要做更多的工作。 这是如何发送文本文档的示例:

$payload = @{
    chat_id              = $ChatID
    document             = $FileURL
    caption              = $Caption
    parse_mode           = $ParseMode
    disable_notification = $DisableNotification.IsPresent
}

$invokeRestMethodSplat = @{
    Uri         = ("https://api.telegram.org/bot{0}/sendDocument" -f $BotToken)
    Body        = (ConvertTo-Json -Compress -InputObject $payload)
    ErrorAction = 'Stop'
    ContentType = "application/json"
    Method      = 'Post'
}

try {
    Invoke-RestMethod @invokeRestMethodSplat
}
catch {
    Write-Error $_
}

我发现的另一个选择是在 PowerShell v6.1 或更高版本中使用 Form 参数 (download it from GitHub if needed); I found this raw example here:

$doc = "C:\something.txt"

$Uri = "https://api.telegram.org/bot$($BotToken)/sendDocument"
#Build the Form
$Form = @{
chat_id = $chatID
document = Get-Item $doc
}
Invoke-RestMethod -Uri $uri -Form $Form -Method Post