Skip to content

Instantly share code, notes, and snippets.

@ptflp
Created April 5, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptflp/412bd3d5785d3162035eeb3f792d387c to your computer and use it in GitHub Desktop.
Save ptflp/412bd3d5785d3162035eeb3f792d387c to your computer and use it in GitHub Desktop.
Upload file through telegram bot to chat id
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
func main() {
token := "1111:asfasfa" //change token
chatID := "111111" // change chat id
method := "sendDocument"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
path := "/tmp/dat"
file, err := os.Open(path)
if err != nil {
return
}
defer file.Close()
part, err := writer.CreateFormFile("document", filepath.Base(path))
if err != nil {
return
}
if _, err = io.Copy(part, file); err != nil {
return
}
writer.WriteField("chat_id", chatID)
if err := writer.Close(); err != nil {
return
}
url := fmt.Sprintf("https://api.telegram.org/bot%s/%s", token, method)
req, err := http.NewRequest("POST", url, body)
if err != nil {
return
}
req.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
bodyString := string(bodyBytes)
fmt.Println(bodyString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment