├── .github ├── dependabot.yml └── workflows │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── docs └── README_RU.md ├── examples ├── checkWhatsApp │ └── main.go ├── createGroup │ └── main.go ├── createInstance │ └── main.go ├── sendFileByURL │ └── main.go ├── sendFileByUpload │ └── main.go ├── sendMessage │ └── main.go ├── sendPoll │ └── main.go ├── uploadFile │ └── main.go └── webhook │ └── main.go ├── go.mod ├── go.sum └── pkg ├── api ├── api.go ├── http.go └── webhook.go └── categories ├── categories.go └── methods ├── account.go ├── base_category.go ├── device.go ├── groups.go ├── journals.go ├── partner.go ├── queues.go ├── read_mark.go ├── receiving.go ├── sending.go └── service.go /.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 | -------------------------------------------------------------------------------- /.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.19", "1.20", "1.21" ] 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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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]interface{}{ 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]interface{}{ 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]interface{}`). 97 | 98 | Link to example: [sendMessage/main.go](examples/sendMessage/main.go). 99 | 100 | ``` 101 | response, _ := GreenAPI.Methods().Sending().SendMessage(map[string]interface{}{ 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]interface{}`). 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]interface{}) { 119 | fmt.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]interface{}`). 126 | 127 | Link to example: [sendPoll/main.go](examples/sendPoll/main.go). 128 | 129 | ``` 130 | response, err := GreenAPI.Methods().Sending().SendPoll(map[string]interface{}{ 131 | "chatId": "11001234567@c.us", 132 | "message": "Please choose a color:", 133 | "options": []map[string]interface{}{ 134 | { 135 | "optionName": "Red", 136 | }, 137 | { 138 | "optionName": "Green", 139 | }, 140 | { 141 | "optionName": "Blue", 142 | }, 143 | }, 144 | }) 145 | ``` 146 | 147 | ## List of examples 148 | 149 | | Description | Link to example | 150 | |-----------------------------------------------|---------------------------------------------------------------| 151 | | How to create a group | [createGroup/main.go](examples/createGroup/main.go) | 152 | | How to send a file by uploading from the disk | [sendFileByUpload/main.go](examples/sendFileByUpload/main.go) | 153 | | How to send a file by URL | [sendFileByURL/main.go](examples/sendFileByURL/main.go) | 154 | | How to send a message | [sendMessage/main.go](examples/sendMessage/main.go) | 155 | | How to receive incoming notifications | [webhook/main.go](examples/webhook/main.go) | 156 | | How to send a message with a poll | [sendPoll/main.go](examples/sendPoll/main.go) | 157 | 158 | ## List of all library methods 159 | 160 | | API method | Description | Documentation link | 161 | |-----------------------------------|---------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| 162 | | `Account().GetSettings` | The method is designed to get the current settings of the account | [GetSettings](https://green-api.com/en/docs/api/account/GetSettings/) | 163 | | `Account().GetWaSettings` | The method is designed to get information about the WhatsApp account | [GetSettings](https://green-api.com/en/docs/api/account/GetWaSettings/) | 164 | | `Account().SetSettings` | The method is designed to set the account settings | [SetSettings](https://green-api.com/docs/api/account/SetSettings/) | 165 | | `Account().GetStateInstance` | The method is designed to get the state of the account | [GetStateInstance](https://green-api.com/en/docs/api/account/GetStateInstance/) | 166 | | `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/) | 167 | | `Account().Reboot` | The method is designed to restart the account | [Reboot](https://green-api.com/en/docs/api/account/Reboot/) | 168 | | `Account().Logout` | The method is designed to unlogin the account | [Logout](https://green-api.com/en/docs/api/account/Logout/) | 169 | | `Account().QR` | The method is designed to get a QR code | [QR](https://green-api.com/en/docs/api/account/QR/) | 170 | | `Account().SetProfilePicture` | The method is designed to set the avatar of the account | [SetProfilePicture](https://green-api.com/en/docs/api/account/SetProfilePicture/) | 171 | | `Account().GetAuthorizationCode` | The method is designed to authorize an instance by phone number | [GetAuthorizationCode](https://green-api.com/en/docs/api/account/GetAuthorizationCode/) | 172 | | `Device().GetDeviceInfo` | The method is designed to get information about the device (phone) on which the WhatsApp Business application is running | [GetDeviceInfo](https://green-api.com/en/docs/api/phone/GetDeviceInfo/) | 173 | | `Groups().CreateGroup` | The method is designed to create a group chat | [CreateGroup](https://green-api.com/en/docs/api/groups/CreateGroup/) | 174 | | `Groups().UpdateGroupName` | The method changes the name of the group chat | [UpdateGroupName](https://green-api.com/en/docs/api/groups/UpdateGroupName/) | 175 | | `Groups().GetGroupData` | The method gets group chat data | [GetGroupData](https://green-api.com/en/docs/api/groups/GetGroupData/) | 176 | | `Groups().AddGroupParticipant` | The method adds a participant to the group chat | [AddGroupParticipant](https://green-api.com/en/docs/api/groups/AddGroupParticipant/) | 177 | | `Groups().RemoveGroupParticipant` | The method removes the participant from the group chat | [RemoveGroupParticipant](https://green-api.com/en/docs/api/groups/RemoveGroupParticipant/) | 178 | | `Groups().SetGroupAdmin` | The method designates a member of a group chat as an administrator | [SetGroupAdmin](https://green-api.com/en/docs/api/groups/SetGroupAdmin/) | 179 | | `Groups().RemoveAdmin` | The method deprives the participant of group chat administration rights | [RemoveAdmin](https://green-api.com/en/docs/api/groups/RemoveAdmin/) | 180 | | `Groups().SetGroupPicture` | The method sets the avatar of the group | [SetGroupPicture](https://green-api.com/en/docs/api/groups/SetGroupPicture/) | 181 | | `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/) | 182 | | `Journals().GetChatHistory` | The method returns the chat message history | [GetChatHistory](https://green-api.com/en/docs/api/journals/GetChatHistory/) | 183 | | `Journals().GetMessage` | The method returns a chat message | [GetMessage](https://green-api.com/en/docs/api/journals/GetMessage/) | 184 | | `Journals().LastIncomingMessages` | The method returns the most recent incoming messages of the account | [LastIncomingMessages](https://green-api.com/en/docs/api/journals/LastIncomingMessages/) | 185 | | `Journals().LastOutgoingMessages` | The method returns the last sent messages of the account | [LastOutgoingMessages](https://green-api.com/en/docs/api/journals/LastOutgoingMessages/) | 186 | | `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/) | 187 | | `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/) | 188 | | `ReadMark().ReadChat` | The method is designed to mark chat messages as read | [ReadChat](https://green-api.com/en/docs/api/marks/ReadChat/) | 189 | | `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/) | 190 | | `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/) | 191 | | `Receiving().DownloadFile` | The method is for downloading received and sent files | [DownloadFile](https://green-api.com/en/docs/api/receiving/files/DownloadFile/) | 192 | | `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/) | 193 | | `Sending().SendButtons` | The method is designed to send a message with buttons to a personal or group chat | [SendButtons](https://green-api.com/en/docs/api/sending/SendButtons/) | 194 | | `Sending().SendTemplateButtons` | The method is designed to send a message with interactive buttons from the list of templates in a personal or group chat | [SendTemplateButtons](https://green-api.com/en/docs/api/sending/SendTemplateButtons/) | 195 | | `Sending().SendListMessage` | The method is designed to send a message with a selection button from a list of values to a personal or group chat | [SendListMessage](https://green-api.com/en/docs/api/sending/SendListMessage/) | 196 | | `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/) | 197 | | `Sending().SendFileByUrl` | The method is designed to send a file downloaded via a link | [SendFileByUrl](https://green-api.com/en/docs/api/sending/SendFileByUrl/) | 198 | | `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/) | 199 | | `Sending().SendLocation` | The method is designed to send a geolocation message | [SendLocation](https://green-api.com/en/docs/api/sending/SendLocation/) | 200 | | `Sending().SendContact` | The method is for sending a message with a contact | [SendContact](https://green-api.com/en/docs/api/sending/SendContact/) | 201 | | `Sending().SendLink` | The method is designed to send a message with a link that will add an image preview, title and description | [SendLink](https://green-api.com/en/docs/api/sending/SendLink/) | 202 | | `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/) | 203 | | `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/) | 204 | | `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/) | 205 | | `Service().GetAvatar` | The method returns the avatar of the correspondent or group chat | [GetAvatar](https://green-api.com/en/docs/api/service/GetAvatar/) | 206 | | `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/) | 207 | | `Service().GetContactInfo` | The method is designed to obtain information about the contact | [GetContactInfo](https://green-api.com/en/docs/api/service/GetContactInfo/) | 208 | | `Service().DeleteMessage` | The method deletes the message from chat | [DeleteMessage](https://green-api.com/en/docs/api/service/deleteMessage/) | 209 | | `Service().ArchiveChat` | The method archives the chat | [ArchiveChat](https://green-api.com/en/docs/api/service/archiveChat/) | 210 | | `Service().UnarchiveChat` | The method unarchives the chat | [UnarchiveChat](https://green-api.com/en/docs/api/service/unarchiveChat/) | 211 | | `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/) | 212 | | `Webhook().Start` | The method is designed to start receiving new notifications | | 213 | | `Webhook().Stop` | The method is designed to stop receiving new notifications | | 214 | 215 | ## Service methods documentation 216 | 217 | [Service methods documentation](https://green-api.com/en/docs/api/). 218 | 219 | ## License 220 | 221 | Licensed under [ 222 | Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) 223 | ](https://creativecommons.org/licenses/by-nd/4.0/) terms. 224 | Please see file [LICENSE](LICENSE). 225 | -------------------------------------------------------------------------------- /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]interface{}{ 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]interface{}{ 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]interface{}`). 96 | 97 | Ссылка на пример: [sendMessage/main.go](../examples/sendMessage/main.go). 98 | 99 | ``` 100 | response, _ := GreenAPI.Methods().Sending().SendMessage(map[string]interface{}{ 101 | "chatId": "11001234567@c.us", 102 | "message": "Any message", 103 | }) 104 | ``` 105 | 106 | ### Как получать входящие уведомления 107 | 108 | Чтобы начать получать уведомления, нужно передать функцию-обработчик в `Webhook().Start`. Функция-обработчик должна 109 | содержать 1 параметр (`body map[string]interface{}`). При получении нового уведомления ваша функция-обработчик будет 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]interface{}) { 118 | fmt.Println(body) 119 | }) 120 | ``` 121 | 122 | ### Как отправить сообщение с опросом 123 | 124 | Если у метода API есть необязательные параметры, то в метод библиотеки нужно передавать JSON (`map[string]interface{}`). 125 | 126 | Ссылка на пример: [sendPoll/main.go](../examples/sendPoll/main.go). 127 | 128 | ``` 129 | response, err := GreenAPI.Methods().Sending().SendPoll(map[string]interface{}{ 130 | "chatId": "11001234567@c.us", 131 | "message": "Please choose a color:", 132 | "options": []map[string]interface{}{ 133 | { 134 | "optionName": "Red", 135 | }, 136 | { 137 | "optionName": "Green", 138 | }, 139 | { 140 | "optionName": "Blue", 141 | }, 142 | }, 143 | }) 144 | ``` 145 | 146 | ## Список примеров 147 | 148 | | Описание | Ссылка на пример | 149 | |--------------------------------------|------------------------------------------------------------------| 150 | | Как создать группу | [createGroup/main.go](../examples/createGroup/main.go) | 151 | | Как отправить файл загрузкой с диска | [sendFileByUpload/main.go](../examples/sendFileByUpload/main.go) | 152 | | Как отправить файл по ссылке | [sendFileByURL/main.go](../examples/sendFileByURL/main.go) | 153 | | Как отправить сообщение | [sendMessage/main.go](../examples/sendMessage/main.go) | 154 | | Как получать входящие уведомления | [webhook/main.go](../examples/webhook/main.go) | 155 | | Как отправить сообщение с опросом | [sendPoll/main.go](../examples/sendPoll/main.go) | 156 | 157 | ## Список всех методов библиотеки 158 | 159 | | Метод API | Описание | Documentation link | 160 | |-----------------------------------|---------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| 161 | | `Account().GetSettings` | Метод предназначен для получения текущих настроек аккаунта | [GetSettings](https://green-api.com/docs/api/account/GetSettings/) | 162 | | `Account().GetWaSettings` | Метод предназначен для получения информации о аккаунте WhatsApp | [GetWaSettings](https://green-api.com/docs/api/account/GetWaSettings/) | 163 | | `Account().SetSettings` | Метод предназначен для установки настроек аккаунта | [SetSettings](https://green-api.com/docs/api/account/SetSettings/) | 164 | | `Account().GetStateInstance` | Метод предназначен для получения состояния аккаунта | [GetStateInstance](https://green-api.com/docs/api/account/GetStateInstance/) | 165 | | `Account().GetStatusInstance` | Метод предназначен для получения состояния сокета соединения инстанса аккаунта с WhatsApp | [GetStatusInstance](https://green-api.com/docs/api/account/GetStatusInstance/) | 166 | | `Account().Reboot` | Метод предназначен для перезапуска аккаунта | [Reboot](https://green-api.com/docs/api/account/Reboot/) | 167 | | `Account().Logout` | Метод предназначен для разлогинивания аккаунта | [Logout](https://green-api.com/docs/api/account/Logout/) | 168 | | `Account().QR` | Метод предназначен для получения QR-кода | [QR](https://green-api.com/docs/api/account/QR/) | 169 | | `Account().SetProfilePicture` | Метод предназначен для установки аватара аккаунта | [SetProfilePicture](https://green-api.com/docs/api/account/SetProfilePicture/) | 170 | | `Account().GetAuthorizationCode` | Метод предназначен для авторизации инстанса по номеру телефона | [GetAuthorizationCode](https://green-api.com/docs/api/account/GetAuthorizationCode/) | 171 | | `Device().GetDeviceInfo` | Метод предназначен для получения информации об устройстве (телефоне), на котором запущено приложение WhatsApp Business | [GetDeviceInfo](https://green-api.com/docs/api/phone/GetDeviceInfo/) | 172 | | `Groups().CreateGroup` | Метод предназначен для создания группового чата | [CreateGroup](https://green-api.com/docs/api/groups/CreateGroup/) | 173 | | `Groups().UpdateGroupName` | Метод изменяет наименование группового чата | [UpdateGroupName](https://green-api.com/docs/api/groups/UpdateGroupName/) | 174 | | `Groups().GetGroupData` | Метод получает данные группового чата | [GetGroupData](https://green-api.com/docs/api/groups/GetGroupData/) | 175 | | `Groups().AddGroupParticipant` | Метод добавляет участника в групповой чат | [AddGroupParticipant](https://green-api.com/docs/api/groups/AddGroupParticipant/) | 176 | | `Groups().RemoveGroupParticipant` | Метод удаляет участника из группового чата | [RemoveGroupParticipant](https://green-api.com/docs/api/groups/RemoveGroupParticipant/) | 177 | | `Groups().SetGroupAdmin` | Метод назначает участника группового чата администратором | [SetGroupAdmin](https://green-api.com/docs/api/groups/SetGroupAdmin/) | 178 | | `Groups().RemoveAdmin` | Метод лишает участника прав администрирования группового чата | [RemoveAdmin](https://green-api.com/docs/api/groups/RemoveAdmin/) | 179 | | `Groups().SetGroupPicture` | Метод устанавливает аватар группы | [SetGroupPicture](https://green-api.com/docs/api/groups/SetGroupPicture/) | 180 | | `Groups().LeaveGroup` | Метод производит выход пользователя текущего аккаунта из группового чата | [LeaveGroup](https://green-api.com/docs/api/groups/LeaveGroup/) | 181 | | `Journals().GetChatHistory` | Метод возвращает историю сообщений чата | [GetChatHistory](https://green-api.com/docs/api/journals/GetChatHistory/) | 182 | | `Journals().GetMessage` | Метод возвращает сообщение чата | [GetMessage](https://green-api.com/docs/api/journals/GetMessage/) | 183 | | `Journals().LastIncomingMessages` | Метод возвращает крайние входящие сообщения аккаунта | [LastIncomingMessages](https://green-api.com/docs/api/journals/LastIncomingMessages/) | 184 | | `Journals().LastOutgoingMessages` | Метод возвращает крайние отправленные сообщения аккаунта | [LastOutgoingMessages](https://green-api.com/docs/api/journals/LastOutgoingMessages/) | 185 | | `Queues().ShowMessagesQueue` | Метод предназначен для получения списка сообщений, находящихся в очереди на отправку | [ShowMessagesQueue](https://green-api.com/docs/api/queues/ShowMessagesQueue/) | 186 | | `Queues().ClearMessagesQueue` | Метод предназначен для очистки очереди сообщений на отправку | [ClearMessagesQueue](https://green-api.com/docs/api/queues/ClearMessagesQueue/) | 187 | | `ReadMark().ReadChat` | Метод предназначен для отметки сообщений в чате прочитанными | [ReadChat](https://green-api.com/docs/api/marks/ReadChat/) | 188 | | `Receiving().ReceiveNotification` | Метод предназначен для получения одного входящего уведомления из очереди уведомлений | [ReceiveNotification](https://green-api.com/docs/api/receiving/technology-http-api/ReceiveNotification/) | 189 | | `Receiving().DeleteNotification` | Метод предназначен для удаления входящего уведомления из очереди уведомлений | [DeleteNotification](https://green-api.com/docs/api/receiving/technology-http-api/DeleteNotification/) | 190 | | `Receiving().DownloadFile` | Метод предназначен для скачивания принятых и отправленных файлов | [DownloadFile](https://green-api.com/docs/api/receiving/files/DownloadFile/) | 191 | | `Sending().SendMessage` | Метод предназначен для отправки текстового сообщения в личный или групповой чат | [SendMessage](https://green-api.com/docs/api/sending/SendMessage/) | 192 | | `Sending().SendButtons` | Метод предназначен для отправки сообщения с кнопками в личный или групповой чат | [SendButtons](https://green-api.com/docs/api/sending/SendButtons/) | 193 | | `Sending().SendTemplateButtons` | Метод предназначен для отправки сообщения с интерактивными кнопками из перечня шаблонов в личный или групповой чат | [SendTemplateButtons](https://green-api.com/docs/api/sending/SendTemplateButtons/) | 194 | | `Sending().SendListMessage` | Метод предназначен для отправки сообщения с кнопкой выбора из списка значений в личный или групповой чат | [SendListMessage](https://green-api.com/docs/api/sending/SendListMessage/) | 195 | | `Sending().SendFileByUpload` | Метод предназначен для отправки файла, загружаемого через форму (form-data) | [SendFileByUpload](https://green-api.com/docs/api/sending/SendFileByUpload/) | 196 | | `Sending().SendFileByUrl` | Метод предназначен для отправки файла, загружаемого по ссылке | [SendFileByUrl](https://green-api.com/docs/api/sending/SendFileByUrl/) | 197 | | `Sending().UploadFile` | Метод предназначен для загрузки файла в облачное хранилище, который можно отправить методом SendFileByUrl | [UploadFile](https://green-api.com/docs/api/sending/UploadFile/) | 198 | | `Sending().SendLocation` | Метод предназначен для отправки сообщения геолокации | [SendLocation](https://green-api.com/docs/api/sending/SendLocation/) | 199 | | `Sending().SendContact` | Метод предназначен для отправки сообщения с контактом | [SendContact](https://green-api.com/docs/api/sending/SendContact/) | 200 | | `Sending().SendLink` | Метод предназначен для отправки сообщения со ссылкой, по которой будут добавлены превью изображения, заголовок и описание | [SendLink](https://green-api.com/docs/api/sending/SendLink/) | 201 | | `Sending().ForwardMessages` | Метод предназначен для пересылки сообщений в личный или групповой чат | [ForwardMessages](https://green-api.com/docs/api/sending/ForwardMessages/) | 202 | | `Sending().UploadFile` | Метод позволяет выгружать файл из локальной файловой системы, который позднее можно отправить методом SendFileByUrl | [UploadFile](https://green-api.com/docs/api/sending/UploadFile/) | 203 | | `Sending().SendPoll` | Метод предназначен для отправки сообщения с опросом в личный или групповой чат | [SendPoll](https://green-api.com/docs/api/sending/SendPoll/) | 204 | | `Service().CheckWhatsapp` | Метод проверяет наличие аккаунта WhatsApp на номере телефона | [CheckWhatsapp](https://green-api.com/docs/api/service/CheckWhatsapp/) | 205 | | `Service().GetAvatar` | Метод возвращает аватар корреспондента или группового чата | [GetAvatar](https://green-api.com/docs/api/service/GetAvatar/) | 206 | | `Service().GetContacts` | Метод предназначен для получения списка контактов текущего аккаунта | [GetContacts](https://green-api.com/docs/api/service/GetContacts/) | 207 | | `Service().GetContactInfo` | Метод предназначен для получения информации о контакте | [GetContactInfo](https://green-api.com/docs/api/service/GetContactInfo/) | 208 | | `Service().DeleteMessage` | Метод удаляет сообщение из чата | [DeleteMessage](https://green-api.com/docs/api/service/deleteMessage/) | 209 | | `Service().ArchiveChat` | Метод архивирует чат | [ArchiveChat](https://green-api.com/docs/api/service/archiveChat/) | 210 | | `Service().UnarchiveChat` | Метод разархивирует чат | [UnarchiveChat](https://green-api.com/docs/api/service/unarchiveChat/) | 211 | | `Service().SetDisappearingChat` | Метод предназначен для изменения настроек исчезающих сообщений в чатах | [SetDisappearingChat](https://green-api.com/docs/api/service/SetDisappearingChat/) | 212 | | `Webhook().Start` | Метод предназначен для старта получения новых уведомлений | | 213 | | `Webhook().Stop` | Метод предназначен для остановки получения новых уведомлений | | 214 | 215 | ## Документация по методам сервиса 216 | 217 | [Документация по методам сервиса](https://green-api.com/docs/api/). 218 | 219 | ## Лицензия 220 | 221 | Лицензировано на условиях [ 222 | Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) 223 | ](https://creativecommons.org/licenses/by-nd/4.0/). 224 | Смотрите файл [LICENSE](../LICENSE). 225 | -------------------------------------------------------------------------------- /examples/checkWhatsApp/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 8 | ) 9 | 10 | func main() { 11 | GreenAPI := api.GreenAPI{ 12 | IDInstance: "1101000001", 13 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 14 | } 15 | 16 | response, err := GreenAPI.Methods().Service().CheckWhatsapp(11001234567) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | 21 | fmt.Println(response) 22 | } 23 | -------------------------------------------------------------------------------- /examples/createGroup/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 8 | ) 9 | 10 | func main() { 11 | GreenAPI := api.GreenAPI{ 12 | IDInstance: "1101000001", 13 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 14 | } 15 | 16 | response, err := GreenAPI.Methods().Groups().CreateGroup("groupName", []string{ 17 | "11001234567@c.us", 18 | "11002345678@c.us", 19 | }) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | 24 | fmt.Println(response) 25 | } 26 | -------------------------------------------------------------------------------- /examples/createInstance/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 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]interface{}{ 15 | "stateWebhook": "yes", 16 | "incomingWebhook": "yes", 17 | }) 18 | if err != nil { 19 | fmt.Println(err) 20 | } 21 | 22 | fmt.Println(response) 23 | } 24 | -------------------------------------------------------------------------------- /examples/sendFileByURL/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 8 | ) 9 | 10 | func main() { 11 | GreenAPI := api.GreenAPI{ 12 | IDInstance: "1101000001", 13 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 14 | } 15 | 16 | response, err := GreenAPI.Methods().Sending().SendFileByUrl(map[string]interface{}{ 17 | "chatId": "11001234567@c.us", 18 | "urlFile": "https://go.dev/blog/go-brand/Go-Logo/SVG/Go-Logo_Blue.svg", 19 | "fileName": "Go-Logo_Blue.svg", 20 | }) 21 | if err != nil { 22 | log.Fatal(err) 23 | } 24 | 25 | fmt.Println(response) 26 | } 27 | -------------------------------------------------------------------------------- /examples/sendFileByUpload/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 8 | ) 9 | 10 | func main() { 11 | GreenAPI := api.GreenAPI{ 12 | IDInstance: "1101000001", 13 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 14 | } 15 | 16 | response, err := GreenAPI.Methods().Sending().SendFileByUpload("example.png", map[string]interface{}{ 17 | "chatId": "11001234567@c.us", 18 | }) 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | 23 | fmt.Println(response) 24 | } 25 | -------------------------------------------------------------------------------- /examples/sendMessage/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 8 | ) 9 | 10 | func main() { 11 | GreenAPI := api.GreenAPI{ 12 | IDInstance: "1101000001", 13 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 14 | } 15 | 16 | response, err := GreenAPI.Methods().Sending().SendMessage(map[string]interface{}{ 17 | "chatId": "11001234567@c.us", 18 | "message": "Any message", 19 | }) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | 24 | fmt.Println(response) 25 | } 26 | -------------------------------------------------------------------------------- /examples/sendPoll/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 8 | ) 9 | 10 | func main() { 11 | GreenAPI := api.GreenAPI{ 12 | IDInstance: "1101000001", 13 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 14 | } 15 | 16 | response, err := GreenAPI.Methods().Sending().SendPoll(map[string]interface{}{ 17 | "chatId": "11001234567@c.us", 18 | "message": "Please choose a color:", 19 | "options": []map[string]interface{}{ 20 | { 21 | "optionName": "Red", 22 | }, 23 | { 24 | "optionName": "Green", 25 | }, 26 | { 27 | "optionName": "Blue", 28 | }, 29 | }, 30 | }) 31 | if err != nil { 32 | log.Fatal(err) 33 | } 34 | 35 | fmt.Println(response) 36 | } 37 | -------------------------------------------------------------------------------- /examples/uploadFile/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "path" 8 | 9 | "github.com/green-api/whatsapp-api-client-golang/pkg/api" 10 | ) 11 | 12 | func main() { 13 | GreenAPI := api.GreenAPI{ 14 | IDInstance: "1101000001", 15 | APITokenInstance: "d75b3a66374942c5b3c019c698abc2067e151558acbd412345", 16 | } 17 | 18 | uploadFileResponse, err := GreenAPI.Methods().Sending().UploadFile("example.png") 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | 23 | fmt.Println(uploadFileResponse) 24 | 25 | urlFile := uploadFileResponse["urlFile"].(string) 26 | request, _ := http.NewRequest("GET", urlFile, nil) 27 | fileName := path.Base(request.URL.Path) 28 | 29 | sendFileByUrlResponse, err := GreenAPI.Methods().Sending().SendFileByUrl(map[string]interface{}{ 30 | "chatId": "11001234567@c.us", 31 | "urlFile": urlFile, 32 | "fileName": fileName, 33 | }) 34 | if err != nil { 35 | log.Fatal(err) 36 | } 37 | 38 | fmt.Println(sendFileByUrlResponse) 39 | } 40 | -------------------------------------------------------------------------------- /examples/webhook/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 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]interface{}) { 18 | fmt.Println(body) 19 | }) 20 | } 21 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/green-api/whatsapp-api-client-golang 2 | 3 | go 1.19 4 | 5 | require github.com/gabriel-vasile/mimetype v1.4.3 6 | 7 | require golang.org/x/net v0.22.0 // indirect 8 | -------------------------------------------------------------------------------- /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.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= 4 | golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= 5 | -------------------------------------------------------------------------------- /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 | 26 | ErrorChannel: make(chan error), 27 | } 28 | } 29 | 30 | func (a GreenAPI) Request(method, APIMethod string, data map[string]interface{}, filePath string) (map[string]interface{}, error) { 31 | url := a.getURL(method, APIMethod, data) 32 | 33 | response, err := executeRequest(method, url, data, filePath) 34 | 35 | return response.(map[string]interface{}), err 36 | } 37 | 38 | func (a GreenAPI) PartnerRequest(method, APIMethod string, data map[string]interface{}, filePath string) (map[string]interface{}, error) { 39 | url, err := a.getPartnerURL(APIMethod) 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | response, err := executeRequest(method, url, data, filePath) 45 | 46 | return response.(map[string]interface{}), err 47 | } 48 | 49 | func (a GreenAPI) ArrayPartnerRequest(method, APIMethod string, data map[string]interface{}, filePath string) ([]interface{}, error) { 50 | url, err := a.getPartnerURL(APIMethod) 51 | if err != nil { 52 | return nil, err 53 | } 54 | 55 | response, err := executeRequest(method, url, data, filePath) 56 | 57 | return response.([]interface{}), err 58 | } 59 | 60 | func (a GreenAPI) RawRequest(method, APIMethod string, data map[string]interface{}, filePath string) (interface{}, error) { 61 | url := a.getURL(method, APIMethod, data) 62 | 63 | return executeRequest(method, url, data, filePath) 64 | } 65 | 66 | func (a GreenAPI) ArrayRequest(method, APIMethod string, data map[string]interface{}, filePath string) ([]interface{}, error) { 67 | url := a.getURL(method, APIMethod, data) 68 | 69 | response, err := executeRequest(method, url, data, filePath) 70 | 71 | return response.([]interface{}), err 72 | } 73 | 74 | func (a GreenAPI) getURL(method, APIMethod string, data map[string]interface{}) string { 75 | if a.URL != "" { 76 | return a.URL 77 | } 78 | 79 | var url strings.Builder 80 | 81 | if APIMethod == "SendFileByUpload" || APIMethod == "UploadFile" { 82 | url.WriteString("https://media.green-api.com") 83 | } else { 84 | url.WriteString("https://api.green-api.com") 85 | } 86 | 87 | url.WriteString("/") 88 | url.WriteString("waInstance") 89 | url.WriteString(a.IDInstance) 90 | url.WriteString("/") 91 | url.WriteString(APIMethod) 92 | url.WriteString("/") 93 | url.WriteString(a.APITokenInstance) 94 | 95 | if method == "DELETE" { 96 | url.WriteString("/") 97 | url.WriteString(strconv.Itoa(data["receiptId"].(int))) 98 | } 99 | 100 | return url.String() 101 | } 102 | 103 | func (a GreenAPI) getPartnerURL(APIMethod string) (string, error) { 104 | if a.PartnerToken == "" { 105 | return "", fmt.Errorf("error while generating URL: PartnerToken is empty") 106 | } 107 | 108 | var url strings.Builder 109 | 110 | url.WriteString("https://api.green-api.com") 111 | 112 | url.WriteString("/") 113 | url.WriteString("partner") 114 | url.WriteString("/") 115 | url.WriteString(APIMethod) 116 | url.WriteString("/") 117 | url.WriteString(a.PartnerToken) 118 | 119 | return url.String(), nil 120 | } 121 | -------------------------------------------------------------------------------- /pkg/api/http.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "mime/multipart" 10 | "net/http" 11 | "os" 12 | "strings" 13 | 14 | "github.com/gabriel-vasile/mimetype" 15 | ) 16 | 17 | func executeRequest(method, url string, data map[string]interface{}, filePath string) (interface{}, 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]interface{}, filePath string) (*http.Request, error) { 38 | if 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 | if data != nil { 68 | for key, value := range data { 69 | err := writer.WriteField(key, value.(string)) 70 | if err != nil { 71 | return nil, err 72 | } 73 | } 74 | } 75 | 76 | file, err := os.Open(filePath) 77 | if err != nil { 78 | return nil, err 79 | } 80 | 81 | part, err := writer.CreateFormFile("file", filePath) 82 | if err != nil { 83 | return nil, err 84 | } 85 | 86 | _, err = io.Copy(part, file) 87 | if err != nil { 88 | return nil, err 89 | } 90 | 91 | err = file.Close() 92 | if err != nil { 93 | return nil, err 94 | } 95 | 96 | err = writer.Close() 97 | if err != nil { 98 | return nil, err 99 | } 100 | 101 | req, err := http.NewRequest(method, url, buffer) 102 | if err != nil { 103 | return nil, err 104 | } 105 | 106 | req.Header.Set("Content-Type", writer.FormDataContentType()) 107 | 108 | return req, nil 109 | } 110 | 111 | func getUploadFileRequest(method, url string, filePath string) (*http.Request, error) { 112 | buf, err := os.ReadFile(filePath) 113 | if err != nil { 114 | return nil, err 115 | } 116 | 117 | req, err := http.NewRequest(method, url, bytes.NewBuffer(buf)) 118 | if err != nil { 119 | return nil, err 120 | } 121 | 122 | MIMEType := mimetype.Detect(buf).String() 123 | 124 | req.Header.Set("Content-Type", MIMEType) 125 | 126 | return req, nil 127 | } 128 | 129 | func getResponse(resp *http.Response) (interface{}, error) { 130 | body, err := io.ReadAll(resp.Body) 131 | if err != nil { 132 | return nil, err 133 | } 134 | 135 | err = resp.Body.Close() 136 | if err != nil { 137 | return nil, err 138 | } 139 | 140 | if resp.StatusCode != http.StatusOK { 141 | return nil, errors.New(fmt.Sprintf("StatusCode = %d. Body = %s.", resp.StatusCode, body)) 142 | } 143 | 144 | var data interface{} 145 | 146 | err = json.Unmarshal(body, &data) 147 | if err != nil { 148 | return nil, err 149 | } 150 | 151 | return data, nil 152 | } 153 | -------------------------------------------------------------------------------- /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]interface{})) { 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 | continue 26 | } else { 27 | body := response["body"] 28 | handler(body.(map[string]interface{})) 29 | 30 | receiptId := int(response["receiptId"].(float64)) 31 | response, err = w.GreenAPI.Methods().Receiving().DeleteNotification(receiptId) 32 | if err != nil { 33 | w.ErrorChannel <- err 34 | 35 | time.Sleep(time.Second * 5) 36 | 37 | continue 38 | } 39 | } 40 | } 41 | } 42 | 43 | func (w GreenAPIWebhook) Stop() { 44 | running = false 45 | } 46 | -------------------------------------------------------------------------------- /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 presents methods for working with the device (phone). 16 | // https://green-api.com/en/docs/api/phone/ 17 | func (c GreenAPICategories) Device() methods.DeviceCategory { 18 | return methods.DeviceCategory{GreenAPI: c.GreenAPI} 19 | } 20 | 21 | // Groups category presents methods for working with group chats. 22 | // https://green-api.com/en/docs/api/groups/ 23 | func (c GreenAPICategories) Groups() methods.GroupsCategory { 24 | return methods.GroupsCategory{GreenAPI: c.GreenAPI} 25 | } 26 | 27 | // Journals present methods for working with incoming and outgoing messages. 28 | // https://green-api.com/en/docs/api/journals/ 29 | func (c GreenAPICategories) Journals() methods.JournalsCategory { 30 | return methods.JournalsCategory{GreenAPI: c.GreenAPI} 31 | } 32 | 33 | // Queues category presents methods for working with a messages queue. 34 | // https://green-api.com/en/docs/api/queues/ 35 | func (c GreenAPICategories) Queues() methods.QueuesCategory { 36 | return methods.QueuesCategory{GreenAPI: c.GreenAPI} 37 | } 38 | 39 | // ReadMark category presents methods for working with chat read mark. 40 | // https://green-api.com/en/docs/api/marks/ 41 | func (c GreenAPICategories) ReadMark() methods.ReadMarkCategory { 42 | return methods.ReadMarkCategory{GreenAPI: c.GreenAPI} 43 | } 44 | 45 | // Receiving category presents methods for working with receiving events. 46 | // https://green-api.com/en/docs/api/receiving/ 47 | func (c GreenAPICategories) Receiving() methods.ReceivingCategory { 48 | return methods.ReceivingCategory{GreenAPI: c.GreenAPI} 49 | } 50 | 51 | // Sending category presents methods for sending different messages. 52 | // https://green-api.com/en/docs/api/sending/ 53 | func (c GreenAPICategories) Sending() methods.SendingCategory { 54 | return methods.SendingCategory{GreenAPI: c.GreenAPI} 55 | } 56 | 57 | // Service category presents different service methods. 58 | // https://green-api.com/en/docs/api/service/ 59 | func (c GreenAPICategories) Service() methods.ServiceCategory { 60 | return methods.ServiceCategory{GreenAPI: c.GreenAPI} 61 | } 62 | 63 | // Partner category presents exclusive methods for partners. 64 | // The partnership scheme involves deeper integration with the service 65 | // and working with a larger number of instances on your side: 66 | // 67 | // * Instance management via API 68 | // * Postpaid billing system (starting from the second month of operation) 69 | // * Daily billing (for created and not deleted instances) 70 | // * Dedicated support line 71 | // For questions regarding connection to the partnership scheme 72 | // and additional conditions, please contact us via email 73 | // at support@green-api.com or via chat on the website. 74 | // https://green-api.com/en/docs/partners/ 75 | func (c GreenAPICategories) Partner() methods.PartnerCategory { 76 | return methods.PartnerCategory{GreenAPI: c.GreenAPI} 77 | } 78 | -------------------------------------------------------------------------------- /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]interface{}, 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]interface{}, 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]interface{}) (map[string]interface{}, error) { 22 | method := "GET" 23 | if parameters != nil { 24 | method = "POST" 25 | } 26 | 27 | return c.GreenAPI.Request(method, "setSettings", parameters, "") 28 | } 29 | 30 | // GetStateInstance is designed to get the state of the account. 31 | // https://green-api.com/en/docs/api/account/GetStateInstance/ 32 | func (c AccountCategory) GetStateInstance() (map[string]interface{}, error) { 33 | return c.GreenAPI.Request("GET", "getStateInstance", nil, "") 34 | } 35 | 36 | // GetStatusInstance is designed to get the socket connection state 37 | // of the account instance with WhatsApp. 38 | // https://green-api.com/en/docs/api/account/GetStatusInstance/ 39 | func (c AccountCategory) GetStatusInstance() (map[string]interface{}, error) { 40 | return c.GreenAPI.Request("GET", "getStatusInstance", nil, "") 41 | } 42 | 43 | // Reboot is designed to restart the account. 44 | // https://green-api.com/en/docs/api/account/Reboot/ 45 | func (c AccountCategory) Reboot() (map[string]interface{}, error) { 46 | return c.GreenAPI.Request("GET", "reboot", nil, "") 47 | } 48 | 49 | // Logout is designed to unlogin the account. 50 | // https://green-api.com/en/docs/api/account/Logout/ 51 | func (c AccountCategory) Logout() (map[string]interface{}, error) { 52 | return c.GreenAPI.Request("GET", "logout", nil, "") 53 | } 54 | 55 | // QR is designed to get a QR code. 56 | // https://green-api.com/en/docs/api/account/QR/ 57 | func (c AccountCategory) QR() (map[string]interface{}, error) { 58 | return c.GreenAPI.Request("GET", "qr", nil, "") 59 | } 60 | 61 | // SetProfilePicture is designed to set the avatar of the account. 62 | // https://green-api.com/en/docs/api/account/SetProfilePicture/ 63 | func (c AccountCategory) SetProfilePicture(filePath string) (map[string]interface{}, error) { 64 | return c.GreenAPI.Request("POST", "setProfilePicture", nil, filePath) 65 | } 66 | 67 | // GetAuthorizationCode is designed to authorize an instance by phone number. 68 | // https://green-api.com/en/docs/api/account/GetAuthorizationCode/ 69 | func (c AccountCategory) GetAuthorizationCode(phoneNumber int) (map[string]interface{}, error) { 70 | return c.GreenAPI.Request("POST", "getAuthorizationCode", map[string]interface{}{ 71 | "phoneNumber": phoneNumber, 72 | }, "") 73 | } 74 | -------------------------------------------------------------------------------- /pkg/categories/methods/base_category.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type GreenAPIInterface interface { 4 | Request(method, APIMethod string, data map[string]interface{}, filePath string) (map[string]interface{}, error) 5 | RawRequest(method, APIMethod string, data map[string]interface{}, filePath string) (interface{}, error) 6 | ArrayRequest(method, APIMethod string, data map[string]interface{}, filePath string) ([]interface{}, error) 7 | PartnerRequest(method, APIMethod string, data map[string]interface{}, filePath string) (map[string]interface{}, error) 8 | ArrayPartnerRequest(method, APIMethod string, data map[string]interface{}, filePath string) ([]interface{}, error) 9 | } 10 | -------------------------------------------------------------------------------- /pkg/categories/methods/device.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type DeviceCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // GetDeviceInfo is designed to get information about the device (phone) 8 | // on which the WhatsApp Business application is running. 9 | // https://green-api.com/en/docs/api/phone/GetDeviceInfo/ 10 | func (c DeviceCategory) GetDeviceInfo() (map[string]interface{}, error) { 11 | return c.GreenAPI.Request("GET", "getDeviceInfo", nil, "") 12 | } 13 | -------------------------------------------------------------------------------- /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]interface{}, error) { 10 | return c.GreenAPI.Request("POST", "createGroup", map[string]interface{}{ 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]interface{}, error) { 19 | return c.GreenAPI.Request("POST", "updateGroupName", map[string]interface{}{ 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]interface{}, error) { 28 | return c.GreenAPI.Request("POST", "getGroupData", map[string]interface{}{ 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]interface{}, error) { 36 | return c.GreenAPI.Request("POST", "addGroupParticipant", map[string]interface{}{ 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]interface{}, error) { 45 | return c.GreenAPI.Request("POST", "removeGroupParticipant", map[string]interface{}{ 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]interface{}, error) { 54 | return c.GreenAPI.Request("POST", "setGroupAdmin", map[string]interface{}{ 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]interface{}, error) { 63 | return c.GreenAPI.Request("POST", "removeAdmin", map[string]interface{}{ 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]interface{}, error) { 72 | return c.GreenAPI.Request("POST", "setGroupPicture", map[string]interface{}{ 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]interface{}, error) { 80 | return c.GreenAPI.Request("POST", "leaveGroup", map[string]interface{}{ 81 | "groupId": groupId, 82 | }, "") 83 | } 84 | -------------------------------------------------------------------------------- /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]interface{}) ([]interface{}, 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]interface{}, error) { 16 | return c.GreenAPI.Request("POST", "getMessage", map[string]interface{}{ 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]interface{}) ([]interface{}, 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]interface{}) ([]interface{}, error) { 32 | return c.GreenAPI.ArrayRequest("GET", "lastOutgoingMessages", parameters, "") 33 | } 34 | -------------------------------------------------------------------------------- /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]interface{}) (map[string]interface{}, 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]interface{}, error) { 16 | return c.GreenAPI.PartnerRequest("POST", "deleteInstanceAccount", map[string]interface{}{"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() ([]interface{}, error) { 22 | return c.GreenAPI.ArrayPartnerRequest("GET", "getInstances", nil, "") 23 | } 24 | -------------------------------------------------------------------------------- /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() ([]interface{}, 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]interface{}, error) { 17 | return c.GreenAPI.Request("GET", "clearMessagesQueue", nil, "") 18 | } 19 | -------------------------------------------------------------------------------- /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]interface{}) (map[string]interface{}, error) { 10 | return c.GreenAPI.Request("POST", "readChat", parameters, "") 11 | } 12 | -------------------------------------------------------------------------------- /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]interface{}, error) { 11 | response, err := c.GreenAPI.RawRequest("GET", "receiveNotification", nil, "") 12 | 13 | if response != nil { 14 | return response.(map[string]interface{}), 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]interface{}, error) { 24 | return c.GreenAPI.Request("DELETE", "deleteNotification", map[string]interface{}{ 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]interface{}, error) { 32 | return c.GreenAPI.Request("POST", "downloadFile", map[string]interface{}{ 33 | "chatId": chatId, 34 | "idMessage": idMessage, 35 | }, "") 36 | } 37 | -------------------------------------------------------------------------------- /pkg/categories/methods/sending.go: -------------------------------------------------------------------------------- 1 | package methods 2 | 3 | type SendingCategory struct { 4 | GreenAPI GreenAPIInterface 5 | } 6 | 7 | // SendMessage is designed to send a text message to a personal or group chat. 8 | // https://green-api.com/en/docs/api/sending/SendMessage/ 9 | func (c SendingCategory) SendMessage(parameters map[string]interface{}) (map[string]interface{}, error) { 10 | return c.GreenAPI.Request("POST", "sendMessage", parameters, "") 11 | } 12 | 13 | // SendButtons is designed to send a message with buttons 14 | // to a personal or group chat. 15 | // https://green-api.com/en/docs/api/sending/SendButtons/ 16 | func (c SendingCategory) SendButtons(parameters map[string]interface{}) (map[string]interface{}, error) { 17 | return c.GreenAPI.Request("POST", "sendButtons", parameters, "") 18 | } 19 | 20 | // SendTemplateButtons is designed to send a message with interactive buttons 21 | // from the list of templates in a personal or group chat. 22 | // https://green-api.com/en/docs/api/sending/SendTemplateButtons/ 23 | func (c SendingCategory) SendTemplateButtons(parameters map[string]interface{}) (map[string]interface{}, error) { 24 | return c.GreenAPI.Request("POST", "sendTemplateButtons", parameters, "") 25 | } 26 | 27 | // SendListMessage is designed to send a message with a selection button 28 | // from a list of values to a personal or group chat. 29 | // https://green-api.com/en/docs/api/sending/SendListMessage/ 30 | func (c SendingCategory) SendListMessage(parameters map[string]interface{}) (map[string]interface{}, error) { 31 | return c.GreenAPI.Request("POST", "sendListMessage", parameters, "") 32 | } 33 | 34 | // SendFileByUpload is designed to send a file loaded through a form-data. 35 | // https://green-api.com/en/docs/api/sending/SendFileByUpload/ 36 | func (c SendingCategory) SendFileByUpload(filePath string, parameters map[string]interface{}) (map[string]interface{}, error) { 37 | return c.GreenAPI.Request("POST", "sendFileByUpload", parameters, filePath) 38 | } 39 | 40 | // SendFileByUrl is designed to send a file downloaded via a link. 41 | // https://green-api.com/en/docs/api/sending/SendFileByUrl/ 42 | func (c SendingCategory) SendFileByUrl(parameters map[string]interface{}) (map[string]interface{}, error) { 43 | return c.GreenAPI.Request("POST", "sendFileByUrl", parameters, "") 44 | } 45 | 46 | // SendLocation is designed to send a geolocation message. 47 | // https://green-api.com/en/docs/api/sending/SendLocation/ 48 | func (c SendingCategory) SendLocation(parameters map[string]interface{}) (map[string]interface{}, error) { 49 | return c.GreenAPI.Request("POST", "sendLocation", parameters, "") 50 | } 51 | 52 | // SendContact is for sending a message with a contact. 53 | // https://green-api.com/en/docs/api/sending/SendContact/ 54 | func (c SendingCategory) SendContact(parameters map[string]interface{}) (map[string]interface{}, error) { 55 | return c.GreenAPI.Request("POST", "sendContact", parameters, "") 56 | } 57 | 58 | // The method is deprecated. Please use SendMessage. 59 | func (c SendingCategory) SendLink(parameters map[string]interface{}) (map[string]interface{}, error) { 60 | return c.GreenAPI.Request("POST", "sendLink", parameters, "") 61 | } 62 | 63 | // ForwardMessages is designed for forwarding messages 64 | // to a personal or group chat. 65 | // https://green-api.com/en/docs/api/sending/ForwardMessages/ 66 | func (c SendingCategory) ForwardMessages(chatId, chatIdFrom string, messages []string) (map[string]interface{}, error) { 67 | return c.GreenAPI.Request("POST", "forwardMessages", map[string]interface{}{ 68 | "chatId": chatId, 69 | "chatIdFrom": chatIdFrom, 70 | "messages": messages, 71 | }, "") 72 | } 73 | 74 | // UploadFile allows you to upload a file from the local file system, 75 | // which can later be sent using the SendFileByUrl method. 76 | // https://green-api.com/en/docs/api/sending/UploadFile/ 77 | func (c SendingCategory) UploadFile(filePath string) (map[string]interface{}, error) { 78 | return c.GreenAPI.Request("POST", "uploadFile", nil, filePath) 79 | } 80 | 81 | // SendPoll is designed for sending messages with a poll 82 | // to a private or group chat. 83 | // https://green-api.com/en/docs/api/sending/SendPoll/ 84 | func (c SendingCategory) SendPoll(parameters map[string]interface{}) (map[string]interface{}, error) { 85 | return c.GreenAPI.Request("POST", "sendPoll", parameters, "") 86 | } 87 | -------------------------------------------------------------------------------- /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]interface{}, error) { 10 | return c.GreenAPI.Request("POST", "checkWhatsapp", map[string]interface{}{ 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]interface{}, error) { 18 | return c.GreenAPI.Request("POST", "getAvatar", map[string]interface{}{ 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() ([]interface{}, 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]interface{}, error) { 32 | return c.GreenAPI.Request("POST", "getContactInfo", map[string]interface{}{ 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]interface{}, error) { 40 | return c.GreenAPI.Request("POST", "deleteMessage", map[string]interface{}{ 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]interface{}, error) { 49 | return c.GreenAPI.Request("POST", "archiveChat", map[string]interface{}{ 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]interface{}, error) { 57 | return c.GreenAPI.Request("POST", "unarchiveChat", map[string]interface{}{ 58 | "chatId": chatId, 59 | }, "") 60 | } 61 | 62 | // SetDisappearingChat is designed to change the settings 63 | // of disappearing messages in chats. 64 | // https://green-api.com/en/docs/api/service/SetDisappearingChat/ 65 | func (c ServiceCategory) SetDisappearingChat(parameters map[string]interface{}) (map[string]interface{}, error) { 66 | method := "GET" 67 | if parameters != nil { 68 | method = "POST" 69 | } 70 | 71 | return c.GreenAPI.Request(method, "setDisappearingChat", parameters, "") 72 | } 73 | --------------------------------------------------------------------------------