【问题标题】:sendDocument via Telegram bot通过 Telegram 机器人发送文档
【发布时间】:2020-10-29 22:59:50
【问题描述】:

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

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

【问题讨论】:

    标签: .net powershell telegram telegram-bot


    【解决方案1】:

    通过 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
    

    【讨论】:

      【解决方案2】:

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

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

      这个项目的目标是将复杂性抽象出来,有利于 简单直接的 PowerShell 命令。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-17
        • 2021-03-22
        • 2021-11-07
        • 2017-05-01
        • 2022-01-03
        • 1970-01-01
        • 2017-09-01
        相关资源
        最近更新 更多