├── .github ├── dependabot.yml └── workflows │ └── go.yml ├── go.mod ├── pkg ├── categories │ ├── methods │ │ ├── device.go │ │ ├── read_mark.go │ │ ├── base_category.go │ │ ├── queues.go │ │ ├── partner.go │ │ ├── receiving.go │ │ ├── journals.go │ │ ├── status.go │ │ ├── account.go │ │ ├── service.go │ │ ├── groups.go │ │ └── sending.go │ └── categories.go └── api │ ├── webhook.go │ ├── http.go │ └── api.go ├── go.sum ├── examples ├── webhook │ └── main.go ├── checkWhatsApp │ └── main.go ├── sendTyping │ └── main.go ├── createInstance │ └── main.go ├── createGroup │ └── main.go ├── sendFileByUpload │ └── main.go ├── sendMessage │ └── main.go ├── sendStatus │ └── main.go ├── sendFileByURL │ └── main.go ├── sendPoll │ └── main.go ├── sendInteractiveButtonsReply │ └── main.go ├── uploadFile │ └── main.go └── sendInteractiveButtons │ └── main.go ├── .gitignore ├── LICENSE ├── docs └── README_RU.md └── README.md /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gomod" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | allow: 8 | - dependency-type: "all" 9 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/green-api/whatsapp-api-client-golang 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.23.2 6 | 7 | require github.com/gabriel-vasile/mimetype v1.4.3 8 | 9 | require golang.org/x/net v0.38.0 // indirect 10 | 11 | replace github.com/green-api/whatsapp-api-client-golang => . 12 | -------------------------------------------------------------------------------- /pkg/categories/methods/device.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | import "errors" 4 | 5 | type DeviceCategory struct { 6 | GreenAPI GreenAPIInterface 7 | } 8 | 9 | func (c DeviceCategory) GetDeviceInfo() (map[string]any, error) { 10 | return nil, errors.New("method GetDeviceInfo() is deprecated and disabled") 11 | } 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= 2 | github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= 3 | golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= 4 | golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= 5 | -------------------------------------------------------------------------------- /pkg/categories/methods/read_mark.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type ReadMarkCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // ReadChat is designed to mark chat messages as read. 8 | // https://green-api.com/en/docs/api/marks/ReadChat/ 9 | func (c ReadMarkCategory) ReadChat(parameters map[string]any) (map[string]any, error) { 10 | return c.GreenAPI.Request("POST", "readChat", parameters, "") 11 | } 12 | -------------------------------------------------------------------------------- /examples/webhook/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | GreenAPIWebhook := GreenAPI.Webhook() 16 | 17 | GreenAPIWebhook.Start(func(body map[string]any) { 18 | log.Println(body) 19 | }) 20 | } 21 | -------------------------------------------------------------------------------- /examples/checkWhatsApp/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Service().CheckWhatsapp(11001234567) 16 | if err != nil { 17 | log.Fatal(err) 18 | } 19 | 20 | log.Println(response) 21 | } 22 | -------------------------------------------------------------------------------- /examples/sendTyping/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Service().SendTyping("11001234567@c.us") 16 | if err != nil { 17 | log.Fatal(err) 18 | } 19 | 20 | log.Println(response) 21 | } 22 | -------------------------------------------------------------------------------- /examples/createInstance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | Partner := api.GreenAPI{ 11 | PartnerToken: "gac.1234567891234567891234567891213456789", 12 | } 13 | 14 | response, err := Partner.Methods().Partner().CreateInstance(map[string]any{ 15 | "stateWebhook": "yes", 16 | "incomingWebhook": "yes", 17 | }) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | 22 | log.Println(response) 23 | } 24 | -------------------------------------------------------------------------------- /examples/createGroup/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Groups().CreateGroup("groupName", []string{ 16 | "11001234567@c.us", 17 | "11002345678@c.us", 18 | }) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | 23 | log.Println(response) 24 | } 25 | -------------------------------------------------------------------------------- /examples/sendFileByUpload/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Sending().SendFileByUpload("example.png", map[string]any{ 16 | "chatId": "11001234567@c.us", 17 | }) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | 22 | log.Println(response) 23 | } 24 | -------------------------------------------------------------------------------- /pkg/categories/methods/base_category.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type GreenAPIInterface interface { 4 | Request(method, APIMethod string, data map[string]any, filePath string) (map[string]any, error) 5 | RawRequest(method, APIMethod string, data map[string]any, filePath string) (any, error) 6 | ArrayRequest(method, APIMethod string, data map[string]any, filePath string) ([]any, error) 7 | PartnerRequest(method, APIMethod string, data map[string]any, filePath string) (map[string]any, error) 8 | ArrayPartnerRequest(method, APIMethod string, data map[string]any, filePath string) ([]any, error) 9 | } 10 | -------------------------------------------------------------------------------- /examples/sendMessage/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Sending().SendMessage(map[string]any{ 16 | "chatId": "11001234567@c.us", 17 | "message": "Any message", 18 | "typingTime": 5000, 19 | }) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | 24 | log.Println(response) 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: 6 | - "master" 7 | pull_request: 8 | branches: 9 | - "master" 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | go-version: [ "1.23" ] 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Setup Go ${{ matrix.go-version }} 22 | uses: actions/setup-go@v4 23 | with: 24 | go-version: ${{ matrix.go-version }} 25 | 26 | - name: Build 27 | run: go build -v ./... 28 | 29 | - name: Test 30 | run: go test -v ./... 31 | -------------------------------------------------------------------------------- /examples/sendStatus/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Status().SendTextStatus(map[string]any{ 16 | "message": "I sent this status using Green Api Go SDK!", 17 | "backgroundColor": "#87CEEB", 18 | "font": "SERIF", 19 | }) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | 24 | log.Println(response) 25 | } 26 | -------------------------------------------------------------------------------- /examples/sendFileByURL/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Sending().SendFileByUrl(map[string]any{ 16 | "chatId": "11001234567@c.us", 17 | "urlFile": "https://go.dev/blog/go-brand/Go-Logo/JPG/Go-Logo_Aqua.jpg", 18 | "fileName": "Go-Logo.jpg", 19 | "typingTime": 5000, 20 | "typingType": "recording", 21 | }) 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | 26 | log.Println(response) 27 | } 28 | -------------------------------------------------------------------------------- /pkg/categories/methods/queues.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type QueuesCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // ShowMessagesQueue is designed to get the list of messages 8 | // that are in the queue to be sent. 9 | // https://green-api.com/en/docs/api/queues/ShowMessagesQueue/ 10 | func (c QueuesCategory) ShowMessagesQueue() ([]any, error) { 11 | return c.GreenAPI.ArrayRequest("GET", "showMessagesQueue", nil, "") 12 | } 13 | 14 | // ClearMessagesQueue is designed to clear the queue of messages to be sent. 15 | // https://green-api.com/en/docs/api/queues/ClearMessagesQueue/ 16 | func (c QueuesCategory) ClearMessagesQueue() (map[string]any, error) { 17 | return c.GreenAPI.Request("GET", "clearMessagesQueue", nil, "") 18 | } 19 | -------------------------------------------------------------------------------- /examples/sendPoll/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | response, err := GreenAPI.Methods().Sending().SendPoll(map[string]any{ 16 | "chatId": "11001234567@c.us", 17 | "message": "Please choose a color:", 18 | "options": []map[string]any{ 19 | { 20 | "optionName": "Red", 21 | }, 22 | { 23 | "optionName": "Green", 24 | }, 25 | { 26 | "optionName": "Blue", 27 | }, 28 | }, 29 | }) 30 | if err != nil { 31 | log.Fatal(err) 32 | } 33 | 34 | log.Println(response) 35 | } 36 | -------------------------------------------------------------------------------- /examples/sendInteractiveButtonsReply/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | replyButtons := []map[string]any{ 16 | { 17 | "buttonId": "1", 18 | "buttonText": "Reply 1", 19 | }, 20 | { 21 | "buttonId": "2", 22 | "buttonText": "Reply 2", 23 | }, 24 | } 25 | 26 | parameters := map[string]any{ 27 | "chatId": "11001234567@c.us", 28 | "body": "Choose an option:", 29 | "buttons": replyButtons, 30 | } 31 | 32 | response, err := GreenAPI.Methods().Sending().SendInteractiveButtonsReply(parameters) 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | 37 | log.Println(response) 38 | } 39 | -------------------------------------------------------------------------------- /pkg/api/webhook.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import "time" 4 | 5 | type GreenAPIWebhook struct { 6 | GreenAPI GreenAPI 7 | 8 | ErrorChannel chan error 9 | } 10 | 11 | var running = true 12 | 13 | func (w GreenAPIWebhook) Start(handler func(map[string]any)) { 14 | for running { 15 | response, err := w.GreenAPI.Methods().Receiving().ReceiveNotification() 16 | if err != nil { 17 | w.ErrorChannel <- err 18 | 19 | time.Sleep(time.Second * 5) 20 | 21 | continue 22 | } 23 | 24 | if response != nil { 25 | body := response["body"] 26 | handler(body.(map[string]any)) 27 | 28 | receiptId := int(response["receiptId"].(float64)) 29 | _, err = w.GreenAPI.Methods().Receiving().DeleteNotification(receiptId) 30 | if err != nil { 31 | w.ErrorChannel <- err 32 | 33 | time.Sleep(time.Second * 5) 34 | 35 | continue 36 | } 37 | } 38 | } 39 | } 40 | 41 | func (w GreenAPIWebhook) Stop() { 42 | running = false 43 | } 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | 11 | # Test binary, built with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | 17 | # Dependency directories (remove the comment below to include it) 18 | # vendor/ 19 | 20 | # Go workspace file 21 | go.work 22 | 23 | # GoLand 24 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 25 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 26 | # and can be added to the global gitignore or merged into this file. For a more nuclear 27 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 28 | .idea/ 29 | -------------------------------------------------------------------------------- /examples/uploadFile/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "path" 7 | 8 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 9 | ) 10 | 11 | func main() { 12 | GreenAPI := api.GreenAPI{ 13 | IDInstance: "1101000001", 14 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 15 | } 16 | 17 | uploadFileResponse, err := GreenAPI.Methods().Sending().UploadFile("example.png") 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | 22 | log.Println(uploadFileResponse) 23 | 24 | urlFile := uploadFileResponse["urlFile"].(string) 25 | request, _ := http.NewRequest("GET", urlFile, nil) 26 | fileName := path.Base(request.URL.Path) 27 | 28 | sendFileByUrlResponse, err := GreenAPI.Methods().Sending().SendFileByUrl(map[string]any{ 29 | "chatId": "11001234567@c.us", 30 | "urlFile": urlFile, 31 | "fileName": fileName, 32 | }) 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | 37 | log.Println(sendFileByUrlResponse) 38 | } 39 | -------------------------------------------------------------------------------- /pkg/categories/methods/partner.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type PartnerCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // CreateInstance is aimed to create an instace using partner account. 8 | // https://green-api.com/en/docs/partners/createInstance/ 9 | func (c PartnerCategory) CreateInstance(parameters map[string]any) (map[string]any, error) { 10 | return c.GreenAPI.PartnerRequest("POST", "createInstance", parameters, "") 11 | } 12 | 13 | // DeleteInstanceAccount is aimed to delete an instance using partner account. 14 | // https://green-api.com/en/docs/partners/deleteInstanceAccount/ 15 | func (c PartnerCategory) DeleteInstanceAccount(idInstance int) (map[string]any, error) { 16 | return c.GreenAPI.PartnerRequest("POST", "deleteInstanceAccount", map[string]any{"idInstance": idInstance}, "") 17 | } 18 | 19 | // GetInstances is aimed to get all instances on a partner account. 20 | // https://green-api.com/en/docs/partners/getInstances/ 21 | func (c PartnerCategory) GetInstances() ([]any, error) { 22 | return c.GreenAPI.ArrayPartnerRequest("GET", "getInstances", nil, "") 23 | } 24 | -------------------------------------------------------------------------------- /examples/sendInteractiveButtons/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 7 | ) 8 | 9 | func main() { 10 | GreenAPI := api.GreenAPI{ 11 | IDInstance: "1101000001", 12 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 13 | } 14 | 15 | buttons := []map[string]any{ 16 | { 17 | "type": "copy", 18 | "buttonId": "1", 19 | "buttonText": "Copy me", 20 | "copyCode": "3333", 21 | }, 22 | { 23 | "type": "call", 24 | "buttonId": "2", 25 | "buttonText": "Call me", 26 | "phoneNumber": "79123456789", 27 | }, 28 | { 29 | "type": "url", 30 | "buttonId": "3", 31 | "buttonText": "Green-api", 32 | "url": "https://green-api.com", 33 | }, 34 | } 35 | 36 | parameters := map[string]any{ 37 | "chatId": "11001234567@c.us", 38 | "body": "Main message text", 39 | "header": "Message header", 40 | "footer": "Message footer", 41 | "buttons": buttons, 42 | } 43 | response, err := GreenAPI.Methods().Sending().SendInteractiveButtons(parameters) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | 48 | log.Println(response) 49 | } 50 | -------------------------------------------------------------------------------- /pkg/categories/methods/receiving.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type ReceivingCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // ReceiveNotification is designed to receive a single incoming notification 8 | // from the notification queue. 9 | // https://green-api.com/en/docs/api/receiving/technology-http-api/ReceiveNotification/ 10 | func (c ReceivingCategory) ReceiveNotification() (map[string]any, error) { 11 | response, err := c.GreenAPI.RawRequest("GET", "receiveNotification", nil, "") 12 | 13 | if response != nil { 14 | return response.(map[string]any), err 15 | } 16 | 17 | return nil, err 18 | } 19 | 20 | // DeleteNotification is designed to remove an incoming notification 21 | // from the notification queue. 22 | // https://green-api.com/en/docs/api/receiving/technology-http-api/DeleteNotification/ 23 | func (c ReceivingCategory) DeleteNotification(receiptId int) (map[string]any, error) { 24 | return c.GreenAPI.Request("DELETE", "deleteNotification", map[string]any{ 25 | "receiptId": receiptId, 26 | }, "") 27 | } 28 | 29 | // DownloadFile is for downloading received and sent files. 30 | // https://green-api.com/en/docs/api/receiving/files/DownloadFile/ 31 | func (c ReceivingCategory) DownloadFile(chatId, idMessage string) (map[string]any, error) { 32 | return c.GreenAPI.Request("POST", "downloadFile", map[string]any{ 33 | "chatId": chatId, 34 | "idMessage": idMessage, 35 | }, "") 36 | } 37 | -------------------------------------------------------------------------------- /pkg/categories/methods/journals.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type JournalsCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // GetChatHistory returns the chat message history. 8 | // https://green-api.com/en/docs/api/journals/GetChatHistory/ 9 | func (c JournalsCategory) GetChatHistory(parameters map[string]any) ([]any, error) { 10 | return c.GreenAPI.ArrayRequest("POST", "getChatHistory", parameters, "") 11 | } 12 | 13 | // GetMessage returns a chat message. 14 | // https://green-api.com/en/docs/api/journals/GetMessage/ 15 | func (c JournalsCategory) GetMessage(chatId, idMessage string) (map[string]any, error) { 16 | return c.GreenAPI.Request("POST", "getMessage", map[string]any{ 17 | "chatId": chatId, 18 | "idMessage": idMessage, 19 | }, "") 20 | } 21 | 22 | // LastIncomingMessages returns the most recent incoming messages 23 | // of the account. 24 | // https://green-api.com/en/docs/api/journals/LastIncomingMessages/ 25 | func (c JournalsCategory) LastIncomingMessages(parameters map[string]any) ([]any, error) { 26 | return c.GreenAPI.ArrayRequest("GET", "lastIncomingMessages", parameters, "") 27 | } 28 | 29 | // LastOutgoingMessages returns the last sent messages of the account. 30 | // https://green-api.com/en/docs/api/journals/LastOutgoingMessages/ 31 | func (c JournalsCategory) LastOutgoingMessages(parameters map[string]any) ([]any, error) { 32 | return c.GreenAPI.ArrayRequest("GET", "lastOutgoingMessages", parameters, "") 33 | } 34 | -------------------------------------------------------------------------------- /pkg/categories/methods/status.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | type StatusCategory struct { 8 | GreenAPI GreenAPIInterface 9 | } 10 | 11 | // SentTextStatus is aimed for sending a text status 12 | // https://green-api.com/en/docs/api/statuses/SendTextStatus/ 13 | func (c StatusCategory) SendTextStatus(parameters map[string]any) (map[string]any, error) { 14 | return c.GreenAPI.Request("POST", "sendTextStatus", parameters, "") 15 | } 16 | 17 | // SendVoiceStatus is aimed for sending a voice status 18 | // https://green-api.com/en/docs/api/statuses/SendVoiceStatus/ 19 | func (c StatusCategory) SendVoiceStatus(parameters map[string]any) (map[string]any, error) { 20 | return c.GreenAPI.Request("POST", "sendVoiceStatus", parameters, "") 21 | } 22 | 23 | // SendMediaStatus is aimed for sending a pictures or video status 24 | // https://green-api.com/en/docs/api/statuses/SendMediaStatus/ 25 | func (c StatusCategory) SendMediaStatus(parameters map[string]any) (map[string]any, error) { 26 | return c.GreenAPI.Request("POST", "sendMediaStatus", parameters, "") 27 | } 28 | 29 | // GetOutgoingStatuses returns the outgoing statuses of the account 30 | // https://green-api.com/en/docs/api/statuses/GetOutgoingStatuses/ 31 | func (c StatusCategory) GetOutgoingStatuses(minutes int) ([]any, error) { 32 | data := map[string]any{"minutes": strconv.Itoa(minutes)} 33 | if minutes == 0 { 34 | data = map[string]any{} 35 | } 36 | return c.GreenAPI.ArrayRequest("GET", "getOutgoingStatuses", data, "") 37 | } 38 | 39 | // GetIncomingStatuses returns the incoming status messages of the account 40 | // https://green-api.com/en/docs/api/statuses/GetIncomingStatuses/ 41 | func (c StatusCategory) GetIncomingStatuses(minutes int) ([]any, error) { 42 | data := map[string]any{"minutes": strconv.Itoa(minutes)} 43 | if minutes == 0 { 44 | data = map[string]any{} 45 | } 46 | return c.GreenAPI.ArrayRequest("GET", "getIncomingStatuses", data, "") 47 | } 48 | 49 | // GetStatusStatistic returns an array of recipients marked for a given status. 50 | // https://green-api.com/en/docs/api/statuses/GetStatusStatistic/ 51 | func (c StatusCategory) GetStatusStatistic(idMessage string) ([]any, error) { 52 | return c.GreenAPI.ArrayRequest("GET", "getStatusStatistic", map[string]any{ 53 | "idMessage": idMessage, 54 | }, "") 55 | } 56 | 57 | // DeleteStatus is aimed for deleting status. 58 | // https://green-api.com/en/docs/api/statuses/DeleteStatus/ 59 | func (c StatusCategory) DeleteStatus(idMessage string) (map[string]any, error) { 60 | _, err := c.GreenAPI.Request("POST", "deleteStatus", map[string]any{ 61 | "idMessage": idMessage, 62 | }, "") 63 | if err != nil { 64 | return nil, err 65 | } 66 | return map[string]any{"deletedStatus": idMessage}, nil 67 | } 68 | -------------------------------------------------------------------------------- /pkg/categories/methods/account.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type AccountCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // GetSettings is designed to get the current settings of the account. 8 | // https://green-api.com/en/docs/api/account/GetSettings/ 9 | func (c AccountCategory) GetSettings() (map[string]any, error) { 10 | return c.GreenAPI.Request("GET", "getSettings", nil, "") 11 | } 12 | 13 | // GetWaSettings is designed to get information about the WhatsApp account. 14 | // https://green-api.com/en/docs/api/account/GetWaSettings/ 15 | func (c AccountCategory) GetWaSettings() (map[string]any, error) { 16 | return c.GreenAPI.Request("GET", "getWaSettings", nil, "") 17 | } 18 | 19 | // SetSettings is for setting the account settings. 20 | // https://green-api.com/en/docs/api/account/SetSettings/ 21 | func (c AccountCategory) SetSettings(parameters map[string]any) (map[string]any, error) { 22 | return c.GreenAPI.Request("POST", "setSettings", parameters, "") 23 | } 24 | 25 | // GetStateInstance is designed to get the state of the account. 26 | // https://green-api.com/en/docs/api/account/GetStateInstance/ 27 | func (c AccountCategory) GetStateInstance() (map[string]any, error) { 28 | return c.GreenAPI.Request("GET", "getStateInstance", nil, "") 29 | } 30 | 31 | // GetStatusInstance is designed to get the socket connection state 32 | // of the account instance with WhatsApp. 33 | // https://green-api.com/en/docs/api/account/GetStatusInstance/ 34 | func (c AccountCategory) GetStatusInstance() (map[string]any, error) { 35 | return c.GreenAPI.Request("GET", "getStatusInstance", nil, "") 36 | } 37 | 38 | // Reboot is designed to restart the account. 39 | // https://green-api.com/en/docs/api/account/Reboot/ 40 | func (c AccountCategory) Reboot() (map[string]any, error) { 41 | return c.GreenAPI.Request("GET", "reboot", nil, "") 42 | } 43 | 44 | // Logout is designed to unlogin the account. 45 | // https://green-api.com/en/docs/api/account/Logout/ 46 | func (c AccountCategory) Logout() (map[string]any, error) { 47 | return c.GreenAPI.Request("GET", "logout", nil, "") 48 | } 49 | 50 | // QR is designed to get a QR code. 51 | // https://green-api.com/en/docs/api/account/QR/ 52 | func (c AccountCategory) QR() (map[string]any, error) { 53 | return c.GreenAPI.Request("GET", "qr", nil, "") 54 | } 55 | 56 | // SetProfilePicture is designed to set the avatar of the account. 57 | // https://green-api.com/en/docs/api/account/SetProfilePicture/ 58 | func (c AccountCategory) SetProfilePicture(filePath string) (map[string]any, error) { 59 | return c.GreenAPI.Request("POST", "setProfilePicture", nil, filePath) 60 | } 61 | 62 | // GetAuthorizationCode is designed to authorize an instance by phone number. 63 | // https://green-api.com/en/docs/api/account/GetAuthorizationCode/ 64 | func (c AccountCategory) GetAuthorizationCode(phoneNumber int) (map[string]any, error) { 65 | return c.GreenAPI.Request("POST", "getAuthorizationCode", map[string]any{ 66 | "phoneNumber": phoneNumber, 67 | }, "") 68 | } 69 | -------------------------------------------------------------------------------- /pkg/categories/methods/service.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type ServiceCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // CheckWhatsapp checks if there is a WhatsApp account on the phone number. 8 | // https://green-api.com/en/docs/api/service/CheckWhatsapp/ 9 | func (c ServiceCategory) CheckWhatsapp(phoneNumber int) (map[string]any, error) { 10 | return c.GreenAPI.Request("POST", "checkWhatsapp", map[string]any{ 11 | "phoneNumber": phoneNumber, 12 | }, "") 13 | } 14 | 15 | // GetAvatar returns the avatar of the correspondent or group chat. 16 | // https://green-api.com/en/docs/api/service/GetAvatar/ 17 | func (c ServiceCategory) GetAvatar(chatId string) (map[string]any, error) { 18 | return c.GreenAPI.Request("POST", "getAvatar", map[string]any{ 19 | "chatId": chatId, 20 | }, "") 21 | } 22 | 23 | // GetContacts is designed to get a list of contacts of the current account. 24 | // https://green-api.com/en/docs/api/service/GetContacts/ 25 | func (c ServiceCategory) GetContacts() ([]any, error) { 26 | return c.GreenAPI.ArrayRequest("GET", "getContacts", nil, "") 27 | } 28 | 29 | // GetContactInfo is designed to obtain information about the contact. 30 | // https://green-api.com/en/docs/api/service/GetContactInfo/ 31 | func (c ServiceCategory) GetContactInfo(chatId string) (map[string]any, error) { 32 | return c.GreenAPI.Request("POST", "getContactInfo", map[string]any{ 33 | "chatId": chatId, 34 | }, "") 35 | } 36 | 37 | // DeleteMessage deletes the message from chat. 38 | // https://green-api.com/en/docs/api/service/deleteMessage/ 39 | func (c ServiceCategory) DeleteMessage(chatId, idMessage string) (map[string]any, error) { 40 | return c.GreenAPI.Request("POST", "deleteMessage", map[string]any{ 41 | "chatId": chatId, 42 | "idMessage": idMessage, 43 | }, "") 44 | } 45 | 46 | // ArchiveChat archives the chat. 47 | // https://green-api.com/en/docs/api/service/archiveChat/ 48 | func (c ServiceCategory) ArchiveChat(chatId string) (map[string]any, error) { 49 | return c.GreenAPI.Request("POST", "archiveChat", map[string]any{ 50 | "chatId": chatId, 51 | }, "") 52 | } 53 | 54 | // UnarchiveChat unarchives the chat. 55 | // https://green-api.com/en/docs/api/service/unarchiveChat/ 56 | func (c ServiceCategory) UnarchiveChat(chatId string) (map[string]any, error) { 57 | return c.GreenAPI.Request("POST", "unarchiveChat", map[string]any{ 58 | "chatId": chatId, 59 | }, "") 60 | } 61 | 62 | // SetDisappearingChat is designed to change the settings of disappearing messages in chats. 63 | // https://green-api.com/en/docs/api/service/SetDisappearingChat/ 64 | func (c ServiceCategory) SetDisappearingChat(parameters map[string]any) (map[string]any, error) { 65 | return c.GreenAPI.Request("POST", "setDisappearingChat", parameters, "") 66 | } 67 | 68 | // SendTyping is designed to send a notification about typing or recording audio in a chat. 69 | // https://green-api.com/en/docs/api/service/SendTyping/ 70 | func (c ServiceCategory) SendTyping(chatId string) (map[string]any, error) { 71 | return c.GreenAPI.Request("POST", "sendTyping", map[string]any{ 72 | "chatId": chatId, 73 | }, "") 74 | } 75 | -------------------------------------------------------------------------------- /pkg/categories/categories.go: -------------------------------------------------------------------------------- 1 | package categories 2 | 3 | import "github.com/green-api/whatsapp-api-client-golang/pkg/categories/methods" 4 | 5 | type GreenAPICategories struct { 6 | GreenAPI methods.GreenAPIInterface 7 | } 8 | 9 | // Account category presents methods for working with the account. 10 | // https://green-api.com/en/docs/api/account/ 11 | func (c GreenAPICategories) Account() methods.AccountCategory { 12 | return methods.AccountCategory{GreenAPI: c.GreenAPI} 13 | } 14 | 15 | // Device category is deprecated 16 | func (c GreenAPICategories) Device() methods.DeviceCategory { 17 | return methods.DeviceCategory{GreenAPI: c.GreenAPI} 18 | } 19 | 20 | // Groups category presents methods for working with group chats. 21 | // https://green-api.com/en/docs/api/groups/ 22 | func (c GreenAPICategories) Groups() methods.GroupsCategory { 23 | return methods.GroupsCategory{GreenAPI: c.GreenAPI} 24 | } 25 | 26 | // Journals present methods for working with incoming and outgoing messages. 27 | // https://green-api.com/en/docs/api/journals/ 28 | func (c GreenAPICategories) Journals() methods.JournalsCategory { 29 | return methods.JournalsCategory{GreenAPI: c.GreenAPI} 30 | } 31 | 32 | // Queues category presents methods for working with a messages queue. 33 | // https://green-api.com/en/docs/api/queues/ 34 | func (c GreenAPICategories) Queues() methods.QueuesCategory { 35 | return methods.QueuesCategory{GreenAPI: c.GreenAPI} 36 | } 37 | 38 | // ReadMark category presents methods for working with chat read mark. 39 | // https://green-api.com/en/docs/api/marks/ 40 | func (c GreenAPICategories) ReadMark() methods.ReadMarkCategory { 41 | return methods.ReadMarkCategory{GreenAPI: c.GreenAPI} 42 | } 43 | 44 | // Receiving category presents methods for working with receiving events. 45 | // https://green-api.com/en/docs/api/receiving/ 46 | func (c GreenAPICategories) Receiving() methods.ReceivingCategory { 47 | return methods.ReceivingCategory{GreenAPI: c.GreenAPI} 48 | } 49 | 50 | // Sending category presents methods for sending different messages. 51 | // https://green-api.com/en/docs/api/sending/ 52 | func (c GreenAPICategories) Sending() methods.SendingCategory { 53 | return methods.SendingCategory{GreenAPI: c.GreenAPI} 54 | } 55 | 56 | // Service category presents different service methods. 57 | // https://green-api.com/en/docs/api/service/ 58 | func (c GreenAPICategories) Service() methods.ServiceCategory { 59 | return methods.ServiceCategory{GreenAPI: c.GreenAPI} 60 | } 61 | 62 | // Partner category presents exclusive methods for partners. 63 | // The partnership scheme involves deeper integration with the service 64 | // and working with a larger number of instances on your side: 65 | // 66 | // * Instance management via API 67 | // * Postpaid billing system (starting from the second month of operation) 68 | // * Daily billing (for created and not deleted instances) 69 | // * Dedicated support line 70 | // For questions regarding connection to the partnership scheme 71 | // and additional conditions, please contact us via email 72 | // at support@green-api.com or via chat on the website. 73 | // https://green-api.com/en/docs/partners/ 74 | func (c GreenAPICategories) Partner() methods.PartnerCategory { 75 | return methods.PartnerCategory{GreenAPI: c.GreenAPI} 76 | } 77 | 78 | // Status category presents methods for statuses 79 | // https://green-api.com/en/docs/api/statuses/ 80 | func (c GreenAPICategories) Status() methods.StatusCategory { 81 | return methods.StatusCategory{GreenAPI: c.GreenAPI} 82 | } 83 | -------------------------------------------------------------------------------- /pkg/categories/methods/groups.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type GroupsCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // CreateGroup is designed to create a group chat. 8 | // https://green-api.com/en/docs/api/groups/CreateGroup/ 9 | func (c GroupsCategory) CreateGroup(groupName string, chatIds []string) (map[string]any, error) { 10 | return c.GreenAPI.Request("POST", "createGroup", map[string]any{ 11 | "groupName": groupName, 12 | "chatIds": chatIds, 13 | }, "") 14 | } 15 | 16 | // UpdateGroupName changes the name of the group chat. 17 | // https://green-api.com/en/docs/api/groups/UpdateGroupName/ 18 | func (c GroupsCategory) UpdateGroupName(groupId, groupName string) (map[string]any, error) { 19 | return c.GreenAPI.Request("POST", "updateGroupName", map[string]any{ 20 | "groupId": groupId, 21 | "groupName": groupName, 22 | }, "") 23 | } 24 | 25 | // GetGroupData gets group chat data. 26 | // https://green-api.com/en/docs/api/groups/GetGroupData/ 27 | func (c GroupsCategory) GetGroupData(groupId string) (map[string]any, error) { 28 | return c.GreenAPI.Request("POST", "getGroupData", map[string]any{ 29 | "groupId": groupId, 30 | }, "") 31 | } 32 | 33 | // AddGroupParticipant adds a participant to the group chat. 34 | // https://green-api.com/en/docs/api/groups/AddGroupParticipant/ 35 | func (c GroupsCategory) AddGroupParticipant(groupId, participantChatId string) (map[string]any, error) { 36 | return c.GreenAPI.Request("POST", "addGroupParticipant", map[string]any{ 37 | "groupId": groupId, 38 | "participantChatId": participantChatId, 39 | }, "") 40 | } 41 | 42 | // RemoveGroupParticipant removes the participant from the group chat. 43 | // https://green-api.com/en/docs/api/groups/RemoveGroupParticipant/ 44 | func (c GroupsCategory) RemoveGroupParticipant(groupId, participantChatId string) (map[string]any, error) { 45 | return c.GreenAPI.Request("POST", "removeGroupParticipant", map[string]any{ 46 | "groupId": groupId, 47 | "participantChatId": participantChatId, 48 | }, "") 49 | } 50 | 51 | // SetGroupAdmin designates a member of a group chat as an administrator. 52 | // https://green-api.com/en/docs/api/groups/SetGroupAdmin/ 53 | func (c GroupsCategory) SetGroupAdmin(groupId, participantChatId string) (map[string]any, error) { 54 | return c.GreenAPI.Request("POST", "setGroupAdmin", map[string]any{ 55 | "groupId": groupId, 56 | "participantChatId": participantChatId, 57 | }, "") 58 | } 59 | 60 | // RemoveAdmin deprives the participant of group chat administration rights. 61 | // https://green-api.com/en/docs/api/groups/RemoveAdmin/ 62 | func (c GroupsCategory) RemoveAdmin(groupId, participantChatId string) (map[string]any, error) { 63 | return c.GreenAPI.Request("POST", "removeAdmin", map[string]any{ 64 | "groupId": groupId, 65 | "participantChatId": participantChatId, 66 | }, "") 67 | } 68 | 69 | // SetGroupPicture sets the avatar of the group. 70 | // https://green-api.com/en/docs/api/groups/SetGroupPicture/ 71 | func (c GroupsCategory) SetGroupPicture(filePath, groupId string) (map[string]any, error) { 72 | return c.GreenAPI.Request("POST", "setGroupPicture", map[string]any{ 73 | "groupId": groupId, 74 | }, filePath) 75 | } 76 | 77 | // LeaveGroup logs the user of the current account out of the group chat. 78 | // https://green-api.com/en/docs/api/groups/LeaveGroup/ 79 | func (c GroupsCategory) LeaveGroup(groupId string) (map[string]any, error) { 80 | return c.GreenAPI.Request("POST", "leaveGroup", map[string]any{ 81 | "groupId": groupId, 82 | }, "") 83 | } 84 | -------------------------------------------------------------------------------- /pkg/api/http.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "mime/multipart" 9 | "net/http" 10 | "os" 11 | "path/filepath" 12 | "strings" 13 | 14 | "github.com/gabriel-vasile/mimetype" 15 | ) 16 | 17 | func executeRequest(method, url string, data map[string]any, filePath string) (any, error) { 18 | client := &http.Client{} 19 | 20 | req, err := getRequest(method, url, data, filePath) 21 | if strings.Contains(url, "uploadFile") { 22 | req, err = getUploadFileRequest(method, url, filePath) 23 | } 24 | 25 | if err != nil { 26 | return nil, err 27 | } 28 | 29 | resp, err := client.Do(req) 30 | if err != nil { 31 | return nil, err 32 | } 33 | 34 | return getResponse(resp) 35 | } 36 | 37 | func getRequest(method, url string, data map[string]any, filePath string) (*http.Request, error) { 38 | if data == nil || method == http.MethodGet || method == http.MethodDelete { 39 | req, err := http.NewRequest(method, url, nil) 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | return req, nil 45 | } 46 | 47 | if filePath == "" { 48 | buf, err := json.Marshal(data) 49 | if err != nil { 50 | return nil, err 51 | } 52 | 53 | req, err := http.NewRequest(method, url, bytes.NewBuffer(buf)) 54 | if err != nil { 55 | return nil, err 56 | } 57 | 58 | req.Header.Set("Content-Type", "application/json") 59 | 60 | return req, nil 61 | } 62 | 63 | buffer := &bytes.Buffer{} 64 | 65 | writer := multipart.NewWriter(buffer) 66 | 67 | for key, value := range data { 68 | err := writer.WriteField(key, value.(string)) 69 | if err != nil { 70 | return nil, err 71 | } 72 | } 73 | 74 | file, err := os.Open(filePath) 75 | if err != nil { 76 | return nil, err 77 | } 78 | 79 | part, err := writer.CreateFormFile("file", filePath) 80 | if err != nil { 81 | return nil, err 82 | } 83 | 84 | _, err = io.Copy(part, file) 85 | if err != nil { 86 | return nil, err 87 | } 88 | 89 | err = file.Close() 90 | if err != nil { 91 | return nil, err 92 | } 93 | 94 | err = writer.Close() 95 | if err != nil { 96 | return nil, err 97 | } 98 | 99 | req, err := http.NewRequest(method, url, buffer) 100 | if err != nil { 101 | return nil, err 102 | } 103 | 104 | req.Header.Set("Content-Type", writer.FormDataContentType()) 105 | 106 | return req, nil 107 | } 108 | 109 | func getUploadFileRequest(method, url string, filePath string) (*http.Request, error) { 110 | buf, err := os.ReadFile(filePath) 111 | if err != nil { 112 | return nil, err 113 | } 114 | 115 | req, err := http.NewRequest(method, url, bytes.NewBuffer(buf)) 116 | if err != nil { 117 | return nil, err 118 | } 119 | 120 | MIMEType := mimetype.Detect(buf).String() 121 | 122 | req.Header.Set("Content-Type", MIMEType) 123 | req.Header.Set("GA-Filename", filepath.Base(filePath)) 124 | 125 | return req, err 126 | } 127 | 128 | func getResponse(resp *http.Response) (any, error) { 129 | body, err := io.ReadAll(resp.Body) 130 | if err != nil { 131 | return nil, err 132 | } 133 | defer resp.Body.Close() 134 | 135 | if resp.StatusCode != http.StatusOK { 136 | if len(body) > 0 { 137 | return nil, fmt.Errorf("StatusCode: %d. Body: %s", resp.StatusCode, strings.TrimSpace(string(body))) 138 | } 139 | return nil, fmt.Errorf("StatusCode: %d", resp.StatusCode) 140 | } 141 | 142 | // amazing 143 | if strings.TrimSpace(string(body)) == `{"code":401,"description":"Unauthorized"}` { 144 | return nil, fmt.Errorf("StatusCode: %d. Body: %s", 401, strings.TrimSpace(string(body))) 145 | } 146 | 147 | if len(body) == 0 { 148 | return nil, nil 149 | } 150 | 151 | var data any 152 | err = json.Unmarshal(body, &data) 153 | if err != nil { 154 | return nil, err 155 | } 156 | 157 | return data, nil 158 | } 159 | -------------------------------------------------------------------------------- /pkg/api/api.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "strings" 7 | 8 | "github.com/green-api/whatsapp-api-client-golang/pkg/categories" 9 | ) 10 | 11 | type GreenAPI struct { 12 | URL string 13 | IDInstance string 14 | APITokenInstance string 15 | PartnerToken string 16 | } 17 | 18 | func (a GreenAPI) Methods() categories.GreenAPICategories { 19 | return categories.GreenAPICategories{GreenAPI: a} 20 | } 21 | 22 | func (a GreenAPI) Webhook() GreenAPIWebhook { 23 | return GreenAPIWebhook{ 24 | GreenAPI: a, 25 | ErrorChannel: make(chan error), 26 | } 27 | } 28 | 29 | func (a GreenAPI) Request(method, APIMethod string, data map[string]any, filePath string) (map[string]any, error) { 30 | url := a.getURL(method, APIMethod, data) 31 | response, err := executeRequest(method, url, data, filePath) 32 | 33 | if response == nil { 34 | return nil, err 35 | } 36 | 37 | responseMap, ok := response.(map[string]any) 38 | if !ok { 39 | return nil, fmt.Errorf("unexpected response type: %T, expected map[string]any", response) 40 | } 41 | 42 | return responseMap, err 43 | } 44 | 45 | func (a GreenAPI) PartnerRequest(method, APIMethod string, data map[string]any, filePath string) (map[string]any, error) { 46 | url, err := a.getPartnerURL(APIMethod) 47 | if err != nil { 48 | return nil, err 49 | } 50 | 51 | response, err := executeRequest(method, url, data, filePath) 52 | 53 | if response == nil { 54 | return nil, err 55 | } 56 | 57 | responseMap, ok := response.(map[string]any) 58 | if !ok { 59 | return nil, fmt.Errorf("unexpected response type: %T, expected map[string]any", response) 60 | } 61 | 62 | return responseMap, err 63 | } 64 | 65 | func (a GreenAPI) ArrayPartnerRequest(method, APIMethod string, data map[string]any, filePath string) ([]any, error) { 66 | url, err := a.getPartnerURL(APIMethod) 67 | if err != nil { 68 | return nil, err 69 | } 70 | 71 | response, err := executeRequest(method, url, data, filePath) 72 | 73 | return response.([]any), err 74 | } 75 | 76 | func (a GreenAPI) RawRequest(method, APIMethod string, data map[string]any, filePath string) (any, error) { 77 | url := a.getURL(method, APIMethod, data) 78 | 79 | return executeRequest(method, url, data, filePath) 80 | } 81 | 82 | func (a GreenAPI) ArrayRequest(method, APIMethod string, data map[string]any, filePath string) ([]any, error) { 83 | url := a.getURL(method, APIMethod, data) 84 | if APIMethod == "getOutgoingStatuses" || APIMethod == "getIncomingStatuses" { 85 | if data["minutes"] != nil { 86 | url = (url + "?minutes=" + data["minutes"].(string)) 87 | } 88 | } 89 | if APIMethod == "getStatusStatistic" { 90 | if data["idMessage"] != nil { 91 | url = (url + "?idMessage=" + data["idMessage"].(string)) 92 | } 93 | } 94 | response, err := executeRequest(method, url, data, filePath) 95 | 96 | return response.([]any), err 97 | } 98 | 99 | func (a GreenAPI) getURL(method, APIMethod string, data map[string]any) string { 100 | if a.URL != "" { 101 | return a.URL 102 | } 103 | 104 | var url strings.Builder 105 | 106 | if APIMethod == "SendFileByUpload" || APIMethod == "UploadFile" { 107 | url.WriteString("https://media.green-api.com") 108 | } else { 109 | url.WriteString("https://api.green-api.com") 110 | } 111 | 112 | url.WriteString("/") 113 | url.WriteString("waInstance") 114 | url.WriteString(a.IDInstance) 115 | url.WriteString("/") 116 | url.WriteString(APIMethod) 117 | url.WriteString("/") 118 | url.WriteString(a.APITokenInstance) 119 | 120 | if method == "DELETE" { 121 | url.WriteString("/") 122 | url.WriteString(strconv.Itoa(data["receiptId"].(int))) 123 | } 124 | 125 | return url.String() 126 | } 127 | 128 | func (a GreenAPI) getPartnerURL(APIMethod string) (string, error) { 129 | if a.PartnerToken == "" { 130 | return "", fmt.Errorf("error while generating URL: PartnerToken is empty") 131 | } 132 | 133 | var url strings.Builder 134 | 135 | url.WriteString("https://api.green-api.com") 136 | 137 | url.WriteString("/") 138 | url.WriteString("partner") 139 | url.WriteString("/") 140 | url.WriteString(APIMethod) 141 | url.WriteString("/") 142 | url.WriteString(a.PartnerToken) 143 | 144 | return url.String(), nil 145 | } 146 | -------------------------------------------------------------------------------- /pkg/categories/methods/sending.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | import "fmt" 4 | 5 | type SendingCategory struct { 6 | GreenAPI GreenAPIInterface 7 | } 8 | 9 | // SendMessage is designed to send a text message to a personal or group chat. 10 | // https://green-api.com/en/docs/api/sending/SendMessage/ 11 | func (c SendingCategory) SendMessage(parameters map[string]any) (map[string]any, error) { 12 | return c.GreenAPI.Request("POST", "sendMessage", parameters, "") 13 | } 14 | 15 | // The method is deprecated. Please use SendInteractiveButtons. 16 | func (c SendingCategory) SendButtons(parameters map[string]any) (map[string]any, error) { 17 | return c.GreenAPI.Request("POST", "sendButtons", parameters, "") 18 | } 19 | 20 | // The method is deprecated. Please use SendInteractiveButtonsReply. 21 | func (c SendingCategory) SendTemplateButtons(parameters map[string]any) (map[string]any, error) { 22 | return c.GreenAPI.Request("POST", "sendTemplateButtons", parameters, "") 23 | } 24 | 25 | // The method is deprecated. Please use SendMessage. 26 | func (c SendingCategory) SendListMessage(parameters map[string]any) (map[string]any, error) { 27 | return c.GreenAPI.Request("POST", "sendListMessage", parameters, "") 28 | } 29 | 30 | // SendFileByUpload is designed to send a file loaded through a form-data. 31 | // https://green-api.com/en/docs/api/sending/SendFileByUpload/ 32 | func (c SendingCategory) SendFileByUpload(filePath string, parameters map[string]any) (map[string]any, error) { 33 | return c.GreenAPI.Request("POST", "sendFileByUpload", parameters, filePath) 34 | } 35 | 36 | // SendFileByUrl is designed to send a file downloaded via a link. 37 | // https://green-api.com/en/docs/api/sending/SendFileByUrl/ 38 | func (c SendingCategory) SendFileByUrl(parameters map[string]any) (map[string]any, error) { 39 | return c.GreenAPI.Request("POST", "sendFileByUrl", parameters, "") 40 | } 41 | 42 | // SendLocation is designed to send a geolocation message. 43 | // https://green-api.com/en/docs/api/sending/SendLocation/ 44 | func (c SendingCategory) SendLocation(parameters map[string]any) (map[string]any, error) { 45 | return c.GreenAPI.Request("POST", "sendLocation", parameters, "") 46 | } 47 | 48 | // SendContact is for sending a message with a contact. 49 | // https://green-api.com/en/docs/api/sending/SendContact/ 50 | func (c SendingCategory) SendContact(parameters map[string]any) (map[string]any, error) { 51 | return c.GreenAPI.Request("POST", "sendContact", parameters, "") 52 | } 53 | 54 | // The method is deprecated. Please use SendMessage. 55 | func (c SendingCategory) SendLink(parameters map[string]any) (map[string]any, error) { 56 | return c.GreenAPI.Request("POST", "sendLink", parameters, "") 57 | } 58 | 59 | // ForwardMessages is designed for forwarding messages 60 | // to a personal or group chat. 61 | // https://green-api.com/en/docs/api/sending/ForwardMessages/ 62 | func (c SendingCategory) ForwardMessages(chatId, chatIdFrom string, messages []string) (map[string]any, error) { 63 | return c.GreenAPI.Request("POST", "forwardMessages", map[string]any{ 64 | "chatId": chatId, 65 | "chatIdFrom": chatIdFrom, 66 | "messages": messages, 67 | }, "") 68 | } 69 | 70 | // UploadFile allows you to upload a file from the local file system, 71 | // which can later be sent using the SendFileByUrl method. 72 | // https://green-api.com/en/docs/api/sending/UploadFile/ 73 | func (c SendingCategory) UploadFile(filePath string) (map[string]any, error) { 74 | return c.GreenAPI.Request("POST", "uploadFile", nil, filePath) 75 | } 76 | 77 | // SendPoll is designed for sending messages with a poll 78 | // to a private or group chat. 79 | // https://green-api.com/en/docs/api/sending/SendPoll/ 80 | func (c SendingCategory) SendPoll(parameters map[string]any) (map[string]any, error) { 81 | message, ok := parameters["message"].(string) 82 | if !ok { 83 | return nil, fmt.Errorf("cannot find message paramater") 84 | } 85 | 86 | if len(message) > 255 { 87 | return nil, fmt.Errorf("number of characters in message exceeded (more than 255)") 88 | } 89 | 90 | if parameters == nil { 91 | return nil, fmt.Errorf("parameters is nil") 92 | } 93 | 94 | optionsValue, exists := parameters["options"] 95 | if !exists || optionsValue == nil { 96 | return nil, fmt.Errorf(`parameters["options"] is nil or not exists`) 97 | } 98 | 99 | options, ok := optionsValue.([]map[string]any) 100 | if !ok { 101 | return nil, fmt.Errorf("options is not of type []map[string]any, got %T", optionsValue) 102 | } 103 | 104 | if len(options) < 2 { 105 | return nil, fmt.Errorf("cannot create less than 2 poll options") 106 | } else if len(options) > 12 { 107 | return nil, fmt.Errorf("cannot create more than 12 poll options") 108 | } 109 | 110 | seen := make(map[string]bool) 111 | 112 | for _, option := range options { 113 | optionValue, ok := option["optionName"].(string) 114 | if len(optionValue) > 100 { 115 | return nil, fmt.Errorf("number of characters in optionName exceeded (more than 100)") 116 | } 117 | if !ok { 118 | return nil, fmt.Errorf("option does not have a valid 'optionName'") 119 | } 120 | if seen[optionValue] { 121 | return nil, fmt.Errorf("poll options cannot have duplicates: %s", optionValue) 122 | } 123 | seen[optionValue] = true 124 | } 125 | 126 | return c.GreenAPI.Request("POST", "sendPoll", parameters, "") 127 | } 128 | 129 | // SendInteractiveButtons is designed to send a message with interactive buttons 130 | // to a personal or group chat. 131 | // https://green-api.com/en/docs/api/sending/SendInteractiveButtons/ 132 | func (c SendingCategory) SendInteractiveButtons(parameters map[string]any) (map[string]any, error) { 133 | return c.GreenAPI.Request("POST", "sendInteractiveButtons", parameters, "") 134 | } 135 | 136 | // SendInteractiveButtonsReply is designed to send a message with interactive reply buttons 137 | // to a personal or group chat. 138 | // https://green-api.com/en/docs/api/sending/SendInteractiveButtons/ 139 | func (c SendingCategory) SendInteractiveButtonsReply(parameters map[string]any) (map[string]any, error) { 140 | return c.GreenAPI.Request("POST", "sendInteractiveButtonsReply", parameters, "") 141 | } 142 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NoDerivatives 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | 56 | ======================================================================= 57 | 58 | Creative Commons Attribution-NoDerivatives 4.0 International Public 59 | License 60 | 61 | By exercising the Licensed Rights (defined below), You accept and agree 62 | to be bound by the terms and conditions of this Creative Commons 63 | Attribution-NoDerivatives 4.0 International Public License ("Public 64 | License"). To the extent this Public License may be interpreted as a 65 | contract, You are granted the Licensed Rights in consideration of Your 66 | acceptance of these terms and conditions, and the Licensor grants You 67 | such rights in consideration of benefits the Licensor receives from 68 | making the Licensed Material available under these terms and 69 | conditions. 70 | 71 | 72 | Section 1 -- Definitions. 73 | 74 | a. Adapted Material means material subject to Copyright and Similar 75 | Rights that is derived from or based upon the Licensed Material 76 | and in which the Licensed Material is translated, altered, 77 | arranged, transformed, or otherwise modified in a manner requiring 78 | permission under the Copyright and Similar Rights held by the 79 | Licensor. For purposes of this Public License, where the Licensed 80 | Material is a musical work, performance, or sound recording, 81 | Adapted Material is always produced where the Licensed Material is 82 | synched in timed relation with a moving image. 83 | 84 | b. Copyright and Similar Rights means copyright and/or similar rights 85 | closely related to copyright including, without limitation, 86 | performance, broadcast, sound recording, and Sui Generis Database 87 | Rights, without regard to how the rights are labeled or 88 | categorized. For purposes of this Public License, the rights 89 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 90 | Rights. 91 | 92 | c. Effective Technological Measures means those measures that, in the 93 | absence of proper authority, may not be circumvented under laws 94 | fulfilling obligations under Article 11 of the WIPO Copyright 95 | Treaty adopted on December 20, 1996, and/or similar international 96 | agreements. 97 | 98 | d. Exceptions and Limitations means fair use, fair dealing, and/or 99 | any other exception or limitation to Copyright and Similar Rights 100 | that applies to Your use of the Licensed Material. 101 | 102 | e. Licensed Material means the artistic or literary work, database, 103 | or other material to which the Licensor applied this Public 104 | License. 105 | 106 | f. Licensed Rights means the rights granted to You subject to the 107 | terms and conditions of this Public License, which are limited to 108 | all Copyright and Similar Rights that apply to Your use of the 109 | Licensed Material and that the Licensor has authority to license. 110 | 111 | g. Licensor means the individual(s) or entity(ies) granting rights 112 | under this Public License. 113 | 114 | h. Share means to provide material to the public by any means or 115 | process that requires permission under the Licensed Rights, such 116 | as reproduction, public display, public performance, distribution, 117 | dissemination, communication, or importation, and to make material 118 | available to the public including in ways that members of the 119 | public may access the material from a place and at a time 120 | individually chosen by them. 121 | 122 | i. Sui Generis Database Rights means rights other than copyright 123 | resulting from Directive 96/9/EC of the European Parliament and of 124 | the Council of 11 March 1996 on the legal protection of databases, 125 | as amended and/or succeeded, as well as other essentially 126 | equivalent rights anywhere in the world. 127 | 128 | j. You means the individual or entity exercising the Licensed Rights 129 | under this Public License. Your has a corresponding meaning. 130 | 131 | 132 | Section 2 -- Scope. 133 | 134 | a. License grant. 135 | 136 | 1. Subject to the terms and conditions of this Public License, 137 | the Licensor hereby grants You a worldwide, royalty-free, 138 | non-sublicensable, non-exclusive, irrevocable license to 139 | exercise the Licensed Rights in the Licensed Material to: 140 | 141 | a. reproduce and Share the Licensed Material, in whole or 142 | in part; and 143 | 144 | b. produce and reproduce, but not Share, Adapted Material. 145 | 146 | 2. Exceptions and Limitations. For the avoidance of doubt, where 147 | Exceptions and Limitations apply to Your use, this Public 148 | License does not apply, and You do not need to comply with 149 | its terms and conditions. 150 | 151 | 3. Term. The term of this Public License is specified in Section 152 | 6(a). 153 | 154 | 4. Media and formats; technical modifications allowed. The 155 | Licensor authorizes You to exercise the Licensed Rights in 156 | all media and formats whether now known or hereafter created, 157 | and to make technical modifications necessary to do so. The 158 | Licensor waives and/or agrees not to assert any right or 159 | authority to forbid You from making technical modifications 160 | necessary to exercise the Licensed Rights, including 161 | technical modifications necessary to circumvent Effective 162 | Technological Measures. For purposes of this Public License, 163 | simply making modifications authorized by this Section 2(a) 164 | (4) never produces Adapted Material. 165 | 166 | 5. Downstream recipients. 167 | 168 | a. Offer from the Licensor -- Licensed Material. Every 169 | recipient of the Licensed Material automatically 170 | receives an offer from the Licensor to exercise the 171 | Licensed Rights under the terms and conditions of this 172 | Public License. 173 | 174 | b. No downstream restrictions. You may not offer or impose 175 | any additional or different terms or conditions on, or 176 | apply any Effective Technological Measures to, the 177 | Licensed Material if doing so restricts exercise of the 178 | Licensed Rights by any recipient of the Licensed 179 | Material. 180 | 181 | 6. No endorsement. Nothing in this Public License constitutes or 182 | may be construed as permission to assert or imply that You 183 | are, or that Your use of the Licensed Material is, connected 184 | with, or sponsored, endorsed, or granted official status by, 185 | the Licensor or others designated to receive attribution as 186 | provided in Section 3(a)(1)(A)(i). 187 | 188 | b. Other rights. 189 | 190 | 1. Moral rights, such as the right of integrity, are not 191 | licensed under this Public License, nor are publicity, 192 | privacy, and/or other similar personality rights; however, to 193 | the extent possible, the Licensor waives and/or agrees not to 194 | assert any such rights held by the Licensor to the limited 195 | extent necessary to allow You to exercise the Licensed 196 | Rights, but not otherwise. 197 | 198 | 2. Patent and trademark rights are not licensed under this 199 | Public License. 200 | 201 | 3. To the extent possible, the Licensor waives any right to 202 | collect royalties from You for the exercise of the Licensed 203 | Rights, whether directly or through a collecting society 204 | under any voluntary or waivable statutory or compulsory 205 | licensing scheme. In all other cases the Licensor expressly 206 | reserves any right to collect such royalties. 207 | 208 | 209 | Section 3 -- License Conditions. 210 | 211 | Your exercise of the Licensed Rights is expressly made subject to the 212 | following conditions. 213 | 214 | a. Attribution. 215 | 216 | 1. If You Share the Licensed Material, You must: 217 | 218 | a. retain the following if it is supplied by the Licensor 219 | with the Licensed Material: 220 | 221 | i. identification of the creator(s) of the Licensed 222 | Material and any others designated to receive 223 | attribution, in any reasonable manner requested by 224 | the Licensor (including by pseudonym if 225 | designated); 226 | 227 | ii. a copyright notice; 228 | 229 | iii. a notice that refers to this Public License; 230 | 231 | iv. a notice that refers to the disclaimer of 232 | warranties; 233 | 234 | v. a URI or hyperlink to the Licensed Material to the 235 | extent reasonably practicable; 236 | 237 | b. indicate if You modified the Licensed Material and 238 | retain an indication of any previous modifications; and 239 | 240 | c. indicate the Licensed Material is licensed under this 241 | Public License, and include the text of, or the URI or 242 | hyperlink to, this Public License. 243 | 244 | For the avoidance of doubt, You do not have permission under 245 | this Public License to Share Adapted Material. 246 | 247 | 2. You may satisfy the conditions in Section 3(a)(1) in any 248 | reasonable manner based on the medium, means, and context in 249 | which You Share the Licensed Material. For example, it may be 250 | reasonable to satisfy the conditions by providing a URI or 251 | hyperlink to a resource that includes the required 252 | information. 253 | 254 | 3. If requested by the Licensor, You must remove any of the 255 | information required by Section 3(a)(1)(A) to the extent 256 | reasonably practicable. 257 | 258 | 259 | Section 4 -- Sui Generis Database Rights. 260 | 261 | Where the Licensed Rights include Sui Generis Database Rights that 262 | apply to Your use of the Licensed Material: 263 | 264 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 265 | to extract, reuse, reproduce, and Share all or a substantial 266 | portion of the contents of the database, provided You do not Share 267 | Adapted Material; 268 | 269 | b. if You include all or a substantial portion of the database 270 | contents in a database in which You have Sui Generis Database 271 | Rights, then the database in which You have Sui Generis Database 272 | Rights (but not its individual contents) is Adapted Material; and 273 | 274 | c. You must comply with the conditions in Section 3(a) if You Share 275 | all or a substantial portion of the contents of the database. 276 | 277 | For the avoidance of doubt, this Section 4 supplements and does not 278 | replace Your obligations under this Public License where the Licensed 279 | Rights include other Copyright and Similar Rights. 280 | 281 | 282 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 283 | 284 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 285 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 286 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 287 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 288 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 289 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 290 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 291 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 292 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 293 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 294 | 295 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 296 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 297 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 298 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 299 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 300 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 301 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 302 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 303 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 304 | 305 | c. The disclaimer of warranties and limitation of liability provided 306 | above shall be interpreted in a manner that, to the extent 307 | possible, most closely approximates an absolute disclaimer and 308 | waiver of all liability. 309 | 310 | 311 | Section 6 -- Term and Termination. 312 | 313 | a. This Public License applies for the term of the Copyright and 314 | Similar Rights licensed here. However, if You fail to comply with 315 | this Public License, then Your rights under this Public License 316 | terminate automatically. 317 | 318 | b. Where Your right to use the Licensed Material has terminated under 319 | Section 6(a), it reinstates: 320 | 321 | 1. automatically as of the date the violation is cured, provided 322 | it is cured within 30 days of Your discovery of the 323 | violation; or 324 | 325 | 2. upon express reinstatement by the Licensor. 326 | 327 | For the avoidance of doubt, this Section 6(b) does not affect any 328 | right the Licensor may have to seek remedies for Your violations 329 | of this Public License. 330 | 331 | c. For the avoidance of doubt, the Licensor may also offer the 332 | Licensed Material under separate terms or conditions or stop 333 | distributing the Licensed Material at any time; however, doing so 334 | will not terminate this Public License. 335 | 336 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 337 | License. 338 | 339 | 340 | Section 7 -- Other Terms and Conditions. 341 | 342 | a. The Licensor shall not be bound by any additional or different 343 | terms or conditions communicated by You unless expressly agreed. 344 | 345 | b. Any arrangements, understandings, or agreements regarding the 346 | Licensed Material not stated herein are separate from and 347 | independent of the terms and conditions of this Public License. 348 | 349 | 350 | Section 8 -- Interpretation. 351 | 352 | a. For the avoidance of doubt, this Public License does not, and 353 | shall not be interpreted to, reduce, limit, restrict, or impose 354 | conditions on any use of the Licensed Material that could lawfully 355 | be made without permission under this Public License. 356 | 357 | b. To the extent possible, if any provision of this Public License is 358 | deemed unenforceable, it shall be automatically reformed to the 359 | minimum extent necessary to make it enforceable. If the provision 360 | cannot be reformed, it shall be severed from this Public License 361 | without affecting the enforceability of the remaining terms and 362 | conditions. 363 | 364 | c. No term or condition of this Public License will be waived and no 365 | failure to comply consented to unless expressly agreed to by the 366 | Licensor. 367 | 368 | d. Nothing in this Public License constitutes or may be interpreted 369 | as a limitation upon, or waiver of, any privileges and immunities 370 | that apply to the Licensor or You, including from the legal 371 | processes of any jurisdiction or authority. 372 | 373 | ======================================================================= 374 | 375 | Creative Commons is not a party to its public 376 | licenses. Notwithstanding, Creative Commons may elect to apply one of 377 | its public licenses to material it publishes and in those instances 378 | will be considered the “Licensor.” The text of the Creative Commons 379 | public licenses is dedicated to the public domain under the CC0 Public 380 | Domain Dedication. Except for the limited purpose of indicating that 381 | material is shared under a Creative Commons public license or as 382 | otherwise permitted by the Creative Commons policies published at 383 | creativecommons.org/policies, Creative Commons does not authorize the 384 | use of the trademark "Creative Commons" or any other trademark or logo 385 | of Creative Commons without its prior written consent including, 386 | without limitation, in connection with any unauthorized modifications 387 | to any of its public licenses or any other arrangements, 388 | understandings, or agreements concerning use of licensed material. For 389 | the avoidance of doubt, this paragraph does not form part of the 390 | public licenses. 391 | 392 | Creative Commons may be contacted at creativecommons.org. 393 | -------------------------------------------------------------------------------- /docs/README_RU.md: -------------------------------------------------------------------------------- 1 | # whatsapp-api-client-golang 2 | 3 | whatsapp-api-client-golang - библиотека для интеграции с мессенджером WhatsApp через API 4 | сервиса [green-api.com](https://green-api.com/). Чтобы воспользоваться библиотекой, нужно получить регистрационный токен 5 | и ID аккаунта в [личном кабинете](https://console.green-api.com/). Есть бесплатный тариф аккаунта разработчика. 6 | 7 | ## API 8 | 9 | Документация к REST API находится по [ссылке](https://green-api.com/docs/api/). Библиотека является оберткой к REST API, 10 | поэтому документация по ссылке выше применима и к самой библиотеке. 11 | 12 | ## Авторизация 13 | 14 | Чтобы отправить сообщение или выполнить другие методы Green API, аккаунт WhatsApp в приложении телефона должен быть в 15 | авторизованном состоянии. Для авторизации аккаунта перейдите в [личный кабинет](https://console.green-api.com/) и 16 | сканируйте QR-код с использованием приложения WhatsApp. 17 | 18 | ## Установка 19 | 20 | Не забудьте создать модуль: 21 | 22 | ```shell 23 | go mod init example 24 | ``` 25 | 26 | Установка: 27 | 28 | ```shell 29 | go get github.com/green-api/whatsapp-api-client-golang 30 | ``` 31 | 32 | ## Импорт 33 | 34 | ``` 35 | import ( 36 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 37 | ) 38 | ``` 39 | 40 | ## Примеры 41 | 42 | ### Как инициализировать объект 43 | 44 | ``` 45 | GreenAPI := api.GreenAPI{ 46 | IDInstance: "1101000001", 47 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 48 | } 49 | ``` 50 | 51 | Обратите внимание, что ключи можно получать из переменных среды: 52 | 53 | ``` 54 | IDInstance := os.Getenv("ID_INSTANCE") 55 | APITokenInstance := os.Getenv("API_TOKEN_INSTANCE") 56 | ``` 57 | 58 | ### Как создать группу 59 | 60 | Ссылка на пример: [createGroup/main.go](../examples/createGroup/main.go). 61 | 62 | ``` 63 | response, _ := GreenAPI.Methods().Groups().CreateGroup("groupName", []string{ 64 | "11001234567@c.us", 65 | "11002345678@c.us", 66 | }) 67 | ``` 68 | 69 | ### Как отправить файл загрузкой с диска 70 | 71 | Чтобы отправить файл, нужно указать первым параметром путь к нужному документу. 72 | 73 | Ссылка на пример: [sendFileByUpload/main.go](../examples/sendFileByUpload/main.go). 74 | 75 | ``` 76 | response, _ := GreenAPI.Methods().Sending().SendFileByUpload("example.png", map[string]any{ 77 | "chatId": "11001234567@c.us", 78 | }) 79 | ``` 80 | 81 | ### Как отправить файл по ссылке 82 | 83 | Ссылка на пример: [sendFileByURL/main.go](../examples/sendFileByURL/main.go). 84 | 85 | ``` 86 | response, _ := GreenAPI.Methods().Sending().SendFileByUrl(map[string]any{ 87 | "chatId": "11001234567@c.us", 88 | "urlFile": "https://go.dev/blog/go-brand/Go-Logo/SVG/Go-Logo_Blue.svg", 89 | "fileName": "Go-Logo_Blue.svg", 90 | }) 91 | ``` 92 | 93 | ### Как отправить сообщение 94 | 95 | Если у метода API есть необязательные параметры, то в метод библиотеки нужно передавать JSON (`map[string]any`). 96 | 97 | Ссылка на пример: [sendMessage/main.go](../examples/sendMessage/main.go). 98 | 99 | ``` 100 | response, _ := GreenAPI.Methods().Sending().SendMessage(map[string]any{ 101 | "chatId": "11001234567@c.us", 102 | "message": "Any message", 103 | }) 104 | ``` 105 | 106 | ### Как получать входящие уведомления 107 | 108 | Чтобы начать получать уведомления, нужно передать функцию-обработчик в `Webhook().Start`. Функция-обработчик должна 109 | содержать 1 параметр (`body map[string]any`). При получении нового уведомления ваша функция-обработчик будет 110 | выполнена. Чтобы перестать получать уведомления, нужно вызвать функцию `Webhook().Stop`. 111 | 112 | Ссылка на пример: [webhook/main.go](../examples/webhook/main.go). 113 | 114 | ``` 115 | GreenAPIWebhook := GreenAPI.Webhook() 116 | 117 | GreenAPIWebhook.Start(func(body map[string]any) { 118 | log.Println(body) 119 | }) 120 | ``` 121 | 122 | ### Как отправить сообщение с опросом 123 | 124 | Если у метода API есть необязательные параметры, то в метод библиотеки нужно передавать JSON (`map[string]any`). 125 | 126 | Ссылка на пример: [sendPoll/main.go](../examples/sendPoll/main.go). 127 | 128 | ``` 129 | response, err := GreenAPI.Methods().Sending().SendPoll(map[string]any{ 130 | "chatId": "11001234567@c.us", 131 | "message": "Please choose a color:", 132 | "options": []map[string]any{ 133 | { 134 | "optionName": "Red", 135 | }, 136 | { 137 | "optionName": "Green", 138 | }, 139 | { 140 | "optionName": "Blue", 141 | }, 142 | }, 143 | }) 144 | ``` 145 | 146 | ### Как отправить сообщение с интерактивными кнопками 147 | 148 | Ссылка на пример: [sendInteractiveButtons/main.go](examples/sendInteractiveButtons/main.go). 149 | 150 | ``` 151 | buttons := []map[string]any{ 152 | { 153 | "type": "copy", 154 | "buttonId": "1", 155 | "buttonText": "Copy me", 156 | "copyCode": "3333", 157 | }, 158 | { 159 | "type": "call", 160 | "buttonId": "2", 161 | "buttonText": "Call me", 162 | "phoneNumber": "79123456789", 163 | }, 164 | { 165 | "type": "url", 166 | "buttonId": "3", 167 | "buttonText": "Green-api", 168 | "url": "https://green-api.com", 169 | }, 170 | } 171 | 172 | parameters := map[string]any{ 173 | "chatId": "11001234567@c.us", 174 | "body": "Main message text", 175 | "header": "Message header", 176 | "footer": "Message footer", 177 | "buttons": buttons, 178 | } 179 | response, err := GreenAPI.Methods().Sending().SendInteractiveButtons(parameters) 180 | if err != nil { 181 | log.Fatal(err) 182 | } 183 | ``` 184 | 185 | ### Как отправить текстовый статус 186 | 187 | Если у метода API есть дополнительные параметры, вам необходимо передать JSON через метод библиотеки (`map[string]any`). 188 | 189 | Ссылка на пример: [sendStatus/main.go](examples/sendStatus/main.go). 190 | 191 | ``` 192 | response, _ := GreenAPI.Methods().Status().SendTextStatus(map[string]any{ 193 | "message": "I used Green API GO SDK to send this status!", 194 | "backgroundColor": "#87CEEB", 195 | "font": "SERIF", 196 | }) 197 | ``` 198 | 199 | ## Список примеров 200 | 201 | | Описание | Ссылка на пример | 202 | |--------------------------------------|------------------------------------------------------------------| 203 | | Как создать группу | [createGroup/main.go](../examples/createGroup/main.go) | 204 | | Как отправить файл загрузкой с диска | [sendFileByUpload/main.go](../examples/sendFileByUpload/main.go) | 205 | | Как отправить файл по ссылке | [sendFileByURL/main.go](../examples/sendFileByURL/main.go) | 206 | | Как отправить сообщение | [sendMessage/main.go](../examples/sendMessage/main.go) | 207 | | Как получать входящие уведомления | [webhook/main.go](../examples/webhook/main.go) | 208 | | Как отправить сообщение с опросом | [sendPoll/main.go](../examples/sendPoll/main.go) | 209 | | Как отправить интерактивные кнопки | [sendInteractiveButtons/main.go](examples/sendInteractiveButtons/main.go) | 210 | | Как отправить интерактивные кнопки с ответом | [sendInteractiveButtonsReply/main.go](examples/sendInteractiveButtonsReply/main.go) | 211 | | Как отправить текстовый статус | [sendStatus/main.go](examples/sendStatus/main.go) | 212 | | Как создать инстанс (парнетрский метод) | [createInstance/main.go](examples/createInstance/main.go) | 213 | 214 | ## Список всех методов библиотеки 215 | 216 | | Метод API | Описание | Documentation link | 217 | |-----------------------------------|---------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| 218 | | `Account().GetSettings` | Метод предназначен для получения текущих настроек аккаунта | [GetSettings](https://green-api.com/docs/api/account/GetSettings/) | 219 | | `Account().GetWaSettings` | Метод предназначен для получения информации о аккаунте WhatsApp | [GetWaSettings](https://green-api.com/docs/api/account/GetWaSettings/) | 220 | | `Account().SetSettings` | Метод предназначен для установки настроек аккаунта | [SetSettings](https://green-api.com/docs/api/account/SetSettings/) | 221 | | `Account().GetStateInstance` | Метод предназначен для получения состояния аккаунта | [GetStateInstance](https://green-api.com/docs/api/account/GetStateInstance/) | 222 | | `Account().GetStatusInstance` | Метод предназначен для получения состояния сокета соединения инстанса аккаунта с WhatsApp | [GetStatusInstance](https://green-api.com/docs/api/account/GetStatusInstance/) | 223 | | `Account().Reboot` | Метод предназначен для перезапуска аккаунта | [Reboot](https://green-api.com/docs/api/account/Reboot/) | 224 | | `Account().Logout` | Метод предназначен для разлогинивания аккаунта | [Logout](https://green-api.com/docs/api/account/Logout/) | 225 | | `Account().QR` | Метод предназначен для получения QR-кода | [QR](https://green-api.com/docs/api/account/QR/) | 226 | | `Account().SetProfilePicture` | Метод предназначен для установки аватара аккаунта | [SetProfilePicture](https://green-api.com/docs/api/account/SetProfilePicture/) | 227 | | `Account().GetAuthorizationCode` | Метод предназначен для авторизации инстанса по номеру телефона | [GetAuthorizationCode](https://green-api.com/docs/api/account/GetAuthorizationCode/) | 228 | | `Groups().CreateGroup` | Метод предназначен для создания группового чата | [CreateGroup](https://green-api.com/docs/api/groups/CreateGroup/) | 229 | | `Groups().UpdateGroupName` | Метод изменяет наименование группового чата | [UpdateGroupName](https://green-api.com/docs/api/groups/UpdateGroupName/) | 230 | | `Groups().GetGroupData` | Метод получает данные группового чата | [GetGroupData](https://green-api.com/docs/api/groups/GetGroupData/) | 231 | | `Groups().AddGroupParticipant` | Метод добавляет участника в групповой чат | [AddGroupParticipant](https://green-api.com/docs/api/groups/AddGroupParticipant/) | 232 | | `Groups().RemoveGroupParticipant` | Метод удаляет участника из группового чата | [RemoveGroupParticipant](https://green-api.com/docs/api/groups/RemoveGroupParticipant/) | 233 | | `Groups().SetGroupAdmin` | Метод назначает участника группового чата администратором | [SetGroupAdmin](https://green-api.com/docs/api/groups/SetGroupAdmin/) | 234 | | `Groups().RemoveAdmin` | Метод лишает участника прав администрирования группового чата | [RemoveAdmin](https://green-api.com/docs/api/groups/RemoveAdmin/) | 235 | | `Groups().SetGroupPicture` | Метод устанавливает аватар группы | [SetGroupPicture](https://green-api.com/docs/api/groups/SetGroupPicture/) | 236 | | `Groups().LeaveGroup` | Метод производит выход пользователя текущего аккаунта из группового чата | [LeaveGroup](https://green-api.com/docs/api/groups/LeaveGroup/) | 237 | | `Status().SendTextStatus` | Метод предназначен для отправки текстового статуса | [SendTextStatus](https://green-api.com/docs/api/statuses/SendTextStatus/) | 238 | | `Status().SendVoiceStatus` | Метод предназначен для отправки голосового статуса | [SendVoiceStatus](https://green-api.com/docs/api/statuses/SendVoiceStatus/) | 239 | | `Status().SendMediaStatus` | Метод предназначен для отправки медиа-файлов | [SendMediaStatus](https://green-api.com/docs/api/statuses/SendMediaStatus/) | 240 | | `Status().GetOutgoingStatuses` | Метод возвращает крайние исходящие статусы аккаунта | [GetOutgoingStatuses](https://green-api.com/docs/api/statuses/GetOutgoingStatuses/) | 241 | | `Status().GetIncomingStatuses` | Метод возвращает крайние входящие статусы аккаунта | [GetIncomingStatuses](https://green-api.com/docs/api/statuses/GetIncomingStatuses/) | 242 | | `Status().GetStatusStatistic` | Метод возвращает массив получателей со статусами | [GetStatusStatistic](https://green-api.com/docs/api/statuses/GetStatusStatistic/) | 243 | | `Status().DeleteStatus` | Метод предназначен для удаления статуса | [DeleteStatus](https://green-api.com/docs/api/statuses/DeleteStatus/) | 244 | 245 | | `Journals().GetChatHistory` | Метод возвращает историю сообщений чата | [GetChatHistory](https://green-api.com/docs/api/journals/GetChatHistory/) | 246 | | `Journals().GetMessage` | Метод возвращает сообщение чата | [GetMessage](https://green-api.com/docs/api/journals/GetMessage/) | 247 | | `Journals().LastIncomingMessages` | Метод возвращает крайние входящие сообщения аккаунта | [LastIncomingMessages](https://green-api.com/docs/api/journals/LastIncomingMessages/) | 248 | | `Journals().LastOutgoingMessages` | Метод возвращает крайние отправленные сообщения аккаунта | [LastOutgoingMessages](https://green-api.com/docs/api/journals/LastOutgoingMessages/) | 249 | | `Queues().ShowMessagesQueue` | Метод предназначен для получения списка сообщений, находящихся в очереди на отправку | [ShowMessagesQueue](https://green-api.com/docs/api/queues/ShowMessagesQueue/) | 250 | | `Queues().ClearMessagesQueue` | Метод предназначен для очистки очереди сообщений на отправку | [ClearMessagesQueue](https://green-api.com/docs/api/queues/ClearMessagesQueue/) | 251 | | `ReadMark().ReadChat` | Метод предназначен для отметки сообщений в чате прочитанными | [ReadChat](https://green-api.com/docs/api/marks/ReadChat/) | 252 | | `Receiving().ReceiveNotification` | Метод предназначен для получения одного входящего уведомления из очереди уведомлений | [ReceiveNotification](https://green-api.com/docs/api/receiving/technology-http-api/ReceiveNotification/) | 253 | | `Receiving().DeleteNotification` | Метод предназначен для удаления входящего уведомления из очереди уведомлений | [DeleteNotification](https://green-api.com/docs/api/receiving/technology-http-api/DeleteNotification/) | 254 | | `Receiving().DownloadFile` | Метод предназначен для скачивания принятых и отправленных файлов | [DownloadFile](https://green-api.com/docs/api/receiving/files/DownloadFile/) | 255 | | `Sending().SendMessage` | Метод предназначен для отправки текстового сообщения в личный или групповой чат | [SendMessage](https://green-api.com/docs/api/sending/SendMessage/) | 256 | | `Sending().SendFileByUpload` | Метод предназначен для отправки файла, загружаемого через форму (form-data) | [SendFileByUpload](https://green-api.com/docs/api/sending/SendFileByUpload/) | 257 | | `Sending().SendFileByUrl` | Метод предназначен для отправки файла, загружаемого по ссылке | [SendFileByUrl](https://green-api.com/docs/api/sending/SendFileByUrl/) | 258 | | `Sending().UploadFile` | Метод предназначен для загрузки файла в облачное хранилище, который можно отправить методом SendFileByUrl | [UploadFile](https://green-api.com/docs/api/sending/UploadFile/) | 259 | | `Sending().SendLocation` | Метод предназначен для отправки сообщения геолокации | [SendLocation](https://green-api.com/docs/api/sending/SendLocation/) | 260 | | `Sending().SendContact` | Метод предназначен для отправки сообщения с контактом | [SendContact](https://green-api.com/docs/api/sending/SendContact/) | 261 | | `Sending().ForwardMessages` | Метод предназначен для пересылки сообщений в личный или групповой чат | [ForwardMessages](https://green-api.com/docs/api/sending/ForwardMessages/) | 262 | | `Sending().UploadFile` | Метод позволяет выгружать файл из локальной файловой системы, который позднее можно отправить методом SendFileByUrl | [UploadFile](https://green-api.com/docs/api/sending/UploadFile/) | 263 | | `Sending().SendPoll` | Метод предназначен для отправки сообщения с опросом в личный или групповой чат | [SendPoll](https://green-api.com/docs/api/sending/SendPoll/) | 264 | | `Sending().SendInteractiveButtons` | Метод предназначен для отправки интерактивных кнопок | [SendInteractiveButtons](https://green-api.com/docs/api/sending/SendInteractiveButtons/) | 265 | | `Sending().SendInteractiveButtonsReply` | Метод предназначен для отправки интерактивных кнопок с ответом | [SendInteractiveButtonsReply](https://green-api.com/docs/api/sending/SendInteractiveButtonsReply/) | 266 | | `Service().CheckWhatsapp` | Метод проверяет наличие аккаунта WhatsApp на номере телефона | [CheckWhatsapp](https://green-api.com/docs/api/service/CheckWhatsapp/) | 267 | | `Service().GetAvatar` | Метод возвращает аватар корреспондента или группового чата | [GetAvatar](https://green-api.com/docs/api/service/GetAvatar/) | 268 | | `Service().GetContacts` | Метод предназначен для получения списка контактов текущего аккаунта | [GetContacts](https://green-api.com/docs/api/service/GetContacts/) | 269 | | `Service().GetContactInfo` | Метод предназначен для получения информации о контакте | [GetContactInfo](https://green-api.com/docs/api/service/GetContactInfo/) | 270 | | `Service().DeleteMessage` | Метод удаляет сообщение из чата | [DeleteMessage](https://green-api.com/docs/api/service/deleteMessage/) | 271 | | `Service().ArchiveChat` | Метод архивирует чат | [ArchiveChat](https://green-api.com/docs/api/service/archiveChat/) | 272 | | `Service().UnarchiveChat` | Метод разархивирует чат | [UnarchiveChat](https://green-api.com/docs/api/service/unarchiveChat/) | 273 | | `Service().SetDisappearingChat` | Метод предназначен для изменения настроек исчезающих сообщений в чатах | [SetDisappearingChat](https://green-api.com/docs/api/service/SetDisappearingChat/) | 274 | | `Webhook().Start` | Метод предназначен для старта получения новых уведомлений | | 275 | | `Webhook().Stop` | Метод предназначен для остановки получения новых уведомлений | | 276 | 277 | ## Документация по методам сервиса 278 | 279 | [Документация по методам сервиса](https://green-api.com/docs/api/). 280 | 281 | ## Лицензия 282 | 283 | Лицензировано на условиях [ 284 | Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) 285 | ](https://creativecommons.org/licenses/by-nd/4.0/). 286 | Смотрите файл [LICENSE](../LICENSE). 287 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # whatsapp-api-client-golang 2 | 3 | - [Документация на русском языке](docs/README_RU.md). 4 | 5 | whatsapp-api-client-golang is a library for integration with WhatsApp messenger using the API 6 | service [green-api.com](https://green-api.com/en/). You should get a registration token and an account ID in 7 | your [personal cabinet](https://console.green-api.com/) to use the library. There is a free developer account tariff. 8 | 9 | ## API 10 | 11 | The documentation for the REST API can be found at the [link](https://green-api.com/en/docs/). The library is a wrapper 12 | for the REST API, so the documentation at the link above also applies. 13 | 14 | #### Authorization 15 | 16 | To send a message or perform other Green API methods, the WhatsApp account in the phone app must be authorized. To 17 | authorize the account, go to your [cabinet](https://console.green-api.com/) and scan the QR code using the WhatsApp app. 18 | 19 | ## Installation 20 | 21 | Do not forget to create a module: 22 | 23 | ```shell 24 | go mod init example 25 | ``` 26 | 27 | Installation: 28 | 29 | ```shell 30 | go get github.com/green-api/whatsapp-api-client-golang 31 | ``` 32 | 33 | ## Import 34 | 35 | ``` 36 | import ( 37 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 38 | ) 39 | ``` 40 | 41 | ## Examples 42 | 43 | ### How to initialize an object 44 | 45 | ``` 46 | GreenAPI := api.GreenAPI{ 47 | IDInstance: "1101000001", 48 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 49 | } 50 | ``` 51 | 52 | Note that keys can be obtained from environment variables: 53 | 54 | ``` 55 | IDInstance := os.Getenv("ID_INSTANCE") 56 | APITokenInstance := os.Getenv("API_TOKEN_INSTANCE") 57 | ``` 58 | 59 | ### How to create a group 60 | 61 | Link to example: [createGroup/main.go](examples/createGroup/main.go). 62 | 63 | ``` 64 | response, _ := GreenAPI.Methods().Groups().CreateGroup("groupName", []string{ 65 | "11001234567@c.us", 66 | "11002345678@c.us", 67 | }) 68 | ``` 69 | 70 | ### How to send a file by uploading from the disk 71 | 72 | To send a file, you need to give the path to the file. 73 | 74 | Link to example: [sendFileByUpload/main.go](examples/sendFileByUpload/main.go). 75 | 76 | ``` 77 | response, _ := GreenAPI.Methods().Sending().SendFileByUpload("example.png", map[string]any{ 78 | "chatId": "11001234567@c.us", 79 | }) 80 | ``` 81 | 82 | ### How to send a file by URL 83 | 84 | Link to example: [sendFileByURL/main.go](examples/sendFileByURL/main.go). 85 | 86 | ``` 87 | response, _ := GreenAPI.Methods().Sending().SendFileByUrl(map[string]any{ 88 | "chatId": "11001234567@c.us", 89 | "urlFile": "https://go.dev/blog/go-brand/Go-Logo/SVG/Go-Logo_Blue.svg", 90 | "fileName": "Go-Logo_Blue.svg", 91 | }) 92 | ``` 93 | 94 | ### How to send a message 95 | 96 | If an API method has optional parameters, you have to pass JSON to the library method (`map[string]any`). 97 | 98 | Link to example: [sendMessage/main.go](examples/sendMessage/main.go). 99 | 100 | ``` 101 | response, _ := GreenAPI.Methods().Sending().SendMessage(map[string]any{ 102 | "chatId": "11001234567@c.us", 103 | "message": "Any message", 104 | }) 105 | ``` 106 | 107 | ### How to receive incoming notifications 108 | 109 | To receive incoming webhooks, you must send a handler function to `Webhook().Start`. The handler function should have 110 | one parameter (`body map[string]any`). When you receive a new notification, your handler function will be 111 | executed. To stop receiving incoming webhooks, you need to call `Webhook().Stop`. 112 | 113 | Link to example: [webhook/main.go](examples/webhook/main.go). 114 | 115 | ``` 116 | GreenAPIWebhook := GreenAPI.Webhook() 117 | 118 | GreenAPIWebhook.Start(func(body map[string]any) { 119 | log.Println(body) 120 | }) 121 | ``` 122 | 123 | ### How to send a message with a poll 124 | 125 | If an API method has optional parameters, you have to pass JSON to the library method (`map[string]any`). 126 | 127 | Link to example: [sendPoll/main.go](examples/sendPoll/main.go). 128 | 129 | ``` 130 | response, err := GreenAPI.Methods().Sending().SendPoll(map[string]any{ 131 | "chatId": "11001234567@c.us", 132 | "message": "Please choose a color:", 133 | "options": []map[string]any{ 134 | { 135 | "optionName": "Red", 136 | }, 137 | { 138 | "optionName": "Green", 139 | }, 140 | { 141 | "optionName": "Blue", 142 | }, 143 | }, 144 | }) 145 | ``` 146 | 147 | ### How to send a message with interactive buttons 148 | 149 | Link to example: [sendInteractiveButtons/main.go](examples/sendInteractiveButtons/main.go). 150 | 151 | ``` 152 | buttons := []map[string]any{ 153 | { 154 | "type": "copy", 155 | "buttonId": "1", 156 | "buttonText": "Copy me", 157 | "copyCode": "3333", 158 | }, 159 | { 160 | "type": "call", 161 | "buttonId": "2", 162 | "buttonText": "Call me", 163 | "phoneNumber": "79123456789", 164 | }, 165 | { 166 | "type": "url", 167 | "buttonId": "3", 168 | "buttonText": "Green-api", 169 | "url": "https://green-api.com", 170 | }, 171 | } 172 | 173 | parameters := map[string]any{ 174 | "chatId": "11001234567@c.us", 175 | "body": "Main message text", 176 | "header": "Message header", 177 | "footer": "Message footer", 178 | "buttons": buttons, 179 | } 180 | response, err := GreenAPI.Methods().Sending().SendInteractiveButtons(parameters) 181 | if err != nil { 182 | log.Fatal(err) 183 | } 184 | ``` 185 | 186 | ### How to send a text status 187 | 188 | If an API method has optional parameters, you have to pass JSON to the library method (`map[string]any`). 189 | 190 | Link to example: [sendStatus/main.go](examples/sendStatus/main.go). 191 | 192 | ``` 193 | response, _ := GreenAPI.Methods().Status().SendTextStatus(map[string]any{ 194 | "message": "I used Green API GO SDK to send this status!", 195 | "backgroundColor": "#87CEEB", 196 | "font": "SERIF", 197 | }) 198 | ``` 199 | 200 | 201 | 202 | ## List of examples 203 | 204 | | Description | Link to example | 205 | |-------------------------------------------------------|---------------------------------------------------------------| 206 | | How to create a group | [createGroup/main.go](examples/createGroup/main.go) | 207 | | How to send a file by uploading from the disk | [sendFileByUpload/main.go](examples/sendFileByUpload/main.go) | 208 | | How to send a file by URL | [sendFileByURL/main.go](examples/sendFileByURL/main.go) | 209 | | How to send a message | [sendMessage/main.go](examples/sendMessage/main.go) | 210 | | How to receive incoming notifications | [webhook/main.go](examples/webhook/main.go) | 211 | | How to send a message with a poll | [sendPoll/main.go](examples/sendPoll/main.go) | 212 | | How to send a message with interactive buttons | [sendInteractiveButtons/main.go](examples/sendInteractiveButtons/main.go) | 213 | | How to send a message with interactive reply buttons | [sendInteractiveButtonsReply/main.go](examples/sendInteractiveButtonsReply/main.go) | 214 | | How to send a text status | [sendStatus/main.go](examples/sendStatus/main.go) | 215 | | How to create an instance (partner method) | [createInstance/main.go](examples/createInstance/main.go) | 216 | 217 | ## List of all library methods 218 | 219 | | API method | Description | Documentation link | 220 | |-----------------------------------|---------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| 221 | | `Account().GetSettings` | The method is designed to get the current settings of the account | [GetSettings](https://green-api.com/en/docs/api/account/GetSettings/) | 222 | | `Account().GetWaSettings` | The method is designed to get information about the WhatsApp account | [GetSettings](https://green-api.com/en/docs/api/account/GetWaSettings/) | 223 | | `Account().SetSettings` | The method is designed to set the account settings | [SetSettings](https://green-api.com/docs/api/account/SetSettings/) | 224 | | `Account().GetStateInstance` | The method is designed to get the state of the account | [GetStateInstance](https://green-api.com/en/docs/api/account/GetStateInstance/) | 225 | | `Account().GetStatusInstance` | The method is designed to get the socket connection state of the account instance with WhatsApp | [GetStatusInstance](https://green-api.com/en/docs/api/account/GetStatusInstance/) | 226 | | `Account().Reboot` | The method is designed to restart the account | [Reboot](https://green-api.com/en/docs/api/account/Reboot/) | 227 | | `Account().Logout` | The method is designed to unlogin the account | [Logout](https://green-api.com/en/docs/api/account/Logout/) | 228 | | `Account().QR` | The method is designed to get a QR code | [QR](https://green-api.com/en/docs/api/account/QR/) | 229 | | `Account().SetProfilePicture` | The method is designed to set the avatar of the account | [SetProfilePicture](https://green-api.com/en/docs/api/account/SetProfilePicture/) | 230 | | `Account().GetAuthorizationCode` | The method is designed to authorize an instance by phone number | [GetAuthorizationCode](https://green-api.com/en/docs/api/account/GetAuthorizationCode/) | 231 | | `Groups().CreateGroup` | The method is designed to create a group chat | [CreateGroup](https://green-api.com/en/docs/api/groups/CreateGroup/) | 232 | | `Groups().UpdateGroupName` | The method changes the name of the group chat | [UpdateGroupName](https://green-api.com/en/docs/api/groups/UpdateGroupName/) | 233 | | `Groups().GetGroupData` | The method gets group chat data | [GetGroupData](https://green-api.com/en/docs/api/groups/GetGroupData/) | 234 | | `Groups().AddGroupParticipant` | The method adds a participant to the group chat | [AddGroupParticipant](https://green-api.com/en/docs/api/groups/AddGroupParticipant/) | 235 | | `Groups().RemoveGroupParticipant` | The method removes the participant from the group chat | [RemoveGroupParticipant](https://green-api.com/en/docs/api/groups/RemoveGroupParticipant/) | 236 | | `Groups().SetGroupAdmin` | The method designates a member of a group chat as an administrator | [SetGroupAdmin](https://green-api.com/en/docs/api/groups/SetGroupAdmin/) | 237 | | `Groups().RemoveAdmin` | The method deprives the participant of group chat administration rights | [RemoveAdmin](https://green-api.com/en/docs/api/groups/RemoveAdmin/) | 238 | | `Groups().SetGroupPicture` | The method sets the avatar of the group | [SetGroupPicture](https://green-api.com/en/docs/api/groups/SetGroupPicture/) | 239 | | `Groups().LeaveGroup` | The method logs the user of the current account out of the group chat | [LeaveGroup](https://green-api.com/en/docs/api/groups/LeaveGroup/) | 240 | | `Status().SendTextStatus` | The method is aimed for sending a text status | [SendTextStatus](https://green-api.com/en/docs/api/statuses/SendTextStatus/) | 241 | | `Status().SendVoiceStatus` | The method is aimed for sending a voice status | [SendVoiceStatus](https://green-api.com/en/docs/api/statuses/SendVoiceStatus/) | 242 | | `Status().SendMediaStatus` | The method is used to sending a pictures or video status | [SendMediaStatus](https://green-api.com/en/docs/api/statuses/SendMediaStatus/) | 243 | | `Status().GetOutgoingStatuses` | The method returns the outgoing statuses of the account | [GetOutgoingStatuses](https://green-api.com/en/docs/api/statuses/GetOutgoingStatuses/) | 244 | | `Status().GetIncomingStatuses` | The method returns the incoming status messages of the account | [GetIncomingStatuses](https://green-api.com/en/docs/api/statuses/GetIncomingStatuses/) | 245 | | `Status().GetStatusStatistic` | The method returns an array of recipients marked for a given status. | [GetStatusStatistic](https://green-api.com/en/docs/api/statuses/GetStatusStatistic/) | 246 | | `Status().DeleteStatus` | The method is aimed for deleting status. | [DeleteStatus](https://green-api.com/en/docs/api/statuses/DeleteStatus/) | 247 | | `Journals().GetChatHistory` | The method returns the chat message history | [GetChatHistory](https://green-api.com/en/docs/api/journals/GetChatHistory/) | 248 | | `Journals().GetMessage` | The method returns a chat message | [GetMessage](https://green-api.com/en/docs/api/journals/GetMessage/) | 249 | | `Journals().LastIncomingMessages` | The method returns the most recent incoming messages of the account | [LastIncomingMessages](https://green-api.com/en/docs/api/journals/LastIncomingMessages/) | 250 | | `Journals().LastOutgoingMessages` | The method returns the last sent messages of the account | [LastOutgoingMessages](https://green-api.com/en/docs/api/journals/LastOutgoingMessages/) | 251 | | `Queues().ShowMessagesQueue` | The method is designed to get the list of messages that are in the queue to be sent | [ShowMessagesQueue](https://green-api.com/en/docs/api/queues/ShowMessagesQueue/) | 252 | | `Queues().ClearMessagesQueue` | The method is designed to clear the queue of messages to be sent | [ClearMessagesQueue](https://green-api.com/en/docs/api/queues/ClearMessagesQueue/) | 253 | | `ReadMark().ReadChat` | The method is designed to mark chat messages as read | [ReadChat](https://green-api.com/en/docs/api/marks/ReadChat/) | 254 | | `Receiving().ReceiveNotification` | The method is designed to receive a single incoming notification from the notification queue | [ReceiveNotification](https://green-api.com/en/docs/api/receiving/technology-http-api/ReceiveNotification/) | 255 | | `Receiving().DeleteNotification` | The method is designed to remove an incoming notification from the notification queue | [DeleteNotification](https://green-api.com/en/docs/api/receiving/technology-http-api/DeleteNotification/) | 256 | | `Receiving().DownloadFile` | The method is for downloading received and sent files | [DownloadFile](https://green-api.com/en/docs/api/receiving/files/DownloadFile/) | 257 | | `Sending().SendMessage` | The method is designed to send a text message to a personal or group chat | [SendMessage](https://green-api.com/en/docs/api/sending/SendMessage/) | 258 | | `Sending().SendFileByUpload` | The method is designed to send a file loaded through a form (form-data) | [SendFileByUpload](https://green-api.com/en/docs/api/sending/SendFileByUpload/) | 259 | | `Sending().SendFileByUrl` | The method is designed to send a file downloaded via a link | [SendFileByUrl](https://green-api.com/en/docs/api/sending/SendFileByUrl/) | 260 | | `Sending().UploadFile` | The method allows you to upload a file from the local file system, which can later be sent using the SendFileByUrl method | [UploadFile](https://green-api.com/en/docs/api/sending/UploadFile/) | 261 | | `Sending().SendLocation` | The method is designed to send a geolocation message | [SendLocation](https://green-api.com/en/docs/api/sending/SendLocation/) | 262 | | `Sending().SendContact` | The method is for sending a message with a contact | [SendContact](https://green-api.com/en/docs/api/sending/SendContact/) | 263 | | `Sending().ForwardMessages` | The method is designed for forwarding messages to a personal or group chat | [ForwardMessages](https://green-api.com/en/docs/api/sending/ForwardMessages/) | 264 | | `Sending().SendPoll` | The method is designed for sending messages with a poll to a private or group chat | [SendPoll](https://green-api.com/en/docs/api/sending/SendPoll/) | 265 | | `Sending().SendInteractiveButtons` | The method is for sending a message with interactive buttons | [SendInteractiveButtons](https://green-api.com/en/docs/api/sending/SendInteractiveButtons/) | 266 | | `Sending().SendInteractiveButtonsReply` | The method is for sending a message with interactive reply buttons | [SendInteractiveButtonsReply](https://green-api.com/en/docs/api/sending/SendInteractiveButtonsReply/) | 267 | | `Service().CheckWhatsapp` | The method checks if there is a WhatsApp account on the phone number | [CheckWhatsapp](https://green-api.com/en/docs/api/service/CheckWhatsapp/) | 268 | | `Service().GetAvatar` | The method returns the avatar of the correspondent or group chat | [GetAvatar](https://green-api.com/en/docs/api/service/GetAvatar/) | 269 | | `Service().GetContacts` | The method is designed to get a list of contacts of the current account | [GetContacts](https://green-api.com/en/docs/api/service/GetContacts/) | 270 | | `Service().GetContactInfo` | The method is designed to obtain information about the contact | [GetContactInfo](https://green-api.com/en/docs/api/service/GetContactInfo/) | 271 | | `Service().DeleteMessage` | The method deletes the message from chat | [DeleteMessage](https://green-api.com/en/docs/api/service/deleteMessage/) | 272 | | `Service().ArchiveChat` | The method archives the chat | [ArchiveChat](https://green-api.com/en/docs/api/service/archiveChat/) | 273 | | `Service().UnarchiveChat` | The method unarchives the chat | [UnarchiveChat](https://green-api.com/en/docs/api/service/unarchiveChat/) | 274 | | `Service().SetDisappearingChat` | The method is designed to change the settings of disappearing messages in chats | [SetDisappearingChat](https://green-api.com/en/docs/api/service/SetDisappearingChat/) | 275 | | `Webhook().Start` | The method is designed to start receiving new notifications | | 276 | | `Webhook().Stop` | The method is designed to stop receiving new notifications | | 277 | | `Partner().CreateInstance` | The method is aimed to create an instace using partner account. | [CreateInstance](https://green-api.com/en/docs/partners/createInstance/) | 278 | | `Partner().DeleteInstanceAccount` | The method is aimed to delete an instance using partner account. | [DeleteInstanceAccount](https://green-api.com/en/docs/partners/deleteInstanceAccount/) | 279 | | `Partner().GetInstances` | The method is aimed to get all instances on a partner account. | [GetInstances](https://green-api.com/en/docs/partners/getInstances/) | 280 | ## Service methods documentation 281 | 282 | [Service methods documentation](https://green-api.com/en/docs/api/). 283 | 284 | ## License 285 | 286 | Licensed under [ 287 | Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) 288 | ](https://creativecommons.org/licenses/by-nd/4.0/) terms. 289 | Please see file [LICENSE](LICENSE). 290 | --------------------------------------------------------------------------------