.net - 通过Telegram机器人发送sendDocument

标签 .net powershell telegram 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 。如何正确发送文件?

最佳答案

通过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参数(如果需要,可以从GitHub上使用download);我找到了这个原始示例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

关于.net - 通过Telegram机器人发送sendDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64563264/

相关文章:

如果与其他语句混合,ps1 文件中的 Java 语句不会以管理员身份执行。 (错误:Return argument has an invalid type)

powershell - 如何通过powershell将计算机加入域

bots - 不要让成员在 Telegram 组中发送消息

python - 错误消息堵塞 Telethon 导致安全错误 : Server sent a very new message xxxxx was ignored

c# - 使用 Graphics.DrawString 时动态调整字体大小以适应空间

c# - 移植WinForms拖拽到WPF拖拽

c# - 通过 Teamviewer 连接时 WPF 应用程序崩溃

powershell - 将Format-Hex PowerShell表转换为原始十六进制转储

c# - Winforms 中的事件和 WPF 中的命令有什么区别?

Telegram Bot 如何从 channel 或群组中删除或移除消息或媒体