我正在用Julia编写Telegram机器人,但我不知道如何正确发送文件。
对于其他语言,我也曾见过类似的问题,但这并没有帮助。
目前,我具有这样的功能:
function sendDoc(chat, fileName::String)
file = open(fileName)
url = string(base_url, "sendDocument")
mp = HTTP.Multipart(basename(fileName), file)
query = Dict("chat_id" => chat)
HTTP.post(url; query=query, files=Dict("document" => mp))
close(file)
end
我在具有内容test.txt
的简单abc
文件上尝试,因此文件大小或名称不会成为任何错误的原因。
我从中得到的信息(以及如果我使用file
而不是mp
的情况)是HTTP 400错误(出于隐私目的,我删除了一些部分):
ERROR: LoadError: HTTP.ExceptionRequest.StatusError(400, "POST", "/bot/sendDocument?chat_id=", HTTP.Messages.Response(v"1.1.0", 400, Pair{SubString{String},SubString{String}}["Server" => "nginx/1.16.1", "Date" => "Thu, 12 Mar 2020 GMT", "Content-Type" => "application/json", "Content-Length" => "94", "Connection" => "keep-alive", "Strict-Transport-Security" => "max-age=31536000; includeSubDomains; preload", "Access-Control-Allow-Origin" => "*", "Access-Control-Expose-Headers" => "Content-Length,Content-Type,Date,Server,Connection"], UInt8[0x7b, 0x22, 0x6f, 0x6b, 0x22, 0x3a, 0x66, 0x61, 0x6c, 0x73 … 0x20, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x7d], HTTP.Messages.Request("POST", "/bot/sendDocument?chat_id=", v"1.1.0", Pair{SubString{String},SubString{String}}["Host" => "api.telegram.org", "User-Agent" => "HTTP.jl/1.3.1", "Content-Length" => "0"], UInt8[], HTTP.Messages.Response(#= circular reference @-2 =#), 1, nothing)))
我还尝试将mp
或file
而不是body
放在files
中,但是我得到以下信息:
┌ Info: Error in @async writebody task. Server likely closed the connection unexpectedly. Only an issue if unable to read the response and this error gets re-thrown.
│ exception =
│ MethodError: no method matching write(::HTTP.Streams.Stream{HTTP.Messages.Response,HTTP.ConnectionPool.Transaction{MbedTLS.SSLContext}}, ::Pair{String,IOStream})
│ Closest candidates are:
│ write(::IO, ::Any) at io.jl:582
│ write(::IO, ::Any, ::Any...) at io.jl:584
│ write(::IO, ::Complex) at complex.jl:217
我也可以尝试将文件包含在query
中,但是随后它将出现在URL中,并且文件大小受到很大限制。
400错误看起来与缺少字段一样,因此我认为Telegram无法看到Dict("document" => mp)
,但同时错误包括UInt8[0x7b, … 0x7d]
,看起来像文件内容。我该怎么做?
答案 0 :(得分:1)
结果是,我需要的不是HTTP.Multipart
,而是HTTP.Form
。
以下功能有效:
function sendDoc(chat, fileName::String)
url = string(base_url, "sendDocument")
file = open(fileName)
query = Dict("chat_id" => chat)
HTTP.post(url, query=query; body=HTTP.Form(Dict("document" => file)))
close(file)
end
答案 1 :(得分:1)
如果愿意,可以使用Telegram.jl软件包,其中特别包括对文档和图像发送的支持。
您可以这样做
using Telegram, Telegram.API
tg = TelegramClient(bot_token; chat_id = chat)
open("picture.png", "r") do io
sendPhoto(photo = io)
end
bot_token
和chat
是漫游器令牌和聊天ID。
答案 2 :(得分:0)
假设您在目录“ Foto.jpg”中有一张照片。要发送照片,您需要这样做:
fileName = "Foto.jpg"
url_photo = string("https://api.telegram.org/bot",bot_token,"/sendPhoto")
file = open(fileName)
query = Dict("chat_id" => bot_manu)
HTTP.post(url_photo, query=query; body=HTTP.Form(Dict("photo" => file)))
close(file)
“ bot_manu”应为您的聊天ID,“ bot_token”应为bot ID令牌。希望这对想要发送照片的人有所帮助。为了获得“ bot_manu”和“ bot_token”,我使用了BotFather。