├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── apihelper.go ├── example_test.go ├── optionals.go ├── telebot.go ├── telebot_test.go ├── test_data ├── go.jpg ├── go.png ├── go.webp ├── record.mp3 ├── record.ogg ├── record.wav └── test_video.mp4 └── types ├── inline_types.go ├── types.go └── types_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # MaxOSX 11 | .DS_Store 12 | 13 | # Architecture specific extensions/prefixes 14 | *.[568vq] 15 | [568vq].out 16 | 17 | *.cgo1.go 18 | *.cgo2.c 19 | _cgo_defun.c 20 | _cgo_gotypes.go 21 | _cgo_export.* 22 | 23 | _testmain.go 24 | 25 | *.exe 26 | *.test 27 | *.prof 28 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.4 5 | - 1.5 6 | - tip 7 | script: 8 | - go test -v ./... 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gotelebot 2 | 3 | [![GoDoc](https://godoc.org/github.com/eternnoir/gotelebot?status.svg)](https://godoc.org/github.com/eternnoir/gotelebot) 4 | 5 | Golang (Go) implementation for the Telegram Bot API. 6 | 7 | This project provide a wrapper around the Telegram Bot API with golang. You can easy to ues telegram bot api 8 | in golang way by use this project. And gotelebot provided polling method let developer easy to get new messages. 9 | 10 | Almost all method in Telegram bot api have been implement. 11 | While official telegram bot api update, this project will update as soon as possible. 12 | 13 | ## Installation 14 | 15 | ``` 16 | go get github.com/eternnoir/gotelebot 17 | ``` 18 | 19 | ## Document 20 | 21 | Full godoc document [http://godoc.org/github.com/eternnoir/gotelebot](http://godoc.org/github.com/eternnoir/gotelebot) 22 | 23 | ### Echo Bot Example 24 | 25 | ```go 26 | package main 27 | 28 | import ( 29 | "fmt" 30 | "github.com/eternnoir/gotelebot" 31 | ) 32 | 33 | func main() { 34 | // Echo Bot example. 35 | 36 | // Create gotelebot instance 37 | bot := gotelebot.InitTeleBot("TOKEN") 38 | // Start get new message whit goroutine and 60s timeout. 39 | go bot.StartPolling(true, 60) 40 | go processNewMessage(bot) 41 | processNewInlineQuery(bot) 42 | } 43 | 44 | func processNewMessage(bot *gotelebot.TeleBot) { 45 | newMsgChan := bot.Messages 46 | for { 47 | m := <-newMsgChan // Get new messaage, when new message arrive. 48 | fmt.Printf("Get Message:%#v \n", m) 49 | if m.Text != "" { // Check message is text message. 50 | bot.SendMessage(int(m.Chat.Id), m.Text, nil) 51 | } 52 | } 53 | } 54 | 55 | func processNewInlineQuery(bot *gotelebot.TeleBot) { 56 | newQuery := bot.InlineQuerys 57 | for { 58 | q := <-newQuery 59 | fmt.Printf("Get NewInlineQuery:%#v \n", q) 60 | if q.Query != "" { // Only return result when query string not empty. 61 | result1 := types.NewInlineQueryResultArticl() 62 | result1.Id = "1" 63 | result1.Title = "Example" 64 | result1.MessageText = "Hi" + q.Query 65 | _, err := bot.AnswerInlineQuery(q.Id, []interface{}{result1}, nil) 66 | if err != nil { 67 | fmt.Println(err) 68 | } 69 | } 70 | } 71 | } 72 | 73 | 74 | ``` 75 | 76 | ## Telegram Bot API Support 77 | 78 | ## Methods 79 | 80 | | Telegram Bot API Method | gotelebot Method | Status | 81 | |-------------------------|----------------------|-------------| 82 | | getMe | GetMe | Supported | 83 | | sendMessage | SendMessage | Supported | 84 | | forwardMessage | ForwardMessage | Supported | 85 | | sendPhoto | SendPhoto | Supported | 86 | | sendAudio | SendAudio | Supported | 87 | | sendDocument | SendDocument | Supported | 88 | | sendSticker | SendSticker | Supported | 89 | | sendVideo | SendVideo | Supported | 90 | | sendVoice | SendVoice | Supported | 91 | | sendLocation | SendLocation | Supported | 92 | | sendChatAction | SendChatAction | Supported | 93 | | getUserProfilePhotos | GetUserProfilePhotos | Supported | 94 | | getUpdates | GetUpdates | Supported | 95 | | getFile | GetFile | Supported | 96 | | inline mode | inline mode | Supported | 97 | 98 | 99 | 100 | # Change Log 101 | 102 | ## 2015-10-12 103 | * New type ```Chat``` support. More information : https://core.telegram.org/bots/api#recent-changes 104 | -------------------------------------------------------------------------------- /apihelper.go: -------------------------------------------------------------------------------- 1 | package gotelebot 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "io/ioutil" 10 | "mime/multipart" 11 | "net/http" 12 | "net/url" 13 | "os" 14 | "path/filepath" 15 | "reflect" 16 | 17 | "github.com/eternnoir/gotelebot/types" 18 | ) 19 | 20 | func sendGetRequest(method string, token string, params url.Values) ([]byte, error) { 21 | url := fmt.Sprintf("https://api.telegram.org/bot%s/%s?%s", 22 | token, method, params.Encode()) 23 | 24 | resp, err := http.Get(url) 25 | if err != nil { 26 | return []byte{}, err 27 | } 28 | return checkResult(resp) 29 | } 30 | 31 | func sendRequest(method, token, name, path string, params url.Values) ([]byte, error) { 32 | body := &bytes.Buffer{} 33 | writer := multipart.NewWriter(body) 34 | if path != "" { 35 | file, err := os.Open(path) 36 | if err != nil { 37 | return nil, err 38 | } 39 | defer file.Close() 40 | part, err := writer.CreateFormFile(name, filepath.Base(path)) 41 | if err != nil { 42 | return nil, err 43 | } 44 | 45 | if _, err = io.Copy(part, file); err != nil { 46 | return nil, err 47 | } 48 | } 49 | for field, values := range params { 50 | if len(values) > 0 { 51 | writer.WriteField(field, values[0]) 52 | } 53 | } 54 | if err := writer.Close(); err != nil { 55 | return nil, err 56 | } 57 | url := fmt.Sprintf("https://api.telegram.org/bot%s/%s", token, method) 58 | req, err := http.NewRequest("POST", url, body) 59 | if err != nil { 60 | return nil, err 61 | } 62 | req.Header.Add("Content-Type", writer.FormDataContentType()) 63 | client := &http.Client{} 64 | resp, err := client.Do(req) 65 | if err != nil { 66 | return nil, err 67 | } 68 | return checkResult(resp) 69 | 70 | } 71 | 72 | func checkResult(resp *http.Response) ([]byte, error) { 73 | if resp.StatusCode != 200 { 74 | con, _ := ioutil.ReadAll(resp.Body) 75 | return nil, errors.New(fmt.Sprintf("gotelebot error:%s-%s", resp.Status, con)) 76 | } 77 | jsonStr, err := ioutil.ReadAll(resp.Body) 78 | if err != nil { 79 | return nil, err 80 | } 81 | var result map[string]interface{} 82 | err = json.Unmarshal(jsonStr, &result) 83 | if err != nil { 84 | return nil, errors.New(fmt.Sprintf("gotelebot The server returned an invalid JSON response. %s-%s", 85 | resp.Status, resp.Body)) 86 | } 87 | if result["ok"] != true { 88 | return nil, errors.New(fmt.Sprintf("gotelebot: Error.ErrorCode: %s-Description%s", 89 | result["errorCode"], result["description"])) 90 | } 91 | str, errs := json.Marshal(result["result"]) 92 | if errs != nil { 93 | fmt.Println("Error encoding JSON") 94 | return nil, errors.New(fmt.Sprintln("gotelebot")) 95 | } 96 | return []byte(str), nil 97 | } 98 | 99 | func makeRequest(method, token, name, filepath string, params url.Values) ([]byte, error) { 100 | return sendRequest(method, token, name, filepath, params) 101 | } 102 | 103 | func getMe(token string) (*types.User, error) { 104 | jsonStr, err := sendGetRequest("getMe", token, url.Values{}) 105 | if err != nil { 106 | return nil, err 107 | } 108 | var user types.User 109 | err = json.Unmarshal(jsonStr, &user) 110 | if err != nil { 111 | return nil, err 112 | } 113 | return &user, nil 114 | } 115 | 116 | func getUpdates(token, offset, limit, timeout string) ([]*types.Update, error) { 117 | payload := url.Values{} 118 | if offset != "" { 119 | payload.Add("offset", offset) 120 | } 121 | if limit != "" { 122 | payload.Add("limit", limit) 123 | } 124 | if timeout != "" { 125 | payload.Add("timeout", timeout) 126 | } 127 | jsonStr, err := sendGetRequest("getUpdates", token, payload) 128 | if err != nil { 129 | return nil, err 130 | } 131 | var result []*types.Update 132 | err = json.Unmarshal(jsonStr, &result) 133 | if err != nil { 134 | return nil, err 135 | } 136 | return result, nil 137 | } 138 | 139 | func getUserProfilePhotos(token, userid string, opt *GetUserProfilePhotosOptional) (*types.UserProfilePhotos, error) { 140 | payload := url.Values{} 141 | payload.Add("user_id", userid) 142 | if opt != nil { 143 | opt.AppendPayload(&payload) 144 | } 145 | jsonStr, err := makeRequest("getUserProfilePhotos", token, "", "", payload) 146 | if err != nil { 147 | return nil, err 148 | } 149 | var ups types.UserProfilePhotos 150 | err = json.Unmarshal(jsonStr, &ups) 151 | if err != nil { 152 | return nil, err 153 | } 154 | return &ups, nil 155 | } 156 | 157 | func sendMessage(token, chat_id, text string, opt *SendMessageOptional) (*types.Message, error) { 158 | payload := url.Values{} 159 | payload.Add("chat_id", chat_id) 160 | payload.Add("text", text) 161 | if opt != nil { 162 | opt.AppendPayload(&payload) 163 | } 164 | jsonStr, err := makeRequest("sendMessage", token, "", "", payload) 165 | if err != nil { 166 | return nil, err 167 | } 168 | return transformToMessage(jsonStr) 169 | } 170 | 171 | func forwardMessage(token, chat_id, from_chat_id, message_id string) (*types.Message, error) { 172 | payload := url.Values{} 173 | payload.Add("chat_id", chat_id) 174 | payload.Add("from_chat_id", from_chat_id) 175 | payload.Add("message_id", message_id) 176 | jsonStr, err := makeRequest("forwardMessage", token, "", "", payload) 177 | var msg types.Message 178 | err = json.Unmarshal(jsonStr, &msg) 179 | if err != nil { 180 | return nil, err 181 | } 182 | return &msg, nil 183 | } 184 | 185 | func sendPhoto(token, chat_id, photo string, opt *SendPhotoOptional) (*types.Message, error) { 186 | return sendFile(token, chat_id, "sendPhoto", "photo", photo, opt) 187 | } 188 | 189 | func sendAudio(token, chat_id, audio string, opt *SendAudioOptional) (*types.Message, error) { 190 | return sendFile(token, chat_id, "sendAudio", "audio", audio, opt) 191 | } 192 | 193 | func sendDocument(token, chat_id, document string, opt *SendDocumentOptional) (*types.Message, error) { 194 | return sendFile(token, chat_id, "sendDocument", "document", document, opt) 195 | } 196 | 197 | func sendSticker(token, chat_id, sticker string, opt *SendStickerOptional) (*types.Message, error) { 198 | return sendFile(token, chat_id, "sendSticker", "sticker", sticker, opt) 199 | } 200 | 201 | func sendVideo(token, chat_id, video string, opt *SendVideoOptional) (*types.Message, error) { 202 | return sendFile(token, chat_id, "sendVideo", "video", video, opt) 203 | } 204 | 205 | func sendVoice(token, chat_id, voice string, opt *SendVoiceOptional) (*types.Message, error) { 206 | return sendFile(token, chat_id, "sendVoice", "voice", voice, opt) 207 | } 208 | 209 | func sendLocation(token, chat_id, latitude, longitude string, opt *SendLocationOptional) (*types.Message, error) { 210 | payload := url.Values{} 211 | payload.Add("chat_id", chat_id) 212 | payload.Add("latitude", latitude) 213 | payload.Add("longitude", longitude) 214 | if opt != nil { 215 | opt.AppendPayload(&payload) 216 | } 217 | jsonStr, err := makeRequest("sendLocation", token, "", "", payload) 218 | if err != nil { 219 | return nil, err 220 | } 221 | return transformToMessage(jsonStr) 222 | } 223 | 224 | func sendChatAction(token, chat_id, action string) (string, error) { 225 | payload := url.Values{} 226 | payload.Add("chat_id", chat_id) 227 | payload.Add("action", action) 228 | jsonStr, err := makeRequest("sendChatAction", token, "", "", payload) 229 | if err != nil { 230 | return "", err 231 | } 232 | ret := string(jsonStr[:]) 233 | return ret, nil 234 | } 235 | 236 | func getFile(token, fileId string) (*types.File, error) { 237 | payload := url.Values{} 238 | payload.Add("file_id", fileId) 239 | jsonStr, err := makeRequest("getFile", token, "", "", payload) 240 | if err != nil { 241 | return nil, err 242 | } 243 | var file types.File 244 | err = json.Unmarshal(jsonStr, &file) 245 | if err != nil { 246 | return nil, err 247 | } 248 | return &file, nil 249 | } 250 | 251 | func downloadFile(token, filePath string) (*[]byte, error) { 252 | url := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", 253 | token, filePath) 254 | 255 | resp, err := http.Get(url) 256 | defer resp.Body.Close() 257 | if err != nil { 258 | return nil, err 259 | } 260 | if resp.StatusCode != 200 { 261 | return nil, errors.New(fmt.Sprintf("downloadFile error.statue code :%d", resp.StatusCode)) 262 | } 263 | ret, err := ioutil.ReadAll(resp.Body) 264 | if err != nil { 265 | return nil, err 266 | } 267 | return &ret, nil 268 | } 269 | 270 | func sendFile(token, chat_id, methodname, typename, file string, opt Optional) (*types.Message, error) { 271 | payload := url.Values{} 272 | filepath := "" 273 | formname := "" 274 | payload.Add("chat_id", chat_id) 275 | if _, err := os.Stat(file); err == nil { 276 | filepath = file 277 | formname = typename 278 | } 279 | if filepath == "" { // Use telegram fileid 280 | payload.Add(typename, file) 281 | } 282 | if !reflect.ValueOf(opt).IsNil() { // Check interface conatain nil 283 | opt.AppendPayload(&payload) 284 | } 285 | jsonStr, err := makeRequest(methodname, token, formname, filepath, payload) 286 | if err != nil { 287 | return nil, err 288 | } 289 | return transformToMessage(jsonStr) 290 | } 291 | 292 | func answerInlineQuery(token, inlineQueryId string, results []interface{}, opt *AnswerInlineQueryOptional) (bool, error) { 293 | payload := url.Values{} 294 | payload.Add("inline_query_id", inlineQueryId) 295 | resultJosn, err := getInlineQueryResultJsonString(results) 296 | if err != nil { 297 | return false, err 298 | } 299 | payload.Add("results", resultJosn) 300 | if !reflect.ValueOf(opt).IsNil() { // Check interface conatain nil 301 | opt.AppendPayload(&payload) 302 | } 303 | jsonStr, err := makeRequest("answerInlineQuery", token, "", "", payload) 304 | if err != nil { 305 | return false, err 306 | } 307 | var ret bool 308 | err = json.Unmarshal(jsonStr, &ret) 309 | if err != nil { 310 | return false, err 311 | } 312 | return ret, nil 313 | } 314 | 315 | func getInlineQueryResultJsonString(results []interface{}) (string, error) { 316 | ret := "" 317 | for _, r := range results { 318 | jsonStr, err := json.Marshal(r) 319 | if err != nil { 320 | return "", errors.New(fmt.Sprint("InlineQueryResult json encode error. %s. %#v", err, r)) 321 | } 322 | ret = ret + string(jsonStr) + "," 323 | } 324 | if len(ret) > 0 { 325 | ret = string(ret[0 : len(ret)-1]) 326 | } 327 | return "[" + ret + "]", nil 328 | } 329 | 330 | func transformToMessage(jsonStr []byte) (*types.Message, error) { 331 | var msg types.Message 332 | err := json.Unmarshal(jsonStr, &msg) 333 | if err != nil { 334 | return nil, err 335 | } 336 | return &msg, nil 337 | } 338 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package gotelebot_test 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | 7 | "github.com/eternnoir/gotelebot" 8 | ) 9 | 10 | func Example() { 11 | // Echo Bot example. 12 | bot := gotelebot.InitTeleBot("TOKEN") // Create gotelebot instance 13 | go bot.StartPolling(true, 0) // Start get new message whit goroutine and default timeout. 14 | newMsgChan := bot.Messages 15 | for { 16 | m := <-newMsgChan // Get new messaage, when new message arrive. 17 | if m.Text != "" { // Check message is text message. 18 | bot.SendMessage(int(m.Chat.Id), m.Text, nil) 19 | } 20 | } 21 | } 22 | 23 | func ExampleTeleBot_GetMe() { 24 | bot := gotelebot.InitTeleBot("TOKEN") // Create gotelebot instance 25 | me, err := bot.GetMe() // Get user object. 26 | if err != nil { 27 | fmt.Println(err) 28 | return 29 | } 30 | fmt.Println(me.FirstName) 31 | } 32 | 33 | func ExampleTeleBot_SendMessage() { 34 | bot := gotelebot.InitTeleBot("TOKEN") // Create gotelebot instance 35 | testMsg := "Test Msg" 36 | chatid := 11111111 37 | _, err := bot.SendMessage(chatid, testMsg, nil) 38 | if err != nil { 39 | fmt.Println("Bot send message error") 40 | } 41 | } 42 | 43 | func ExampleTeleBot_SendPhoto() { 44 | bot := gotelebot.InitTeleBot("TOKEN") // Create gotelebot instance 45 | chatid := 11111111 46 | filePath := "./test_data/go.png" 47 | _, err := bot.SendPhoto(chatid, filePath, nil) 48 | if err != nil { 49 | fmt.Println("Bot send Photo error") 50 | } 51 | } 52 | 53 | func ExampleTeleBot_DownloadFile() { 54 | token := "TOKEN" 55 | bot := gotelebot.InitTeleBot(token) 56 | fi := "BQADBQADnAMAAsYifgZph-iT9_z_rgI" 57 | file, err := bot.DownloadFile(fi) 58 | if err != nil { 59 | fmt.Println("Bot get File error") 60 | return 61 | } 62 | ferr := ioutil.WriteFile("/tmp/data", *file, 0644) 63 | if ferr != nil { 64 | fmt.Println("Write to File error") 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /optionals.go: -------------------------------------------------------------------------------- 1 | package gotelebot 2 | 3 | import ( 4 | "net/url" 5 | "strconv" 6 | 7 | "github.com/eternnoir/gotelebot/types" 8 | ) 9 | 10 | type Optional interface { 11 | AppendPayload(payload *url.Values) 12 | } 13 | 14 | // Optional parameters for SendMessage method 15 | type SendMessageOptional struct { 16 | // Send Markdown, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. 17 | ParseMode *string 18 | // Disables link previews for links in this message 19 | DisableWebPagePreview *bool 20 | ReplyToMessageId *int 21 | ReplyMarkup *types.ReplyMarkup 22 | } 23 | 24 | func (opt *SendMessageOptional) AppendPayload(payload *url.Values) { 25 | if opt.ParseMode != nil { 26 | payload.Add("parse_mode", *opt.ParseMode) 27 | } 28 | if opt.DisableWebPagePreview != nil { 29 | payload.Add("disable_web_page_preview", strconv.FormatBool(*opt.DisableWebPagePreview)) 30 | } 31 | if opt.ReplyToMessageId != nil { 32 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 33 | } 34 | if opt.ReplyMarkup != nil { 35 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 36 | payload.Add("reply_markup", jsonStr) 37 | } 38 | } 39 | 40 | // Optional parameters for SendPhoto method 41 | type SendPhotoOptional struct { 42 | // Photo caption 43 | Caption *string 44 | ReplyToMessageId *int 45 | ReplyMarkup *types.ReplyMarkup 46 | } 47 | 48 | func (opt *SendPhotoOptional) AppendPayload(payload *url.Values) { 49 | if opt.Caption != nil { 50 | payload.Add("caption", *opt.Caption) 51 | } 52 | if opt.ReplyToMessageId != nil { 53 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 54 | } 55 | if opt.ReplyMarkup != nil { 56 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 57 | payload.Add("reply_markup", jsonStr) 58 | } 59 | } 60 | 61 | // Optional parameters for SendAudio method 62 | type SendAudioOptional struct { 63 | // Duration of the audio in seconds 64 | Duration *int 65 | Performer *string 66 | Title *string 67 | ReplyToMessageId *int 68 | ReplyMarkup *types.ReplyMarkup 69 | } 70 | 71 | func (opt *SendAudioOptional) AppendPayload(payload *url.Values) { 72 | if opt.Duration != nil { 73 | payload.Add("duration", strconv.Itoa(*opt.Duration)) 74 | } 75 | if opt.Performer != nil { 76 | payload.Add("performer", *opt.Performer) 77 | } 78 | if opt.Title != nil { 79 | payload.Add("title", *opt.Title) 80 | } 81 | if opt.ReplyToMessageId != nil { 82 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 83 | } 84 | if opt.ReplyMarkup != nil { 85 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 86 | payload.Add("reply_markup", jsonStr) 87 | } 88 | } 89 | 90 | // Optional parameters for SendDocument method 91 | type SendDocumentOptional struct { 92 | ReplyToMessageId *int 93 | ReplyMarkup *types.ReplyMarkup 94 | } 95 | 96 | func (opt *SendDocumentOptional) AppendPayload(payload *url.Values) { 97 | if opt.ReplyToMessageId != nil { 98 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 99 | } 100 | if opt.ReplyMarkup != nil { 101 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 102 | payload.Add("reply_markup", jsonStr) 103 | } 104 | } 105 | 106 | // Optional parameters for SendSticker method 107 | type SendStickerOptional struct { 108 | ReplyToMessageId *int 109 | ReplyMarkup *types.ReplyMarkup 110 | } 111 | 112 | func (opt *SendStickerOptional) AppendPayload(payload *url.Values) { 113 | if opt.ReplyToMessageId != nil { 114 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 115 | } 116 | if opt.ReplyMarkup != nil { 117 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 118 | payload.Add("reply_markup", jsonStr) 119 | } 120 | } 121 | 122 | // Optional parameters for SendVideo method 123 | type SendVideoOptional struct { 124 | Duration *int 125 | Caption *string 126 | ReplyToMessageId *int 127 | ReplyMarkup *types.ReplyMarkup 128 | } 129 | 130 | func (opt *SendVideoOptional) AppendPayload(payload *url.Values) { 131 | if opt.Duration != nil { 132 | payload.Add("duration", strconv.Itoa(*opt.Duration)) 133 | } 134 | if opt.Caption != nil { 135 | payload.Add("caption", *opt.Caption) 136 | } 137 | if opt.ReplyToMessageId != nil { 138 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 139 | } 140 | if opt.ReplyMarkup != nil { 141 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 142 | payload.Add("reply_markup", jsonStr) 143 | } 144 | } 145 | 146 | // Optional parameters for SendVoice method 147 | type SendVoiceOptional struct { 148 | Duration *int 149 | ReplyToMessageId *int 150 | ReplyMarkup *types.ReplyMarkup 151 | } 152 | 153 | func (opt *SendVoiceOptional) AppendPayload(payload *url.Values) { 154 | if opt.Duration != nil { 155 | payload.Add("duration", strconv.Itoa(*opt.Duration)) 156 | } 157 | if opt.ReplyToMessageId != nil { 158 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 159 | } 160 | if opt.ReplyMarkup != nil { 161 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 162 | payload.Add("reply_markup", jsonStr) 163 | } 164 | } 165 | 166 | // Optional parameters for SendLocation method 167 | type SendLocationOptional struct { 168 | ReplyToMessageId *int 169 | ReplyMarkup *types.ReplyMarkup 170 | } 171 | 172 | func (opt *SendLocationOptional) AppendPayload(payload *url.Values) { 173 | if opt.ReplyToMessageId != nil { 174 | payload.Add("reply_to_message_id", strconv.Itoa(*opt.ReplyToMessageId)) 175 | } 176 | if opt.ReplyMarkup != nil { 177 | jsonStr, _ := (*opt.ReplyMarkup).ToJson() 178 | payload.Add("reply_markup", jsonStr) 179 | } 180 | } 181 | 182 | type GetUserProfilePhotosOptional struct { 183 | Offset *int 184 | Limit *int 185 | } 186 | 187 | func (opt *GetUserProfilePhotosOptional) AppendPayload(payload *url.Values) { 188 | if opt.Offset != nil { 189 | payload.Add("offset", strconv.Itoa(*opt.Offset)) 190 | } 191 | if opt.Limit != nil { 192 | payload.Add("limit", strconv.Itoa(*opt.Limit)) 193 | } 194 | } 195 | 196 | type AnswerInlineQueryOptional struct { 197 | CacheTime *int 198 | IsPersonal *bool 199 | NextOffset *string 200 | } 201 | 202 | func (opt *AnswerInlineQueryOptional) AppendPayload(payload *url.Values) { 203 | if opt.CacheTime != nil { 204 | payload.Add("cache_time", strconv.Itoa(*opt.CacheTime)) 205 | } 206 | if opt.IsPersonal != nil { 207 | if *opt.IsPersonal { 208 | payload.Add("is_personal", "True") 209 | } else { 210 | payload.Add("is_personal", "False") 211 | } 212 | } 213 | if opt.NextOffset != nil { 214 | payload.Add("next_offset", *opt.NextOffset) 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /telebot.go: -------------------------------------------------------------------------------- 1 | // Golang (Go) implementation for the Telegram Bot API. 2 | package gotelebot 3 | 4 | import ( 5 | "errors" 6 | "fmt" 7 | "strconv" 8 | 9 | "github.com/eternnoir/gotelebot/types" 10 | ) 11 | 12 | type TeleBot struct { 13 | token string 14 | Messages chan (*types.Message) 15 | InlineQuerys chan (*types.InlineQuery) 16 | ChosenInlineResults chan (*types.ChosenInlineResult) 17 | Offset float64 18 | stopPollingFlag bool 19 | } 20 | 21 | // InitTeleBot is the function to create gotelebot instance. 22 | func InitTeleBot(botToken string) *TeleBot { 23 | bot := new(TeleBot) 24 | bot.token = botToken 25 | bot.Messages = make(chan *types.Message) 26 | bot.InlineQuerys = make(chan *types.InlineQuery) 27 | bot.ChosenInlineResults = make(chan *types.ChosenInlineResult) 28 | return bot 29 | } 30 | 31 | // Returns basic information about the bot in form of a User object. 32 | func (bot *TeleBot) GetMe() (*types.User, error) { 33 | return getMe(bot.token) 34 | } 35 | 36 | // Use this method to receive incoming updates using long polling. An Array of Update objects is returned. 37 | func (bot *TeleBot) GetUpdates(offset, limit string, timeout int) ([]*types.Update, error) { 38 | return getUpdates(bot.token, offset, limit, strconv.Itoa(timeout)) 39 | } 40 | 41 | // Use this method to send text messages. On success, the sent Message type is returned. 42 | // 43 | // Use SendMessageOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 44 | func (bot *TeleBot) SendMessage(chatid int, text string, opt *SendMessageOptional) (*types.Message, error) { 45 | return sendMessage(bot.token, strconv.Itoa(chatid), text, opt) 46 | } 47 | 48 | // Use this method to forward messages of any kind. On success, the sent Message type is returned. 49 | func (bot *TeleBot) ForwardMessage(chatid, from_chat_id, message_id int) (*types.Message, error) { 50 | return forwardMessage(bot.token, strconv.Itoa(chatid), strconv.Itoa(from_chat_id), strconv.Itoa(message_id)) 51 | } 52 | 53 | // Use this method to send photos. On success, the sent Message is returned. 54 | // 55 | // Use SendPhotoOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 56 | func (bot *TeleBot) SendPhoto(chatid int, photo string, opt *SendPhotoOptional) (*types.Message, error) { 57 | return sendPhoto(bot.token, strconv.Itoa(chatid), photo, opt) 58 | } 59 | 60 | // Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. 61 | // On success, the sent Message is returned. 62 | // 63 | // Use SendAudioOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 64 | func (bot *TeleBot) SendAudio(chatid int, audio string, opt *SendAudioOptional) (*types.Message, error) { 65 | return sendAudio(bot.token, strconv.Itoa(chatid), audio, opt) 66 | } 67 | 68 | // Use this method to send general files. On success, the sent Message is returned. 69 | // 70 | // Use SendDocumentOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 71 | func (bot *TeleBot) SendDocument(chatid int, document string, opt *SendDocumentOptional) (*types.Message, error) { 72 | return sendDocument(bot.token, strconv.Itoa(chatid), document, opt) 73 | } 74 | 75 | // Use this method to send .webp stickers. On success, the sent Message is returned. 76 | // 77 | // Use SendStickerOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 78 | func (bot *TeleBot) SendSticker(chatid int, sticker string, opt *SendStickerOptional) (*types.Message, error) { 79 | return sendSticker(bot.token, strconv.Itoa(chatid), sticker, opt) 80 | } 81 | 82 | // Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). 83 | // 84 | // Use SendVideoOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 85 | func (bot *TeleBot) SendVideo(chatid int, video string, opt *SendVideoOptional) (*types.Message, error) { 86 | return sendVideo(bot.token, strconv.Itoa(chatid), video, opt) 87 | } 88 | 89 | // Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. 90 | // For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). 91 | // On success, the sent Message is returned. 92 | // 93 | // Use SendVideoOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 94 | func (bot *TeleBot) SendVoice(chatid int, voice string, opt *SendVoiceOptional) (*types.Message, error) { 95 | return sendVoice(bot.token, strconv.Itoa(chatid), voice, opt) 96 | } 97 | 98 | // Use this method to send point on the map. On success, the sent Message is returned. 99 | // 100 | // Use SendLocationOptional to setup optional parameters. If you don't want use any optional parameters, just asign nil to opt. 101 | func (bot *TeleBot) SendLocation(chatid int, latitude, longitude float64, opt *SendLocationOptional) (*types.Message, error) { 102 | return sendLocation(bot.token, strconv.Itoa(chatid), strconv.FormatFloat(latitude, 'f', 6, 64), strconv.FormatFloat(longitude, 'f', 6, 64), opt) 103 | } 104 | 105 | func (bot *TeleBot) AnswerInlineQuery(inlineQueryId string, results []interface{}, opt *AnswerInlineQueryOptional) (bool, error) { 106 | return answerInlineQuery(bot.token, inlineQueryId, results, opt) 107 | } 108 | 109 | // Use this method when you need to tell the user that something is happening on the bot's side. 110 | // 111 | // action can be : 112 | // "typing" for text messages, 113 | // "upload_photo" for photos, 114 | // "record_video" or upload_video for videos, 115 | // "record_audio" or upload_audio for audio files, 116 | // "upload_document" for general files, 117 | // "find_location" for location data. 118 | func (bot *TeleBot) SendChatAction(chatid int, action string) (string, error) { 119 | return sendChatAction(bot.token, strconv.Itoa(chatid), action) 120 | } 121 | 122 | // Use this method to get a list of profile pictures for a user. 123 | func (bot *TeleBot) GetUserProfilePhotos(userid int, opt *GetUserProfilePhotosOptional) (*types.UserProfilePhotos, error) { 124 | return getUserProfilePhotos(bot.token, strconv.Itoa(userid), opt) 125 | } 126 | 127 | // Use this method to get basic info about a file and prepare it for downloading. 128 | func (bot *TeleBot) GetFile(fileId string) (*types.File, error) { 129 | return getFile(bot.token, fileId) 130 | } 131 | 132 | // Download file by fileId. 133 | func (bot *TeleBot) DownloadFile(fileId string) (*[]byte, error) { 134 | file, err := bot.GetFile(fileId) 135 | if err != nil { 136 | return nil, err 137 | } 138 | if file.FilePath == "" { 139 | return nil, errors.New("File path not found") 140 | } 141 | filePath := file.FilePath 142 | return downloadFile(bot.token, filePath) 143 | } 144 | 145 | // Let gotelebot stop polling new messages. 146 | func (bot *TeleBot) StopPolling() { 147 | bot.stopPollingFlag = true 148 | } 149 | 150 | // Let gotelebot always try to get new messages. This function will put new message to gotelebot's Message channel. 151 | func (bot *TeleBot) StartPolling(nonStop bool, timeout int) error { 152 | bot.stopPollingFlag = false 153 | for { 154 | if bot.stopPollingFlag == true { 155 | return nil 156 | } 157 | newUpdates, err := bot.GetUpdates(strconv.Itoa(int(bot.Offset)), "", timeout) 158 | if err != nil { 159 | if !nonStop { 160 | return err 161 | } else { 162 | fmt.Println(err) 163 | } 164 | } 165 | bot.processNewUpdate(newUpdates) 166 | } 167 | } 168 | 169 | func (bot *TeleBot) processNewUpdate(updates []*types.Update) { 170 | for _, update := range updates { 171 | if update.UpdateId >= bot.Offset { 172 | bot.Offset = update.UpdateId + 1 173 | } 174 | switch { 175 | case update.Message != nil: 176 | bot.Messages <- update.Message 177 | case update.InlineQuery != nil: 178 | bot.InlineQuerys <- update.InlineQuery 179 | case update.ChosenInlineResult != nil: 180 | bot.ChosenInlineResults <- update.ChosenInlineResult 181 | } 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /telebot_test.go: -------------------------------------------------------------------------------- 1 | package gotelebot 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strconv" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | func TestGetMe(t *testing.T) { 13 | assert := assert.New(t) 14 | token := os.Getenv("TOKEN") 15 | bot := InitTeleBot(token) 16 | me, err := bot.GetMe() 17 | if err != nil { 18 | assert.Fail("Bot getMe error") 19 | } 20 | assert.NotEmpty(me.Id) 21 | } 22 | 23 | func TestSendMessage(t *testing.T) { 24 | assert := assert.New(t) 25 | token := os.Getenv("TOKEN") 26 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 27 | bot := InitTeleBot(token) 28 | testMsg := "Test Msg" 29 | msg, err := bot.SendMessage(chatid, testMsg, nil) 30 | if err != nil { 31 | assert.Fail("Bot send message error") 32 | } 33 | assert.EqualValues(testMsg, msg.Text) 34 | } 35 | 36 | func SendMsgAndGetId() int { 37 | token := os.Getenv("TOKEN") 38 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 39 | bot := InitTeleBot(token) 40 | testMsg := "Test Msg" 41 | msg, _ := bot.SendMessage(chatid, testMsg, nil) 42 | return int(msg.Message_Id) 43 | } 44 | 45 | func TestSendMessageWithOpt(t *testing.T) { 46 | assert := assert.New(t) 47 | token := os.Getenv("TOKEN") 48 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 49 | bot := InitTeleBot(token) 50 | testMsg := "Test Msg" 51 | dis := true 52 | rid := SendMsgAndGetId() 53 | opt := &SendMessageOptional{DisableWebPagePreview: &dis, ReplyToMessageId: &rid} 54 | msg, err := bot.SendMessage(chatid, testMsg, opt) 55 | if err != nil { 56 | assert.Fail("Bot send message error") 57 | } 58 | assert.EqualValues(testMsg, msg.Text) 59 | } 60 | 61 | func TestForwardMessage(t *testing.T) { 62 | assert := assert.New(t) 63 | token := os.Getenv("TOKEN") 64 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 65 | bot := InitTeleBot(token) 66 | msg, err := bot.ForwardMessage(chatid, chatid, SendMsgAndGetId()) 67 | if err != nil { 68 | assert.Fail("Bot forwardMessage error") 69 | } 70 | assert.NotEmpty(msg.ForwardFrom) 71 | 72 | } 73 | 74 | func TestSendPhoto(t *testing.T) { 75 | assert := assert.New(t) 76 | token := os.Getenv("TOKEN") 77 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 78 | bot := InitTeleBot(token) 79 | filePath := "./test_data/go.png" 80 | msg, err := bot.SendPhoto(chatid, filePath, nil) 81 | if err != nil { 82 | fmt.Println(err) 83 | assert.Fail("Bot sendPhoto error") 84 | } 85 | assert.NotEmpty(msg.Photo) 86 | } 87 | 88 | func TestSendPhotoWithOpt(t *testing.T) { 89 | assert := assert.New(t) 90 | token := os.Getenv("TOKEN") 91 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 92 | bot := InitTeleBot(token) 93 | filePath := "./test_data/go.png" 94 | rsi := SendMsgAndGetId() 95 | opt := &SendPhotoOptional{ReplyToMessageId: &rsi} 96 | msg, err := bot.SendPhoto(chatid, filePath, opt) 97 | if err != nil { 98 | fmt.Println(err) 99 | assert.Fail("Bot sendPhoto error") 100 | } 101 | assert.NotEmpty(msg.Photo) 102 | } 103 | 104 | func TestSendAudio(t *testing.T) { 105 | assert := assert.New(t) 106 | token := os.Getenv("TOKEN") 107 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 108 | bot := InitTeleBot(token) 109 | filePath := "./test_data/record.mp3" 110 | msg, err := bot.SendAudio(chatid, filePath, nil) 111 | if err != nil { 112 | fmt.Println(err) 113 | assert.Fail("Bot sendAudio error") 114 | } 115 | assert.NotEmpty(msg) 116 | } 117 | 118 | func TestSendAudioWithOpt(t *testing.T) { 119 | assert := assert.New(t) 120 | token := os.Getenv("TOKEN") 121 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 122 | bot := InitTeleBot(token) 123 | performer := "tele" 124 | title := "gram" 125 | rsi := SendMsgAndGetId() 126 | opt := &SendAudioOptional{Performer: &performer, Title: &title, ReplyToMessageId: &rsi} 127 | filePath := "./test_data/record.mp3" 128 | msg, err := bot.SendAudio(chatid, filePath, opt) 129 | if err != nil { 130 | fmt.Println(err) 131 | assert.Fail("Bot sendAudio error") 132 | } 133 | assert.Equal(msg.Audio.Title, title) 134 | } 135 | 136 | func TestSendDocument(t *testing.T) { 137 | assert := assert.New(t) 138 | token := os.Getenv("TOKEN") 139 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 140 | bot := InitTeleBot(token) 141 | filePath := "./test_data/go.png" 142 | msg, err := bot.SendDocument(chatid, filePath, nil) 143 | if err != nil { 144 | fmt.Println(err) 145 | assert.Fail("Bot sendDocument error") 146 | } 147 | assert.NotEmpty(msg.Document.FileId) 148 | } 149 | 150 | func TestSendSticker(t *testing.T) { 151 | assert := assert.New(t) 152 | token := os.Getenv("TOKEN") 153 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 154 | bot := InitTeleBot(token) 155 | filePath := "./test_data/go.webp" 156 | msg, err := bot.SendSticker(chatid, filePath, nil) 157 | if err != nil { 158 | fmt.Println(err) 159 | assert.Fail("Bot sendStick error") 160 | } 161 | assert.NotEmpty(msg.Sticker.FileId) 162 | } 163 | 164 | func TestSendVideo(t *testing.T) { 165 | assert := assert.New(t) 166 | token := os.Getenv("TOKEN") 167 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 168 | bot := InitTeleBot(token) 169 | filePath := "./test_data/test_video.mp4" 170 | msg, err := bot.SendVideo(chatid, filePath, nil) 171 | if err != nil { 172 | fmt.Println(err) 173 | assert.Fail("Bot sendVideo error") 174 | } 175 | assert.NotEmpty(msg.Video.FileId) 176 | } 177 | 178 | func TestSendVoice(t *testing.T) { 179 | assert := assert.New(t) 180 | token := os.Getenv("TOKEN") 181 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 182 | bot := InitTeleBot(token) 183 | filePath := "./test_data/record.ogg" 184 | msg, err := bot.SendVoice(chatid, filePath, nil) 185 | if err != nil { 186 | fmt.Println(err) 187 | assert.Fail("Bot sendVOice error") 188 | } 189 | assert.NotEmpty(msg.Voice.FileId) 190 | } 191 | 192 | func TestSendLocation(t *testing.T) { 193 | assert := assert.New(t) 194 | token := os.Getenv("TOKEN") 195 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 196 | bot := InitTeleBot(token) 197 | lat := 26.3875591 198 | lon := -161.2901042 199 | msg, err := bot.SendLocation(chatid, lat, lon, nil) 200 | if err != nil { 201 | assert.Fail("Bot send Location error") 202 | } 203 | assert.NotEmpty(msg.Location.Latitude) 204 | } 205 | 206 | func TestSendChatAction(t *testing.T) { 207 | assert := assert.New(t) 208 | token := os.Getenv("TOKEN") 209 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 210 | bot := InitTeleBot(token) 211 | msg, err := bot.SendChatAction(chatid, "typing") 212 | if err != nil { 213 | assert.Fail("Bot send ChatAction error") 214 | } 215 | fmt.Println(msg) 216 | } 217 | 218 | func TestGetUserProfilePhotos(t *testing.T) { 219 | assert := assert.New(t) 220 | token := os.Getenv("TOKEN") 221 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 222 | bot := InitTeleBot(token) 223 | photos, err := bot.GetUserProfilePhotos(chatid, nil) 224 | if err != nil { 225 | fmt.Println(err) 226 | assert.Fail("Bot get User Profile phtots fail.") 227 | } 228 | assert.True(len(*photos.Photos) > 0) 229 | assert.True(photos.TotalCount > 0) 230 | } 231 | 232 | func TestChatType(t *testing.T) { 233 | assert := assert.New(t) 234 | token := os.Getenv("TOKEN") 235 | chatid, _ := strconv.Atoi(os.Getenv("CHAT")) 236 | bot := InitTeleBot(token) 237 | msg, err := bot.SendMessage(chatid, "Test", nil) 238 | if err != nil { 239 | assert.Fail("Bot send message error") 240 | } 241 | assert.EqualValues(int(msg.Chat.Id), chatid) 242 | assert.EqualValues(msg.Chat.Type, "private") 243 | } 244 | -------------------------------------------------------------------------------- /test_data/go.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/go.jpg -------------------------------------------------------------------------------- /test_data/go.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/go.png -------------------------------------------------------------------------------- /test_data/go.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/go.webp -------------------------------------------------------------------------------- /test_data/record.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/record.mp3 -------------------------------------------------------------------------------- /test_data/record.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/record.ogg -------------------------------------------------------------------------------- /test_data/record.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/record.wav -------------------------------------------------------------------------------- /test_data/test_video.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eternnoir/gotelebot/82299e7925d57a3c220a750ae1bcca3ad26868ac/test_data/test_video.mp4 -------------------------------------------------------------------------------- /types/inline_types.go: -------------------------------------------------------------------------------- 1 | // This package define all inline type used in Telegram Bot API. 2 | // 3 | // More information : https://core.telegram.org/bots/api#inline-mode 4 | package types 5 | 6 | import ( 7 | _ "encoding/json" 8 | ) 9 | 10 | type InlineQuery struct { 11 | Id string `json:"id"` 12 | From *User `json:"from"` 13 | Query string `json:"query"` 14 | offset string `json:"offset"` 15 | } 16 | 17 | type ChosenInlineResult struct { 18 | ResultId string `json:"result_id"` 19 | From *User `json:"from"` 20 | Query string `json:"query"` 21 | } 22 | 23 | type InlineQueryResult struct { 24 | Type string `json:"type"` 25 | Id string `json:"id"` 26 | ParseMode string `json:"parse_mode,omitempty"` 27 | DisableWebPagePreview bool `json:"description,omitempty"` 28 | } 29 | 30 | type InlineQueryResultArticle struct { 31 | InlineQueryResult 32 | Title string `json:"title"` 33 | MessageText string `json:"message_text"` 34 | Url string `json:"url,omitempty"` 35 | HideUrl bool `json:"hide_url,omitempty"` 36 | Description string `json:"description,omitempty"` 37 | ThumbUrl string `json:"thumb_url,omitempty"` 38 | ThumbWidth float64 `json:"thumb_width,omitempty"` 39 | ThumbHeight float64 `json:"thumb_height,omitempty"` 40 | } 41 | 42 | func NewInlineQueryResultArticl() *InlineQueryResultArticle { 43 | ret := new(InlineQueryResultArticle) 44 | ret.Type = "article" 45 | return ret 46 | } 47 | 48 | type InlineQueryResultPhoto struct { 49 | InlineQueryResult 50 | PhotoUrl string `json:"photo_url"` 51 | PhotoWidth float64 `json:"photo_width,omitempty"` 52 | PhotoHeight float64 `json:"photo_height,omitempty"` 53 | ThumbUrl string `json:"thumb_url"` 54 | Title string `json:"title,omitempty"` 55 | Description string `json:"description,omitempty"` 56 | Caption string `json:"caption,omitempty"` 57 | MessageText string `json:"message_text,omitempty"` 58 | } 59 | 60 | func NewInlineQueryResultPhoto() *InlineQueryResultPhoto { 61 | ret := new(InlineQueryResultPhoto) 62 | ret.Type = "photo" 63 | return ret 64 | } 65 | 66 | type InlineQueryResultGif struct { 67 | InlineQueryResult 68 | GifUrl string `json:"gif_url"` 69 | GifWidth float64 `json:"gif_width,omitempty"` 70 | GifHeight float64 `json:"gif_height,omitempty"` 71 | ThumbUrl string `json:"thumb_url"` 72 | Title string `json:"title,omitempty"` 73 | Caption string `json:"caption,omitempty"` 74 | MessageText string `json:"message_text,omitempty"` 75 | } 76 | 77 | func NewInlineQueryResultGif() *InlineQueryResultGif { 78 | ret := new(InlineQueryResultGif) 79 | ret.Type = "gif" 80 | return ret 81 | } 82 | 83 | type InlineQueryResultMpeg4Gif struct { 84 | InlineQueryResult 85 | Mpeg4Url string `json:"mpeg4_url"` 86 | Mpeg4Width float64 `json:"mpeg4_width,omitempty"` 87 | Mpeg4Height float64 `json:"mpeg4_height,omitempty"` 88 | ThumbUrl string `json:"thumb_url"` 89 | Title string `json:"title,omitempty"` 90 | Caption string `json:"caption,omitempty"` 91 | MessageText string `json:"message_text,omitempty"` 92 | } 93 | 94 | func NewInlineQueryResultMpeg4Gif() *InlineQueryResultMpeg4Gif { 95 | ret := new(InlineQueryResultMpeg4Gif) 96 | ret.Type = "mpeg4_gif" 97 | return ret 98 | } 99 | 100 | type InlineQueryResultVideo struct { 101 | InlineQueryResult 102 | VideoUrl string `json:"video_url"` 103 | MimeType string `json:"mime_type"` 104 | MessageText string `json:"message_text"` 105 | VideoWidth float64 `json:"video_width,omitempty"` 106 | VideoHeight float64 `json:"video_height,omitempty"` 107 | VideoDuration float64 `json:"video_duration,omitempty"` 108 | Title string `json:"title"` 109 | ThumbUrl string `json:"thumb_url"` 110 | Description string `json:"description,omitempty"` 111 | } 112 | 113 | func NewInlineQueryResultVideo() *InlineQueryResultVideo { 114 | ret := new(InlineQueryResultVideo) 115 | ret.Type = "video" 116 | return ret 117 | } 118 | -------------------------------------------------------------------------------- /types/types.go: -------------------------------------------------------------------------------- 1 | // This package define all type used in Telegram Bot API. 2 | // 3 | // More information : https://core.telegram.org/bots/api#available-types 4 | package types 5 | 6 | import ( 7 | "encoding/json" 8 | ) 9 | 10 | // Update object. 11 | // Optional means this variable could be nil or empty. 12 | type Update struct { 13 | // The update‘s unique identifier. 14 | UpdateId float64 `json:"update_id"` 15 | // Optional. New incoming message of any kind 16 | Message *Message `json:"message,omitempty"` 17 | // Optional. New incoming inline query 18 | InlineQuery *InlineQuery `json:"inline_query,omitempty"` 19 | // Optional. The result of a inline query that was chosen by a user and sent to their chat partner 20 | ChosenInlineResult *ChosenInlineResult `json:"chosen_inline_result,omitempty"` 21 | } 22 | 23 | // User object. 24 | // Optional means this variable could be nil or empty. 25 | type User struct { 26 | // Unique identifier for this user or bot 27 | Id float64 `json:"id"` 28 | // User‘s or bot’s first name 29 | FirstName string `json:"first_name"` 30 | // Optional. User‘s or bot’s last name 31 | LastName string `json:"last_name"` 32 | // Optional. User‘s or bot’s username 33 | Username string `json:"username"` 34 | } 35 | 36 | // GroupChat object. 37 | // Optional means this variable could be nil or empty. 38 | type GroupChat struct { 39 | // Unique identifier for this group chat 40 | Id float64 `json:"id"` 41 | // Group name 42 | Title string `json:"title"` 43 | } 44 | 45 | // Chat object. Representatives GroupChat and User Chat. 46 | // Optional means this variable could be nil or empty. 47 | type Chat struct { 48 | Id float64 `json:"id"` 49 | Type string `json:"type"` 50 | FirstName string `json:"first_name"` 51 | LastName string `json:"last_name"` 52 | Username string `json:"username"` 53 | Title string `json:"title"` 54 | } 55 | 56 | // Message object. 57 | // Optional means this variable could be nil or empty. 58 | type Message struct { 59 | // Unique message identifier 60 | Message_Id float64 `josn:"message_id"` 61 | // Sender 62 | From *User `json:"from"` 63 | // Date the message was sent. 64 | Date float64 `json:"date"` 65 | // Conversation the message belongs to. 66 | Chat *Chat `json:"chat"` 67 | // Optional. For forwarded messages, sender of the original message 68 | ForwardFrom *User `json:"forward_from,omitempty"` 69 | // Optional. For forwarded messages, date the original message was sent. 70 | ForwardDate float64 `json:"forward_date,omitempty"` 71 | // Optional. For text messages 72 | Text string `json:"text,omitempty"` 73 | // Optional. Message is an audio file 74 | Audio *Audio `json:"audio,omitempty"` 75 | // Optional. Message is a general file 76 | Document *Document `json:"document,omitempty"` 77 | // Optional. Message is a photo 78 | Photo *[]*PhotoSize `json:"photo,omitempty"` 79 | // Optional. Message is a sticker 80 | Sticker *Sticker `json:"sticker,omitempty"` 81 | // Optional. Message is a video 82 | Video *Video `json:"video,omitempty"` 83 | // Optional. Message is a voice message 84 | Voice *Voice `json:"voice,omitempty"` 85 | // Optional. Caption for the photo or video 86 | Caption string `json:"caption,omitempty"` 87 | // Optional. Message is a shared contact 88 | Contact *Contact `json:"contact,omitempty"` 89 | // Optional. Message is a shared location 90 | Location *Location `json:"location,omitempty"` 91 | // Optional. A new member was added to the group 92 | NewChatParticipant *User `json:"new_chat_participant,omitempty"` 93 | // Optional. A member was removed from the group 94 | LeftChatParticipant *User `json:"left_chat_participant,omitempty"` 95 | // Optional. A group title was changed to this value 96 | NewChatTitle string `json:"new_chat_title,omitempty"` 97 | // Optional. A group photo was change to this value 98 | NewChatPhoto *[]*PhotoSize `json:"new_chat_photo,omitempty"` 99 | // Optional. Informs that the group photo was deleted 100 | DeleteChatPhoto bool `json:"delete_chat_photo,omitempty"` 101 | // Optional. Informs that the group has been created 102 | GroupChatCreated bool `json:"group_chat_created,omitempty"` 103 | } 104 | 105 | // This object represents one size of a photo or a file / sticker thumbnail. 106 | // Optional means this variable could be nil or empty. 107 | type PhotoSize struct { 108 | // Unique identifier for this file 109 | FileId string `json:"file_id"` 110 | // Photo width 111 | Width float64 `json:"width"` 112 | // Photo height 113 | Height float64 `json:"height"` 114 | // Optional. File size 115 | FileSize float64 `json:"file_size"` 116 | } 117 | 118 | // This object represents an audio file to be treated as music by the Telegram clients. 119 | // Optional means this variable could be nil or empty. 120 | type Audio struct { 121 | // Unique identifier for this file 122 | FileId string `json:"file_id"` 123 | // Duration of the audio in seconds as defined by sender 124 | Duration float64 `json:"duration"` 125 | // Optional. Performer of the audio as defined by sender or by audio tags 126 | Performer string `json:"performer"` 127 | // Optional. Title of the audio as defined by sender or by audio tags 128 | Title string `json:"title"` 129 | // Optional. MIME type of the file as defined by sender 130 | MimeType string `json:"mime_type"` 131 | // Optional. File size 132 | FileSize float64 `json:"file_size"` 133 | } 134 | 135 | // This object represents a general file (as opposed to photos, voice messages and audio files). 136 | // Optional means this variable could be nil or empty. 137 | type Document struct { 138 | // Unique file identifier 139 | FileId string `json:"file_id"` 140 | // Optional. Document thumbnail as defined by sender 141 | Thumb PhotoSize `json:"thumb"` 142 | // Optional. Original filename as defined by sender 143 | FileName string `json:"file_name"` 144 | // Optional. MIME type of the file as defined by sender 145 | MimeType string `json:"mime_type"` 146 | // Optional. File size 147 | FileSize float64 `josn:"file_size"` 148 | } 149 | 150 | // This object represents a sticker. 151 | // Optional means this variable could be nil or empty. 152 | type Sticker struct { 153 | // Unique identifier for this file 154 | FileId string `json:"file_id"` 155 | // Sticker width 156 | width float64 `json:"width"` 157 | // Sticker height 158 | height float64 `json:"height"` 159 | // Optional. Sticker thumbnail in .webp or .jpg format 160 | Thumb PhotoSize `json:"thumb"` 161 | // Optional. File size 162 | FileSize float64 `josn:"file_size"` 163 | } 164 | 165 | // This object represents a video file. 166 | type Video struct { 167 | FileId string `json:"file_id"` 168 | width float64 `json:"width"` 169 | height float64 `json:"height"` 170 | Thumb PhotoSize `json:"thumb"` 171 | Duration float64 `json:"duration"` 172 | MimeType string `json:"mime_type"` 173 | FileSize float64 `josn:"file_size"` 174 | } 175 | 176 | //This object represents a voice note. 177 | type Voice struct { 178 | FileId string `json:"file_id"` 179 | Duration float64 `json:"duration"` 180 | MimeType string `json:"mime_type"` 181 | FileSize float64 `json:"file_size"` 182 | } 183 | 184 | // This object represents a phone contact. 185 | type Contact struct { 186 | PhoneNumber string `json:"phone_number"` 187 | FirstName string `json:"first_name"` 188 | LastName string `json:"last_name"` 189 | Username string `json:"username"` 190 | } 191 | 192 | // This object represents a point on the map. 193 | type Location struct { 194 | Longitude float64 `json:"longitude"` 195 | Latitude float64 `json:"latitude"` 196 | } 197 | 198 | type ReplyMarkup interface { 199 | ToJson() (string, error) 200 | } 201 | 202 | type ReplyKeyboardMarkup struct { 203 | Keyboard [][]string `json:"keyboard"` 204 | ResizeKeyboard bool `json:"resize_keyboard,omitempty"` 205 | OneTimeKeyboard bool `json:"one_time_keyboard,omitempty"` 206 | Selective bool `json:"selective,omitempty"` 207 | } 208 | 209 | func (rkm *ReplyKeyboardMarkup) ToJson() (string, error) { 210 | b, err := json.Marshal(rkm) 211 | if err != nil { 212 | return "", err 213 | } 214 | return string(b), nil 215 | } 216 | 217 | type ReplyKeyboardHide struct { 218 | HideKeyboard bool `json:"hide_keyboard"` 219 | Selective bool `json:"selective"` 220 | } 221 | 222 | func (rkm *ReplyKeyboardHide) ToJson() (string, error) { 223 | rkm.HideKeyboard = true 224 | b, err := json.Marshal(rkm) 225 | if err != nil { 226 | return "", err 227 | } 228 | return string(b), nil 229 | } 230 | 231 | type ForceReply struct { 232 | ForceReply bool `json:"force_reply"` 233 | Selective bool `json:"selective"` 234 | } 235 | 236 | func (rkm *ForceReply) ToJson() (string, error) { 237 | rkm.ForceReply = true 238 | b, err := json.Marshal(rkm) 239 | if err != nil { 240 | return "", err 241 | } 242 | return string(b), nil 243 | } 244 | 245 | type File struct { 246 | FileId string `json:"file_id"` 247 | FileSize float64 `json:"file_size"` 248 | FilePath string `json:"file_path"` 249 | } 250 | 251 | type UserProfilePhotos struct { 252 | TotalCount float64 `json:"total_count"` 253 | Photos *[]*[]*PhotoSize `json:"photos"` 254 | } 255 | -------------------------------------------------------------------------------- /types/types_test.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestReplyKeyboardMarkup(t *testing.T) { 10 | assert := assert.New(t) 11 | row1 := []string{"1", "2", "3"} 12 | row2 := []string{"4", "5", "6"} 13 | rkm := ReplyKeyboardMarkup{} 14 | rkm.Keyboard = append(rkm.Keyboard, row1) 15 | rkm.Keyboard = append(rkm.Keyboard, row2) 16 | _, err := rkm.ToJson() 17 | if err != nil { 18 | assert.Fail(err.Error()) 19 | } 20 | } 21 | --------------------------------------------------------------------------------