├── .gitignore ├── LICENSE-BEERWARE ├── Cargo.toml ├── deploy.sh ├── examples ├── simple.rs └── complete.rs ├── .travis.yml ├── LICENSE-MIT ├── src ├── test.rs ├── send.rs └── lib.rs ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | secrets.sh 4 | files 5 | -------------------------------------------------------------------------------- /LICENSE-BEERWARE: -------------------------------------------------------------------------------- 1 | "THE BEER-WARE LICENSE" (Revision 42): 2 | wrote this project. 3 | As long as you retain this notice you can do whatever you want with this stuff. 4 | If you meet us some day, and you think this stuff is worth it, 5 | you can buy us a beer in return. -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "awesome-bot" 3 | version = "0.2.0" 4 | authors = ["Rock Neurotiko "] 5 | license = "MIT OR Apache-2.0 OR Beerware" 6 | 7 | description = "An awesome framework to build Telegram bots up to telegram-bot library." 8 | readme = "README.md" 9 | documentation = "http://web.neurotiko.com/awesome-bot/awesome_bot" 10 | 11 | repository = "https://github.com/rockneurotiko/awesome-bot" 12 | keywords = ["telegram", "bot", "api", "library", "framework"] 13 | 14 | 15 | [dependencies] 16 | telegram-bot = "0.4.2" 17 | rustc-serialize = "0.3.*" 18 | regex = "0.1.*" 19 | scoped_threadpool = "0.1.*" 20 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Author: Steve Klabnik 3 | # github.com/steveklabnik/automatically_update_github_pages_with_travis_example 4 | 5 | set -o errexit -o nounset 6 | 7 | rev=$(git rev-parse --short HEAD) 8 | 9 | cargo doc 10 | cd target/doc/ 11 | 12 | git init 13 | git config user.name "Rock Neurotiko" 14 | git config user.email "miguelglafuente@gmail.com" 15 | 16 | git remote add upstream "https://${GH_TOKEN}@github.com/rockneurotiko/awesome-bot.git" 17 | git fetch upstream 18 | git reset upstream/gh-pages 19 | 20 | touch . 21 | 22 | git add -A . 23 | git commit -m "rebuild pages at ${rev}" 24 | git push -q upstream HEAD:gh-pages 25 | -------------------------------------------------------------------------------- /examples/simple.rs: -------------------------------------------------------------------------------- 1 | extern crate awesome_bot; 2 | 3 | use awesome_bot::*; 4 | 5 | fn echohandler(bot: &AwesomeBot, msg: &Message, _: String, args: Vec) { 6 | // We can access safely because the pattern match have that argument mandatory 7 | let toecho = &args[1]; 8 | let phrase = format!("Echoed: {}", toecho); 9 | // Send the text in a beauty way :) 10 | let sent = bot.answer(msg).text(&phrase).end(); 11 | println!("{:?}", sent); 12 | } 13 | 14 | fn main() { 15 | // Create the Awesome Bot (You need TELEGRAM_BOT_TOKEN environment variable with the token) 16 | let mut bot = AwesomeBot::from_env("TELEGRAM_BOT_TOKEN"); 17 | // Add a command, this will add the route to that function. 18 | bot.command("echo (.+)", echohandler); 19 | 20 | // Start the bot with getUpdates 21 | let res = bot.simple_start(); 22 | if let Err(e) = res { 23 | println!("An error occurred: {}", e); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - nightly 4 | - beta 5 | - stable 6 | env: 7 | global: 8 | secure: TnVf8DHhB24blKZoHuY1bm79aD47lqKG0qn0xHMlC/+mwhilz/0ZUbr9flnwnuVsDRJJjWkinjZS9/LObtwHJCGiirb7L5167wspEiJYx9PCrIbpjdS+nGy+VTL89xIzD4Ga7cOcW/bTTOAIUpufZpC0+t1arOmmkFPgNBg7u/qSukiqykYii2W0a25zxegzqQnbht7zv7/0515AWIM3fg9L15f8C1aqVNHTv49Y8vC+uTYAAffr1iTuc4em48ye+8xrArJKStEwlxNGBRMlQfIDp2qyPwM2MZfuygULyYs/A88yRz0cDxW5VabxCQBXxRGvQWDXeHqzA87dQ5afy88aiVgmyHZKul/WfDZKcRMbwGxX0JkMT98FnqK/fkbhh2U4p0iTUhE1DTJT1Sdz0cNcqmK+mAgD+TzYriVlrJ3lMbO+izrDQy85E3gXh94PCI2VG03pRyswjSoO936fMKzKQDQriX+/dHKtUsHpYSROMzRfGkSvbCiaugQyUTY+3iXsCJid3scxMyBB7Y9CKwkLMEkHX9PH9xTpYUHHDCJBHP4AkqcwRu7MLPFTHoAoA6jrEgnLIaWCuBFcG85TFsy9EGA5lBb+dZJKwWQHdUEuf5wKsf0+4AS9QGFgvMZdlU3JBzMFneiyvU9Lc5ImNICakx4ltCV6XMxcNSIZAQ8= 9 | after_success: 10 | - | 11 | test ${TRAVIS_PULL_REQUEST} == "false" && \ 12 | test ${TRAVIS_BRANCH} == "master" && \ 13 | test "${TRAVIS_BUILD_NUMBER}.3" == "${TRAVIS_JOB_NUMBER}" && \ 14 | bash deploy.sh 15 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/test.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod test { 3 | use regex::Regex; 4 | use AwesomeBot; 5 | 6 | struct Defs { 7 | cmd: &'static str, 8 | res: String, 9 | usern: String, 10 | } 11 | 12 | impl Default for Defs { 13 | fn default() -> Defs { 14 | Defs { 15 | cmd: "test", 16 | res: String::from("^/test(?:@usernamebot)?$"), 17 | usern: String::from("usernamebot"), 18 | } 19 | } 20 | } 21 | 22 | macro_rules! create_test_string { 23 | ($name:ident, $cmd:expr) => { 24 | #[test] 25 | fn $name() { 26 | let defs = Defs { 27 | cmd: $cmd, 28 | ..Default::default() 29 | }; 30 | assert_eq!(AwesomeBot::modify_command(defs.cmd, &defs.usern), defs.res); 31 | } 32 | }; 33 | } 34 | create_test_string!(mt_simple_right, "test"); 35 | create_test_string!(mt_end_right, "test$"); 36 | create_test_string!(mt_slash_right, "/test"); 37 | create_test_string!(mt_slashend_right, "/test$"); 38 | create_test_string!(mt_startslash_right, "^/test"); 39 | create_test_string!(mt_startslashend_right, "^/test$"); 40 | 41 | #[test] 42 | fn test_complex_command() { 43 | assert_eq!( 44 | AwesomeBot::modify_command("echo (.+)", "rock"), 45 | String::from("^/echo(?:@rock)? (.+)$") 46 | ); 47 | } 48 | 49 | fn create_regex(cmd: &'static str) -> Regex { 50 | let defs = Defs { 51 | cmd: cmd, 52 | ..Default::default() 53 | }; 54 | let cmd = AwesomeBot::modify_command(defs.cmd, &defs.usern); 55 | Regex::new(&*cmd).unwrap() 56 | } 57 | 58 | #[test] 59 | fn rcmd_simple_right() { 60 | let r = create_regex("test"); 61 | assert!(r.is_match("/test")); 62 | } 63 | 64 | #[test] 65 | fn rcmd_withusername_right() { 66 | let r = create_regex("test"); 67 | assert!(r.is_match("/test@usernamebot")); 68 | } 69 | 70 | #[test] 71 | fn rcmd_capturessimple_right() { 72 | let r = create_regex("test"); 73 | let cap = r.captures("/test").unwrap(); 74 | assert_eq!(cap.len(), 1); 75 | assert_eq!(cap.at(0), Some("/test")); 76 | } 77 | 78 | #[test] 79 | fn rcmd_capturesusername_right() { 80 | let r = create_regex("test"); 81 | let cap = r.captures("/test@usernamebot").unwrap(); 82 | assert_eq!(cap.len(), 1); 83 | assert_eq!(cap.at(0), Some("/test@usernamebot")); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Awesome Bot 2 | =========== 3 | 4 | [![Travis](https://travis-ci.org/rockneurotiko/awesome-bot.svg?branch=master)](https://travis-ci.org/rockneurotiko/awesome-bot) 5 | [![Crates.io](https://img.shields.io/crates/v/awesome-bot.svg)](https://crates.io/crates/awesome-bot) 6 | 7 | [**Documentation**](http://web.neurotiko.com/awesome-bot/awesome_bot/) 8 | 9 | A framework to build your own [Telegram](https://telegram.org/) bots easily. More information [here](https://core.telegram.org/bots). Official API [here](https://core.telegram.org/bots/api). 10 | 11 | This framework is based on [`telegram-bot`](https://github.com/LukasKalbertodt/telegram-bot) library to communicate with the API. 12 | 13 | ## Usage 14 | 15 | This framework is available in `crates.io`. Just add this to your `Cargo.toml` dependencies: 16 | 17 | ``` 18 | [dependencies] 19 | awesome-bot = "0.1.0" 20 | ``` 21 | 22 | ## Example 23 | 24 | Here is a simple example (download from [`examples/simple.rs`](https://github.com/rockneurotiko/awesome-bot/blob/master/examples/simple.rs)). 25 | 26 | ```rust 27 | extern crate awesome_bot; 28 | 29 | use awesome_bot::*; 30 | 31 | fn echohandler(bot: &AwesomeBot, msg: &Message, _: String, args: Vec) { 32 | // We can access safely because the pattern match have that argument mandatory 33 | let toecho = &args[1]; 34 | let phrase = format!("Echoed: {}", toecho); 35 | // Send the text in a beauty way :) 36 | let sent = bot.answer(msg).text(&phrase).end(); 37 | println!("{:?}", sent); 38 | } 39 | 40 | fn main() { 41 | // Create the Awesome Bot (You need TELEGRAM_BOT_TOKEN environment with the token) 42 | let mut bot = AwesomeBot::from_env("TELEGRAM_BOT_TOKEN"); 43 | // Add a command, this will add the routing to that function. 44 | bot.command("echo (.+)", echohandler); 45 | 46 | // Start the bot with getUpdates 47 | let res = bot.simple_start(); 48 | if let Err(e) = res { 49 | println!("An error occurred: {}", e); 50 | } 51 | } 52 | ``` 53 | 54 | In the `examples` folder there is more code: 55 | 56 | - [`examples/simple.rs`](https://github.com/rockneurotiko/awesome-bot/blob/master/examples/simple.rs): An echo example, really simple. 57 | - [`examples/complete.rs`](https://github.com/rockneurotiko/awesome-bot/blob/master/examples/complete.rs): An example that have all (I think, probably not all, but almost all) features of `awesome-bot`, it's a big example ;-) 58 | 59 | *Note: To execute `examples/complete.rs` with all the features, you will need to add some test files that the bot will send, this files shall be: `files/test.{jpg, mp3, mp4, pdf, webp}` for image, audio/voice, video, document and sticker* 60 | 61 | ## Collaboration 62 | 63 | All help are welcome! Open issues, open PR of code or documentation, make suggestions, tell me that my rust sucks (and why), what you want :) 64 | 65 | You can contact me in [telegram](https://telegram.me/rockneurotiko). 66 | 67 | ## License 68 | 69 | Licensed under either of 70 | 71 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 72 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 73 | * Beerware ([LICENSE-BEERATE](LICENSE-BEERWARE)) or https://goo.gl/GGzTvj 74 | 75 | at your option. 76 | 77 | ### Contribution 78 | 79 | Unless you explicitly state otherwise, any contribution intentionally submitted 80 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be triple licensed as above, without any 81 | additional terms or conditions. 82 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /examples/complete.rs: -------------------------------------------------------------------------------- 1 | extern crate awesome_bot; 2 | 3 | use std::collections::HashMap; 4 | use std::iter::FromIterator; 5 | use std::{thread, time}; 6 | 7 | use awesome_bot::{ 8 | Audio, AwesomeBot, ChatAction, Document, Finisher, Float, Message, MessageType, PhotoSize, 9 | ReplyKeyboardMarkup, Sticker, Video, Voice, 10 | }; 11 | 12 | macro_rules! debug { 13 | ($e:expr) => { 14 | println!("{:?}", $e); 15 | }; 16 | } 17 | 18 | macro_rules! debug_msg { 19 | ($m:expr, $t:expr) => { 20 | println!("<{}> {}", $m.from.first_name, $t); 21 | }; 22 | ($m:expr) => { 23 | println!("<{}>", $m.from.first_name); 24 | }; 25 | } 26 | 27 | fn transform(vecs: Vec>) -> Vec> { 28 | vecs.iter() 29 | .map(|x| x.iter().map(|x| x.to_string()).collect()) 30 | .collect() 31 | } 32 | 33 | fn cmd_keyboard(bot: &AwesomeBot, msg: &Message, _: String) { 34 | let kbl = ReplyKeyboardMarkup { 35 | keyboard: transform(vec![vec!["I", "<3"], vec!["You"]]), 36 | resize_keyboard: None, 37 | one_time_keyboard: None, 38 | selective: None, 39 | }; 40 | debug!(bot.answer(msg).text("There you go!").keyboard(kbl).end()); 41 | } 42 | 43 | fn test_async_hand(bot: &AwesomeBot, msg: &Message, _: String) { 44 | debug!( 45 | bot.answer(msg) 46 | .text("Starting, send me another command in the next 5 seconds...") 47 | .end() 48 | ); 49 | thread::sleep(time::Duration::from_millis(5000)); 50 | debug!(bot.answer(msg).text("End async test").end()); 51 | } 52 | 53 | fn divide_by_two(it: T) -> Vec> { 54 | let mut result: Vec> = vec![]; 55 | let mut nit = it; 56 | loop { 57 | let e1 = nit.next(); 58 | let e2 = nit.next(); 59 | match (e1, e2) { 60 | (None, _) => break, // means that we are done! 61 | (Some(e11), Some(e21)) => result.push(vec![e11, e21]), 62 | (Some(e11), None) => result.push(vec![e11]), 63 | } 64 | } 65 | result 66 | } 67 | 68 | fn show_me_hand(bot: &AwesomeBot, msg: &Message, _: String) { 69 | let cmds = HashMap::<&str, &str>::from_iter(vec![ 70 | ("/start", "Start the bot!"), 71 | ("/keyboard", "Send you a keyboard"), 72 | ("/hidekeyboard", "Hide the keyboard"), 73 | ("/hardecho", "Echo with force reply"), 74 | ("/forwardme", "Forward that message to you"), 75 | ( 76 | "/sleep", 77 | "Sleep for 5 seconds, without blocking, awesome goroutines", 78 | ), 79 | ( 80 | "/showmecommands", 81 | "Returns you a keyboard with the simplest commands", 82 | ), 83 | ("/sendimage", "Sends you an image"), 84 | ("/sendimagekey", "Sends you an image with a custom keyboard"), 85 | ("/senddocument", "Sends you a document"), 86 | ("/sendsticker", "Sends you a sticker"), 87 | ("/sendvideo", "Sends you a video"), 88 | ("/sendlocation", "Sends you a location"), 89 | ("/sendchataction", "Sends a random chat action"), 90 | ]); 91 | 92 | let commands_k = divide_by_two(cmds.into_iter().map(|(x, _)| x)); 93 | let kbl = ReplyKeyboardMarkup { 94 | keyboard: transform(commands_k), 95 | resize_keyboard: None, 96 | one_time_keyboard: Some(true), 97 | selective: None, 98 | }; 99 | debug!( 100 | bot.answer(msg) 101 | .text("There you have the commands!") 102 | .keyboard(kbl) 103 | .end() 104 | ); 105 | } 106 | 107 | fn hide_keyboard(bot: &AwesomeBot, msg: &Message, _: String) { 108 | debug!(bot.answer(msg).text("Hiden!!").hide(true).end()); 109 | } 110 | 111 | fn handforw(bot: &AwesomeBot, msg: &Message, _: String) { 112 | debug!(bot.answer(msg).forward(msg.chat.id(), msg.message_id).end()); 113 | } 114 | 115 | fn hard_echo(bot: &AwesomeBot, msg: &Message, _: String, args: Vec) { 116 | debug!(bot.answer(msg).text(&args[1]).force(true).end()); 117 | } 118 | 119 | fn hello_hand(bot: &AwesomeBot, msg: &Message, _: String) { 120 | debug!( 121 | bot.answer(msg) 122 | .text(&format!("Hi {}!", msg.from.first_name)) 123 | .end() 124 | ); 125 | } 126 | 127 | fn tell_me_hand(bot: &AwesomeBot, msg: &Message, _: String, args: Vec) { 128 | debug!(bot.answer(msg).text(&args[1]).end()); 129 | } 130 | 131 | // ====== 132 | // LOGGER 133 | // ====== 134 | 135 | fn all_msg_hand(_: &AwesomeBot, msg: &Message) { 136 | if let MessageType::Text(ref t) = msg.msg { 137 | debug_msg!(msg, t); 138 | } else { 139 | debug_msg!(msg); 140 | } 141 | } 142 | 143 | // ============= 144 | // Send media handlers 145 | // ============= 146 | 147 | fn handimage(bot: &AwesomeBot, msg: &Message, _: String) { 148 | debug!(bot.answer(msg).photo("files/test.jpg").end()); 149 | } 150 | 151 | fn handaudio(bot: &AwesomeBot, msg: &Message, _: String) { 152 | debug!(bot.answer(msg).audio("files/test.mp3").end()); 153 | } 154 | 155 | fn handvoice(bot: &AwesomeBot, msg: &Message, _: String) { 156 | debug!(bot.answer(msg).voice("files/test.mp3").end()); 157 | } 158 | 159 | fn handdoc(bot: &AwesomeBot, msg: &Message, _: String) { 160 | debug!(bot.answer(msg).document("files/test.pdf").end()); 161 | } 162 | 163 | fn handstick(bot: &AwesomeBot, msg: &Message, _: String) { 164 | debug!(bot.answer(msg).sticker("files/test.webp").end()); 165 | } 166 | 167 | fn handvideo(bot: &AwesomeBot, msg: &Message, _: String) { 168 | debug!(bot.answer(msg).video("files/test.mp4").end()); 169 | } 170 | 171 | fn handlocation(bot: &AwesomeBot, msg: &Message, _: String) { 172 | debug!(bot.answer(msg).location(40.324159, -4.21096).end()); 173 | } 174 | 175 | fn handaction(bot: &AwesomeBot, msg: &Message, _: String) { 176 | debug!(bot.answer(msg).action(ChatAction::Typing).end()); 177 | } 178 | 179 | // ================= 180 | // MEDIA HANDLERS 181 | // ================= 182 | 183 | fn transform_info_photos(v: Vec) -> String { 184 | v.iter() 185 | .map(|p| { 186 | format!( 187 | "Image of size ({} x {})\nID: {}\nSize: {}", 188 | p.width, 189 | p.height, 190 | p.file_id, 191 | p.file_size.unwrap_or(0) 192 | ) 193 | }) 194 | .collect::>() 195 | .join("\n----------\n") 196 | } 197 | 198 | fn photo_handler(bot: &AwesomeBot, msg: &Message, photos: Vec) { 199 | let imageinfo = transform_info_photos(photos); 200 | debug!(bot.answer(msg).text(&imageinfo).end()); 201 | } 202 | 203 | fn audio_handler(bot: &AwesomeBot, msg: &Message, audio: Audio) { 204 | let message = format!("Information about the audio:\nID: {}\nDuration: {} seconds\nPerformer: {}\nTitle: {}\nMimeType: {}\nFile size: {} Bytes", audio.file_id, audio.duration, audio.performer.unwrap_or("No performer".into()), audio.title.unwrap_or("No title".into()), audio.mime_type.unwrap_or("No mime type".into()), audio.file_size.unwrap_or(0)); 205 | debug!(bot.answer(msg).text(&message).end()); 206 | } 207 | 208 | fn voice_handler(bot: &AwesomeBot, msg: &Message, voice: Voice) { 209 | let message = format!("Information about the voice:\nID: {}\nDuration: {} seconds\nMimeType: {}\nFile size: {} Bytes", voice.file_id, voice.duration, voice.mime_type.unwrap_or("No mime type".into()), voice.file_size.unwrap_or(0)); 210 | debug!(bot.answer(msg).text(&message).end()); 211 | } 212 | 213 | fn document_handler(bot: &AwesomeBot, msg: &Message, document: Document) { 214 | let mut message = format!( 215 | "Information about the document:\nID: {}\nFile name: {}\nMimeType: {}\nFile size: {} Bytes", 216 | document.file_id, 217 | document.file_name.unwrap_or("No name".into()), 218 | document.mime_type.unwrap_or("No mime type".into()), 219 | document.file_size.unwrap_or(0) 220 | ); 221 | if let Some(thumb) = document.thumb { 222 | message = format!( 223 | "{}\nAnd the information about the thumb:\n{}", 224 | message, 225 | transform_info_photos(vec![thumb]) 226 | ); 227 | } 228 | // Add thumb 229 | debug!(bot.answer(msg).text(&message).end()); 230 | } 231 | 232 | fn sticker_handler(bot: &AwesomeBot, msg: &Message, sticker: Sticker) { 233 | let mut message = format!( 234 | "Information about the sticker:\nID: {}\nWidth: {}\nHeight: {}\nFile size: {} Bytes", 235 | sticker.file_id, 236 | sticker.width, 237 | sticker.height, 238 | sticker.file_size.unwrap_or(0) 239 | ); 240 | // Add thumb 241 | if let Some(thumb) = sticker.thumb { 242 | message = format!( 243 | "{}\nAnd the information about the thumb:\n{}", 244 | message, 245 | transform_info_photos(vec![thumb]) 246 | ); 247 | } 248 | debug!(bot.answer(msg).text(&message).end()); 249 | } 250 | 251 | fn video_handler(bot: &AwesomeBot, msg: &Message, video: Video) { 252 | let mut message = format!("Information about the video:\nID: {}\nWidth: {}\nHeight: {}\nDuration: {}\nMime type: {}\nFile size: {} Bytes", video.file_id, video.width, video.height, video.duration, video.mime_type.unwrap_or("No mime type".into()), video.file_size.unwrap_or(0)); 253 | // Add thumb 254 | if let Some(thumb) = video.thumb { 255 | message = format!( 256 | "{}\nThumb:\n{}", 257 | message, 258 | transform_info_photos(vec![thumb]) 259 | ); 260 | } 261 | debug!(bot.answer(msg).text(&message).end()); 262 | } 263 | 264 | fn location_handler(bot: &AwesomeBot, msg: &Message, latitude: Float, longitude: Float) { 265 | let message = format!( 266 | "Information of location:\nLatitude: {}\nLongitude: {}", 267 | latitude, longitude 268 | ); 269 | debug!(bot.answer(msg).text(&message).end()); 270 | } 271 | 272 | fn main() { 273 | let mut bot = AwesomeBot::from_env("TELEGRAM_BOT_TOKEN"); 274 | 275 | // Logger :) 276 | bot.any_fn(all_msg_hand); // Just to print all the messages 277 | 278 | // Random handlers 279 | bot.simple_command("sleep", test_async_hand) // Test to prove asynchronous 280 | .simple_command("showmecommands", show_me_hand) // Send a keyboard with all the commands 281 | .simple_command("keyboard", cmd_keyboard) // Send a keyboard 282 | .simple_command("hidekeyboard", hide_keyboard) // Hide the keyboard 283 | .simple_command("forwardme", handforw) // Forward the message 284 | .command("hardecho (.+)", hard_echo) // Echo the text with a force reply 285 | .simple_regex("^Hello!?$", hello_hand) // Answer to Hello! 286 | .regex("^Tell me (.+)$", tell_me_hand); // An echo without command 287 | 288 | // Add commands that send media files (And action) 289 | // To make this commands work, you need files to send: 290 | // files/test.{jpg, mp3, mp4, pdf, webp} 291 | bot.simple_command("sendimage", handimage) 292 | .simple_command("sendaudio", handaudio) 293 | .simple_command("sendvoice", handvoice) 294 | .simple_command("senddocument", handdoc) 295 | .simple_command("sendsticker", handstick) 296 | .simple_command("sendvideo", handvideo) 297 | .simple_command("sendlocation", handlocation) 298 | .simple_command("sendaction", handaction); 299 | 300 | // Add handlers that react with media files received sending information 301 | bot.photo_fn(photo_handler) 302 | .audio_fn(audio_handler) 303 | .voice_fn(voice_handler) 304 | .document_fn(document_handler) 305 | .sticker_fn(sticker_handler) 306 | .video_fn(video_handler) 307 | .location_fn(location_handler); 308 | 309 | let res = bot.simple_start(); 310 | if let Err(e) = res { 311 | println!("An error occured: {}", e); 312 | } 313 | } 314 | -------------------------------------------------------------------------------- /src/send.rs: -------------------------------------------------------------------------------- 1 | use rustc_serialize::Decodable; 2 | use telegram_bot::*; 3 | 4 | /// Help trait indicating that at least the `end` method is implemented for the SendBuilder structs 5 | pub trait Finisher { 6 | fn end(&mut self) -> Result; 7 | } 8 | 9 | /// SendBuilder it's a builder struct that allows you to construct answers in 10 | /// a composable way, you will use it transparently with the `send` and `answer` 11 | /// methods of `AwesomeBot` 12 | #[derive(Clone)] 13 | pub struct SendBuilder { 14 | chat_id: Integer, 15 | bot: Api, 16 | } 17 | 18 | impl SendBuilder { 19 | /// Create a new SendBuilder, don't use it, 20 | /// use the `send` and `answer` methods of `AwesomeBot` :) 21 | pub fn new(id: Integer, bot: Api) -> SendBuilder { 22 | SendBuilder { 23 | chat_id: id, 24 | bot: bot, 25 | } 26 | } 27 | 28 | /// Start a text constructor to send. 29 | pub fn text(self, t: &str) -> SendText { 30 | SendText { 31 | send: self, 32 | text: t.to_string(), 33 | parse_mode: None, 34 | disable_webpage_preview: None, 35 | reply_to_message_id: None, 36 | reply_markup: None, 37 | } 38 | } 39 | 40 | /// Start a photo constructor to send. 41 | pub fn photo(self, t: &str) -> SendPhoto { 42 | SendPhoto { 43 | send: self, 44 | photo: t.to_string(), 45 | caption: None, 46 | reply_to_message_id: None, 47 | reply_markup: None, 48 | } 49 | } 50 | 51 | /// Start an audio constructor to send. 52 | pub fn audio(self, t: &str) -> SendAudio { 53 | SendAudio { 54 | send: self, 55 | audio: t.to_string(), 56 | duration: None, 57 | performer: None, 58 | title: None, 59 | reply_to_message_id: None, 60 | reply_markup: None, 61 | } 62 | } 63 | 64 | /// Start a voice constructor to send. 65 | pub fn voice(self, t: &str) -> SendVoice { 66 | SendVoice { 67 | send: self, 68 | voice: t.to_string(), 69 | duration: None, 70 | reply_to_message_id: None, 71 | reply_markup: None, 72 | } 73 | } 74 | 75 | /// Start a document constructor to send. 76 | pub fn document(self, t: &str) -> SendDocument { 77 | SendDocument { 78 | send: self, 79 | document: t.to_string(), 80 | reply_to_message_id: None, 81 | reply_markup: None, 82 | } 83 | } 84 | 85 | /// Start a sticker constructor to send. 86 | pub fn sticker(self, t: &str) -> SendSticker { 87 | SendSticker { 88 | send: self, 89 | sticker: t.to_string(), 90 | reply_to_message_id: None, 91 | reply_markup: None, 92 | } 93 | } 94 | 95 | /// Start a video constructor to send. 96 | pub fn video(self, t: &str) -> SendVideo { 97 | SendVideo { 98 | send: self, 99 | video: t.to_string(), 100 | caption: None, 101 | duration: None, 102 | reply_to_message_id: None, 103 | reply_markup: None, 104 | } 105 | } 106 | 107 | /// Start a forward constructor to send. 108 | pub fn forward(self, to: Integer, msg: Integer) -> SendForward { 109 | SendForward { 110 | send: self, 111 | to: to, 112 | msg: msg, 113 | } 114 | } 115 | 116 | /// Start an action constructor to send. 117 | pub fn action(self, action: ChatAction) -> SendAction { 118 | SendAction { 119 | send: self, 120 | action: action, 121 | } 122 | } 123 | 124 | /// Start a location constructor to send. 125 | pub fn location(self, latitude: Float, longitude: Float) -> SendLocation { 126 | SendLocation { 127 | send: self, 128 | latitude: latitude, 129 | longitude: longitude, 130 | reply_to_message_id: None, 131 | reply_markup: None, 132 | } 133 | } 134 | } 135 | 136 | macro_rules! basesendtype { 137 | ( 138 | $name: ident, 139 | $structdoc: expr, 140 | [$($id: ident => $field: ty),*], 141 | [$($o_id: ident => ($o_name: ident, $o_field: ty, $docf: expr)),*]) => { 142 | 143 | #[doc="Transparent struct built by `SendBuilder` to send"] 144 | #[doc=$structdoc] 145 | #[doc="messages."] 146 | pub struct $name { 147 | send: SendBuilder, 148 | $($id: $field),* 149 | , 150 | $($o_id: Option<$o_field>),* 151 | } 152 | 153 | impl $name { 154 | $( 155 | #[doc=$docf] 156 | pub fn $o_name(&mut self, v: $o_field) -> &mut $name { 157 | self.$o_id = Some(v); 158 | self 159 | } 160 | )* 161 | } 162 | } 163 | } 164 | 165 | macro_rules! addkeyboardfuncs { 166 | ($name:ident, $markname:ident) => { 167 | /// Add keyboard methods to the struct, only one of these will be sent, 168 | /// and it will be the last one used. 169 | impl $name { 170 | /// Add a keyboard to the reply 171 | pub fn keyboard(&mut self, r: ReplyKeyboardMarkup) -> &mut $name { 172 | self.$markname = Some(ReplyMarkup::from(r)); 173 | self 174 | } 175 | 176 | /// Hide the keyboard 177 | pub fn hide(&mut self, h: bool) -> &mut $name { 178 | self.$markname = Some(ReplyMarkup::KeyboardHide(h)); 179 | self 180 | } 181 | 182 | /// Force the reply to this message 183 | pub fn force(&mut self, f: bool) -> &mut $name { 184 | self.$markname = Some(ReplyMarkup::ForceReply(f)); 185 | self 186 | } 187 | } 188 | }; 189 | } 190 | 191 | basesendtype!(SendText, 192 | "`Text`", 193 | [text => String], 194 | [parse_mode => (parse_mode, ParseMode, "Set `ParseMode` for the message"), 195 | disable_webpage_preview => (disable_preview, bool, "Set `true` to disable the link preview in the message."), 196 | reply_to_message_id => (reply_id, Integer, "Set a message ID to reply to with this message."), 197 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of directly using this, use the `keyboard`, `hide` or `force` methods")]); 198 | 199 | addkeyboardfuncs!(SendText, reply_markup); 200 | 201 | impl Finisher for SendText { 202 | fn end(&mut self) -> Result { 203 | self.send.bot.send_message( 204 | self.send.chat_id, 205 | self.text.clone(), 206 | self.parse_mode, 207 | self.disable_webpage_preview, 208 | self.reply_to_message_id, 209 | self.reply_markup.clone(), 210 | ) 211 | } 212 | } 213 | 214 | basesendtype!(SendPhoto, 215 | "`Photo`", 216 | [photo => String], 217 | [caption => (caption, String, "Set a caption to be included with the message."), 218 | reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 219 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 220 | 221 | addkeyboardfuncs!(SendPhoto, reply_markup); 222 | 223 | impl Finisher for SendPhoto { 224 | fn end(&mut self) -> Result { 225 | self.send.bot.send_photo( 226 | self.send.chat_id, 227 | self.photo.clone(), 228 | self.caption.clone(), 229 | self.reply_to_message_id, 230 | self.reply_markup.clone(), 231 | ) 232 | } 233 | } 234 | 235 | basesendtype!(SendAudio, 236 | "`Audio`", 237 | [audio => String], 238 | [duration => (duration, Integer, "Set the duration of the track"), 239 | performer => (performer, String, "Set the performer of the track"), 240 | title => (title, String, "Set the title of the track"), 241 | reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 242 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 243 | 244 | addkeyboardfuncs!(SendAudio, reply_markup); 245 | 246 | impl Finisher for SendAudio { 247 | fn end(&mut self) -> Result { 248 | self.send.bot.send_audio( 249 | self.send.chat_id, 250 | self.audio.clone(), 251 | self.duration, 252 | self.performer.clone(), 253 | self.title.clone(), 254 | self.reply_to_message_id, 255 | self.reply_markup.clone(), 256 | ) 257 | } 258 | } 259 | 260 | basesendtype!(SendVoice, 261 | "`Voice`", 262 | [voice => String], 263 | [duration => (duration, Integer, "Set the duration of the voice audio."), 264 | reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 265 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 266 | 267 | addkeyboardfuncs!(SendVoice, reply_markup); 268 | 269 | impl Finisher for SendVoice { 270 | fn end(&mut self) -> Result { 271 | self.send.bot.send_voice( 272 | self.send.chat_id, 273 | self.voice.clone(), 274 | self.duration, 275 | self.reply_to_message_id, 276 | self.reply_markup.clone(), 277 | ) 278 | } 279 | } 280 | 281 | basesendtype!(SendDocument, 282 | "`Document`", 283 | [document => String], 284 | [reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 285 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 286 | 287 | addkeyboardfuncs!(SendDocument, reply_markup); 288 | 289 | impl Finisher for SendDocument { 290 | fn end(&mut self) -> Result { 291 | self.send.bot.send_document( 292 | self.send.chat_id, 293 | self.document.clone(), 294 | self.reply_to_message_id, 295 | self.reply_markup.clone(), 296 | ) 297 | } 298 | } 299 | 300 | basesendtype!(SendSticker, 301 | "`Sticker`", 302 | [sticker => String], 303 | [reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 304 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 305 | 306 | addkeyboardfuncs!(SendSticker, reply_markup); 307 | 308 | impl Finisher for SendSticker { 309 | fn end(&mut self) -> Result { 310 | self.send.bot.send_sticker( 311 | self.send.chat_id, 312 | self.sticker.clone(), 313 | self.reply_to_message_id, 314 | self.reply_markup.clone(), 315 | ) 316 | } 317 | } 318 | 319 | basesendtype!(SendVideo, 320 | "`Video`", 321 | [video => String], 322 | [caption => (caption, String, "Set a caption to be included with the message."), 323 | duration => (duration, Integer, "Set the duration of the video"), 324 | reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 325 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 326 | 327 | addkeyboardfuncs!(SendVideo, reply_markup); 328 | 329 | impl Finisher for SendVideo { 330 | fn end(&mut self) -> Result { 331 | self.send.bot.send_video( 332 | self.send.chat_id, 333 | self.video.clone(), 334 | self.caption.clone(), 335 | self.duration, 336 | self.reply_to_message_id, 337 | self.reply_markup.clone(), 338 | ) 339 | } 340 | } 341 | 342 | basesendtype!(SendForward, 343 | "`Forward`", 344 | [to => Integer, msg => Integer], 345 | []); 346 | 347 | impl Finisher for SendForward { 348 | fn end(&mut self) -> Result { 349 | self.send 350 | .bot 351 | .forward_message(self.send.chat_id, self.to, self.msg) 352 | } 353 | } 354 | 355 | basesendtype!(SendAction, 356 | "`Action`", 357 | [action => ChatAction], 358 | []); 359 | 360 | impl Finisher for SendAction { 361 | fn end(&mut self) -> Result { 362 | self.send 363 | .bot 364 | .send_chat_action(self.send.chat_id, self.action) 365 | } 366 | } 367 | 368 | basesendtype!(SendLocation, 369 | "`Location`", 370 | [latitude => Float, 371 | longitude => Float], 372 | [reply_to_message_id => (reply_id, Integer, "Set a message ID to reply with this message."), 373 | reply_markup => (markup, ReplyMarkup, "Set a `ReplyMarkup` to send, but instead of this, use the `keyboard`, `hide` or `force` methods")]); 374 | 375 | addkeyboardfuncs!(SendLocation, reply_markup); 376 | 377 | impl Finisher for SendLocation { 378 | fn end(&mut self) -> Result { 379 | self.send.bot.send_location( 380 | self.send.chat_id, 381 | self.latitude, 382 | self.longitude, 383 | self.reply_to_message_id, 384 | self.reply_markup.clone(), 385 | ) 386 | } 387 | } 388 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate helps writing bots for Telegram. This is a framework to build the bots, 2 | //! the main wrapped crate is `telegram-bot` which provides the actual protocol access. 3 | //! 4 | //! How to use it 5 | //! ------------- 6 | //! 7 | //! The first step is always to create the AwesomeBot instance, 8 | //! this will represent your bot, so, if you have more than one bot, 9 | //! you will have to create more instances. 10 | //! 11 | //! You have two ways to create the bot, with `new`, 12 | //! that you pass the bot token directly, or with `from_env`, more recommended. 13 | //! 14 | //! This framework uses the "route" pattern to apply behavior. 15 | //! There are plenty of routing ways available, the main ones are: 16 | //! `command`, `simple_command`, `any_fn`. 17 | //! But there are many more, check the docs of [AwesomeBot](struct.AwesomeBot.html) 18 | //! 19 | //! Then, to send things you need to use the SendBuilder struct, to create an instance use 20 | //! the `send` or `answer` methods in `AwesomeBot`. 21 | //! 22 | //! This uses the "builder" pattern, for example, to answer a message with a text, 23 | //! while disabling web pages, you do (Assuming that bot is `&AwesomeBot` and msg is `&Message`): 24 | //! 25 | //! ``` ignore 26 | //! bot.answer(msg).text("Answering this text").disable_preview(true).end(); 27 | //! ``` 28 | //! 29 | //! Check [`SendBuilder`](struct.SendBuilder.html) struct implementation to see the methods 30 | //! available (text, photo, audio, ...) 31 | //! 32 | //! Once you have all your routings, you need to start the bot, right now it supports only 33 | //! getUpdates method, just call the `simple_start` method in AwesomeBot. 34 | //! 35 | //! You don't have to worry about blocking the bot in a function handler, 36 | //! because it uses a thread pool (of 4 threads right now, 37 | //! it will be configurable in the future), so the handling for 38 | //! a message is done in his own thread. 39 | //! 40 | //! # Examples 41 | //! 42 | //! ## Minimalistic example (Echo text) 43 | //! ```no_run 44 | //! extern crate awesome_bot; 45 | //! 46 | //! use awesome_bot::*; 47 | //! 48 | //! fn echohandler(bot: &AwesomeBot, msg: &Message, _: String, args: Vec) { 49 | //! // We can access safely because the pattern match have that argument mandatory 50 | //! let toecho = &args[1]; 51 | //! let phrase = format!("Echoed: {}", toecho); 52 | //! // Send the text in a beauty way :) 53 | //! let sended = bot.answer(msg).text(&phrase).end(); 54 | //! println!("{:?}", sended); 55 | //! } 56 | //! 57 | //! fn main() { 58 | //! // Create the Awesome Bot (You need TELEGRAM_BOT_TOKEN environment with the token) 59 | //! let mut bot = AwesomeBot::from_env("TELEGRAM_BOT_TOKEN"); 60 | //! // Add a command, this will add the routing to that function. 61 | //! bot.command("echo (.+)", echohandler); 62 | //! 63 | //! // Start the bot with getUpdates 64 | //! let res = bot.simple_start(); 65 | //! if let Err(e) = res { 66 | //! println!("An error occurred: {}", e); 67 | //! } 68 | //! } 69 | //! ``` 70 | //! 71 | //! ## More examples 72 | //! You have more examples in `examples/` directory in the project's repository. 73 | //! 74 | 75 | extern crate regex; 76 | extern crate rustc_serialize; 77 | extern crate scoped_threadpool; 78 | extern crate telegram_bot; 79 | 80 | mod send; 81 | mod test; 82 | 83 | pub use send::*; 84 | 85 | pub use telegram_bot::*; 86 | 87 | use scoped_threadpool::Pool; 88 | 89 | use regex::Regex; 90 | use std::env; 91 | use std::sync::Arc; 92 | 93 | /// Represents audio and voice, this is used in `all_music_fn` handler. 94 | pub enum GeneralSound { 95 | Audio(Audio), 96 | Voice(Voice), 97 | } 98 | 99 | // This enumeration determines what type of routing handler to use 100 | #[derive(Clone)] 101 | enum Muxer { 102 | PatternMux( 103 | Regex, 104 | Arc) + Send + Sync + 'static>, 105 | ), 106 | TextMux( 107 | Regex, 108 | Arc, 109 | ), 110 | PhotoMux(Arc) + Send + Sync + 'static>), 111 | VideoMux(Arc), 112 | DocumentMux(Arc), 113 | StickerMux(Arc), 114 | AudioMux(Arc), 115 | VoiceMux(Arc), 116 | GeneralAudioMux(Arc), 117 | ContactMux(Arc), 118 | LocationMux(Arc), 119 | NewParticipantMux(Arc), 120 | LeftParticipantMux(Arc), 121 | NewTitleMux(Arc), 122 | NewChatPhotoMux(Arc) + Send + Sync + 'static>), 123 | DeleteChatPhotoMux(Arc), 124 | GroupChatCreatedMux(Arc), 125 | SuperGroupChatCreatedMux( 126 | Arc, 127 | ), 128 | ChannelChatCreatedMux(Arc), 129 | AnyMux(Arc), 130 | } 131 | 132 | // This macro matches one muxer and executes a block while sending "Any" message :) 133 | // First: self 134 | // Second: msg to pass 135 | // Third: List of Patterns to match => Code block to execute for that Pattern 136 | macro_rules! muxer_match { 137 | ($_self: expr, $msg: expr, [$($pat:pat => $result: expr),*]) => { 138 | for m in &$_self.muxers { 139 | match m { 140 | &Muxer::AnyMux(ref f) => { 141 | f($_self, &$msg); 142 | }, 143 | $($pat => $result,)* 144 | _ => {}, 145 | } 146 | } 147 | } 148 | } 149 | 150 | // This macro adds a muxer to the muxers vec 151 | // First: self 152 | // Second: handler (function to add) 153 | // Third: The Muxer enum type 154 | // Fourth: List of extra parameters, in order, first passed to the muxer 155 | macro_rules! add_muxer { 156 | ($_self: expr, 157 | $handler: expr, 158 | $mux: expr, 159 | [$($extra: expr),*]) => { 160 | { 161 | let fa = Arc::new($handler); 162 | $_self.muxers.push($mux($($extra,)* fa.clone())); 163 | $_self 164 | } 165 | } 166 | } 167 | 168 | /// Main type for building the Telegram Bot. 169 | /// 170 | /// Create a new instance using `new` or `from_env`, add routing handlers and start the bot. 171 | pub struct AwesomeBot { 172 | bot: Api, 173 | /// The ID of the bot. 174 | pub id: Integer, 175 | /// The username of the bot. 176 | pub username: String, 177 | muxers: Vec, 178 | } 179 | 180 | impl Clone for AwesomeBot { 181 | fn clone(&self) -> AwesomeBot { 182 | let b = self.bot.clone(); 183 | let mut v: Vec = Vec::new(); 184 | for m in &self.muxers { 185 | v.push(m.clone()); 186 | } 187 | AwesomeBot { 188 | bot: b, 189 | id: self.id, 190 | username: self.username.clone(), 191 | muxers: v, 192 | } 193 | } 194 | } 195 | 196 | // unsafe impl Send for AwesomeBot { } 197 | // unsafe impl Sync for AwesomeBot { } 198 | 199 | impl AwesomeBot { 200 | // =========================================================== 201 | // Constructors 202 | // =========================================================== 203 | /// Creates a new bot with the given token. This checks that the token is a 204 | /// valid Telegram Bot Token by calling `get_me`. 205 | /// It panics if the token is invalid. 206 | pub fn new(token: &str) -> AwesomeBot { 207 | let bot = Api::from_token(token).unwrap(); 208 | match bot.get_me() { 209 | Ok(user) => AwesomeBot { 210 | bot: bot, 211 | id: user.id, 212 | username: user.username.unwrap_or("".to_string()), 213 | muxers: Vec::new(), 214 | }, 215 | Err(e) => panic!("Invalid token! ({})", e), 216 | } 217 | } 218 | 219 | /// Will receive the Bot Token from the environment variable `var` and call `new`. 220 | /// It panics if the environment variable can't be read or if the token is invalid. 221 | pub fn from_env(var: &str) -> AwesomeBot { 222 | let token = env::var(var) 223 | .ok() 224 | .expect(&format!("Environment variable {} error.", var)); 225 | 226 | Self::new(&token) 227 | } 228 | 229 | // Listener functions 230 | 231 | /// Start the bot using `getUpdates` method, calling the routes defined before calling this method. 232 | pub fn simple_start(&self) -> Result<()> { 233 | let mut listener = self.bot.listener(ListeningMethod::LongPoll(Some(20))); 234 | let mut pool = Pool::new(4); 235 | // let botcloned = Arc::new(self.clone()); 236 | 237 | pool.scoped(|scoped| { 238 | // Handle updates 239 | let result = listener.listen(|u| { 240 | if let Some(m) = u.message { 241 | // let bot_instance = botcloned.clone(); 242 | scoped.execute(move || { 243 | // bot_instance.handle_message(m); 244 | self.handle_message(m); 245 | }); 246 | } 247 | Ok(ListeningAction::Continue) 248 | }); 249 | scoped.join_all(); // Wait all scoped threads to finish 250 | result 251 | }) 252 | } 253 | 254 | // Send builders 255 | /// Start a SendBuilder directly with the id, this is useful when you have the id saved and want to send a message. 256 | pub fn send(&self, id: Integer) -> SendBuilder { 257 | SendBuilder::new(id, self.bot.clone()) 258 | } 259 | 260 | /// Start a SendBuilder answering a message directly, this is used to answer in a handler to the sender of the message. 261 | pub fn answer(&self, m: &Message) -> SendBuilder { 262 | self.send(m.chat.id()) 263 | } 264 | 265 | // AUXILIARY FUNCTIONS 266 | 267 | // This function modifies the command by adding the username and some regex cleanup 268 | fn modify_command(orig: &str, username: &str) -> String { 269 | let s = String::from(orig); 270 | let mut words: Vec = s.split_whitespace().map(|x| String::from(x)).collect(); 271 | 272 | if words.len() >= 1 { 273 | let mut lastchar = ""; 274 | let mut comm = words.remove(0); 275 | if comm.ends_with("$") { 276 | lastchar = "$"; 277 | comm.pop(); 278 | } 279 | let ns: String = format!("{}(?:@{})?{}", comm, username, lastchar); 280 | words.insert(0, ns); 281 | } 282 | 283 | let mut ns: String = words.join(" "); 284 | if !ns.starts_with("^/") { 285 | if !ns.starts_with("/") { 286 | ns.insert(0, '/'); 287 | } 288 | if !s.starts_with("^") { 289 | ns.insert(0, '^'); 290 | } 291 | } 292 | if !ns.ends_with("$") { 293 | ns.push_str("$"); 294 | } 295 | ns 296 | } 297 | } 298 | 299 | // Internal handler functions 300 | impl AwesomeBot { 301 | fn handle_text_msg(&self, msg: &Message, text: String) { 302 | use Muxer::*; 303 | muxer_match!(self, msg, 304 | [&TextMux(ref r, ref f) => 305 | { 306 | if r.is_match(&text) { 307 | f(self, msg, text.clone()); 308 | } 309 | }, 310 | &PatternMux(ref r, ref f) => 311 | { 312 | if r.is_match(&text) { // If there are matches 313 | r.captures(&text) // Get the captures 314 | .map(|c| { // Map over them because they are Option<_> 315 | // Change the capture groups to Vec 316 | c.iter().map(|x| String::from(x.unwrap_or(""))) 317 | .collect::>() 318 | }) 319 | .map(|captures_vec|{ 320 | // If everything goes well, call the function 321 | f(self, msg, text.clone(), captures_vec) 322 | }); 323 | } 324 | }] 325 | ); 326 | } 327 | 328 | fn handle_image_msg(&self, msg: &Message, photos: Vec) { 329 | use Muxer::*; 330 | muxer_match!(self, msg, 331 | [&PhotoMux(ref f) => f(self, msg, photos.clone())] 332 | ); 333 | } 334 | 335 | fn handle_video_msg(&self, msg: &Message, video: Video) { 336 | use Muxer::*; 337 | muxer_match!(self, msg, 338 | [&VideoMux(ref f) => f(self, msg, video.clone())] 339 | ); 340 | } 341 | 342 | fn handle_document_msg(&self, msg: &Message, document: Document) { 343 | use Muxer::*; 344 | muxer_match!(self, msg, 345 | [&DocumentMux(ref f) => f(self, msg, document.clone())] 346 | ); 347 | } 348 | 349 | fn handle_sticker_msg(&self, msg: &Message, sticker: Sticker) { 350 | use Muxer::*; 351 | muxer_match!(self, msg, 352 | [&StickerMux(ref f) => f(self, msg, sticker.clone())] 353 | ); 354 | } 355 | 356 | fn handle_audio_msg(&self, msg: &Message, audio: Audio) { 357 | use Muxer::*; 358 | muxer_match!(self, msg, 359 | [&AudioMux(ref f) => f(self, msg, audio.clone()), 360 | &GeneralAudioMux(ref f) => f(self, msg, GeneralSound::Audio(audio.clone()))] 361 | ); 362 | } 363 | 364 | fn handle_voice_msg(&self, msg: &Message, voice: Voice) { 365 | use Muxer::*; 366 | muxer_match!(self, msg, 367 | [&VoiceMux(ref f) => f(self, msg, voice.clone()), 368 | &GeneralAudioMux(ref f) => f(self, msg, GeneralSound::Voice(voice.clone()))] 369 | ); 370 | } 371 | 372 | fn handle_contact_msg(&self, msg: &Message, cont: Contact) { 373 | use Muxer::*; 374 | muxer_match!(self, msg, 375 | [&ContactMux(ref f) => f(self, msg, cont.clone())] 376 | ); 377 | } 378 | 379 | fn handle_location_msg(&self, msg: &Message, f1: Float, f2: Float) { 380 | use Muxer::*; 381 | muxer_match!(self, msg, 382 | [&LocationMux(ref f) => f(self, msg, f1, f2)] 383 | ); 384 | } 385 | 386 | fn handle_new_chat_msg(&self, msg: &Message, newp: User) { 387 | use Muxer::*; 388 | muxer_match!(self, msg, 389 | [&NewParticipantMux(ref f) => f(self, msg, newp.clone())] 390 | ); 391 | } 392 | 393 | fn handle_left_part_msg(&self, msg: &Message, user: User) { 394 | use Muxer::*; 395 | muxer_match!(self, msg, 396 | [&LeftParticipantMux(ref f) => f(self, msg, user.clone())] 397 | ); 398 | } 399 | 400 | fn handle_new_title_msg(&self, msg: &Message, title: String) { 401 | use Muxer::*; 402 | muxer_match!(self, msg, 403 | [&NewTitleMux(ref f) => f(self, msg, title.clone())] 404 | ); 405 | } 406 | 407 | fn handle_chat_photo_msg(&self, msg: &Message, photos: Vec) { 408 | use Muxer::*; 409 | muxer_match!(self, msg, 410 | [&NewChatPhotoMux(ref f) => f(self, msg, photos.clone())] 411 | ); 412 | } 413 | 414 | fn handle_delete_photo_msg(&self, msg: &Message, group: Chat) { 415 | use Muxer::*; 416 | muxer_match!(self, msg, 417 | [&DeleteChatPhotoMux(ref f) => f(self, msg, group.clone())] 418 | ); 419 | } 420 | 421 | fn handle_group_created_msg(&self, msg: &Message, group: Chat) { 422 | use Muxer::*; 423 | muxer_match!(self, msg, 424 | [&GroupChatCreatedMux(ref f) => f(self, msg, group.clone())] 425 | ); 426 | } 427 | 428 | fn handle_super_group_chat_created_msg( 429 | &self, 430 | msg: &Message, 431 | migration: GroupToSuperGroupMigration, 432 | ) { 433 | use Muxer::*; 434 | muxer_match!(self, msg, [&SuperGroupChatCreatedMux (ref f) => f(self, msg, migration.clone())]); 435 | } 436 | 437 | fn handle_channel_chat_created_msg(&self, msg: &Message, chat: Chat) { 438 | use Muxer::*; 439 | muxer_match!(self, msg, [&ChannelChatCreatedMux (ref f) => f(self, msg, chat.clone())]); 440 | } 441 | 442 | fn handle_message(&self, message: Message) { 443 | // use MessageType::*; // When nightly becomes stable? 444 | use telegram_bot::MessageType::*; 445 | // // Any message 446 | // let anybot = bot.clone(); 447 | // let anym = m.clone(); 448 | // thread::spawn(move || { 449 | // anybot.handle_any_msg(anym); 450 | // }); 451 | 452 | // Rest of messages :) 453 | match message.msg.clone() { 454 | Text(text) => self.handle_text_msg(&message, text), 455 | Audio(audio) => self.handle_audio_msg(&message, audio), 456 | Voice(voice) => self.handle_voice_msg(&message, voice), 457 | Photo(photos) => self.handle_image_msg(&message, photos), 458 | File(document) => self.handle_document_msg(&message, document), 459 | Sticker(sticker) => self.handle_sticker_msg(&message, sticker), 460 | Video(video) => self.handle_video_msg(&message, video), 461 | Contact(contact) => self.handle_contact_msg(&message, contact), 462 | Location(loc) => self.handle_location_msg(&message, loc.latitude, loc.longitude), 463 | NewChatParticipant(user) => self.handle_new_chat_msg(&message, user), 464 | LeftChatParticipant(user) => self.handle_left_part_msg(&message, user), 465 | NewChatTitle(title) => self.handle_new_title_msg(&message, title), 466 | NewChatPhoto(photos) => self.handle_chat_photo_msg(&message, photos), 467 | DeleteChatPhoto => self.handle_delete_photo_msg(&message, message.chat.clone()), 468 | GroupChatCreated => self.handle_group_created_msg(&message, message.chat.clone()), 469 | SuperGroupChatCreated(migration) => { 470 | self.handle_super_group_chat_created_msg(&message, migration) 471 | } 472 | ChannelChatCreated => { 473 | self.handle_channel_chat_created_msg(&message, message.chat.clone()) 474 | } 475 | } 476 | } 477 | } 478 | 479 | // Add functions implementation 480 | /// Methods to add function handlers to different routes. 481 | /// 482 | /// The different parameters of the handlers are: 483 | /// 484 | /// - Common: 485 | /// - `&AwesomeBot`: First argument of all the handlers is the bot itself, so you can send/answer. 486 | /// - `&Message`: Second argument of all the handlers is the message that has triggered 487 | /// the handler, you can grab all the information you want. This struct comes 488 | /// from `telegram-bot` crate. 489 | /// - Specific to some handlers: 490 | /// - `String`: Refers to the full text if it's a command or regular expression, 491 | /// or the new title of a group. 492 | /// - `Vec`: These are only in `command` and `regex` methods, and represent a vector 493 | /// of the capture groups. 494 | /// - `Vec`: Represents an image (it's received in different sizes) and you get it 495 | /// when a photo arrives or when someone change a group photo. 496 | /// - `Video`, `Document`, `Sticker`, `Audio`, `Voice`, `GeneralSound`, `Contact`, `Float`: 497 | /// All these parameters are the media that made the handler trigger, for example, 498 | /// in `video_fn` you will receive a `Video`. 499 | /// - `User`: An User is received when a participants leave or enter a group. 500 | /// - `Chat::Group`: Whenever someone delete a chat photo, or create a group (add the bot to 501 | /// the group) you receive this. 502 | impl AwesomeBot { 503 | /// Add complex command routing (With capture groups). 504 | /// 505 | /// This method will transform the pattern to be exhaustive and include the mention to the bot, 506 | /// for example, the pattern `echo (.+)` will be used inside an the regular expression 507 | /// `^/start(?:@usernamebot)? (.+)$` 508 | pub fn command(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot 509 | where 510 | H: Fn(&AwesomeBot, &Message, String, Vec) + Send + Sync + 'static, 511 | { 512 | let nr = Self::modify_command(pattern, &self.username); 513 | match Regex::new(&*nr) { 514 | Ok(r) => add_muxer!(self, handler, Muxer::PatternMux, [r]), 515 | Err(_) => self, 516 | } 517 | } 518 | 519 | /// Add simple command routing (Without capture groups). 520 | /// 521 | /// This method will transform the pattern the same as `command` method, but the handler 522 | /// will not receive the capture groups. 523 | pub fn simple_command(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot 524 | where 525 | H: Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static, 526 | { 527 | let nr = Self::modify_command(pattern, &self.username); 528 | match Regex::new(&*nr) { 529 | Ok(r) => add_muxer!(self, handler, Muxer::TextMux, [r]), 530 | Err(_) => self, 531 | } 532 | } 533 | 534 | /// Add complex regular expression routing (With capture groups) 535 | /// 536 | /// This method won't tranform anything about the regular expression, you are free to write 537 | /// the expression you want and receive the capture groups matched. 538 | pub fn regex(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot 539 | where 540 | H: Fn(&AwesomeBot, &Message, String, Vec) + Send + Sync + 'static, 541 | { 542 | match Regex::new(pattern) { 543 | Ok(r) => add_muxer!(self, handler, Muxer::PatternMux, [r]), 544 | Err(_) => self, 545 | } 546 | } 547 | 548 | /// Add complex regular expression routing (Without capture groups) 549 | /// 550 | /// This method won't tranform anything about the regular expression, you are free to write 551 | /// the expression. The difference from `regex` is that you won't receive any capture groups. 552 | pub fn simple_regex(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot 553 | where 554 | H: Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static, 555 | { 556 | match Regex::new(pattern) { 557 | Ok(r) => add_muxer!(self, handler, Muxer::TextMux, [r]), 558 | Err(_) => self, 559 | } 560 | } 561 | 562 | // pub fn multi_regex(&mut self, patterns: Vec<&str>, handler: H) -> &mut AwesomeBot 563 | // where H: Fn(&AwesomeBot, &Message, String, Vec) + Send + Sync + 'static 564 | // { 565 | // } 566 | 567 | /// Add a routing handler that will be triggerer on every message, useful for logging. 568 | pub fn any_fn(&mut self, handler: H) -> &mut AwesomeBot 569 | where 570 | H: Fn(&AwesomeBot, &Message) + Send + Sync + 'static, 571 | { 572 | add_muxer!(self, handler, Muxer::AnyMux, []) 573 | } 574 | 575 | /// Add a photo media routing handler. 576 | pub fn photo_fn(&mut self, handler: H) -> &mut AwesomeBot 577 | where 578 | H: Fn(&AwesomeBot, &Message, Vec) + Send + Sync + 'static, 579 | { 580 | add_muxer!(self, handler, Muxer::PhotoMux, []) 581 | } 582 | 583 | /// Add a video media routing handler. 584 | pub fn video_fn(&mut self, handler: H) -> &mut AwesomeBot 585 | where 586 | H: Fn(&AwesomeBot, &Message, Video) + Send + Sync + 'static, 587 | { 588 | add_muxer!(self, handler, Muxer::VideoMux, []) 589 | } 590 | 591 | /// Add a document media routing handler. 592 | pub fn document_fn(&mut self, handler: H) -> &mut AwesomeBot 593 | where 594 | H: Fn(&AwesomeBot, &Message, Document) + Send + Sync + 'static, 595 | { 596 | add_muxer!(self, handler, Muxer::DocumentMux, []) 597 | } 598 | 599 | /// Add a sticker media routing handler. 600 | pub fn sticker_fn(&mut self, handler: H) -> &mut AwesomeBot 601 | where 602 | H: Fn(&AwesomeBot, &Message, Sticker) + Send + Sync + 'static, 603 | { 604 | add_muxer!(self, handler, Muxer::StickerMux, []) 605 | } 606 | 607 | /// Add an audio media routing handler. 608 | pub fn audio_fn(&mut self, handler: H) -> &mut AwesomeBot 609 | where 610 | H: Fn(&AwesomeBot, &Message, Audio) + Send + Sync + 'static, 611 | { 612 | add_muxer!(self, handler, Muxer::AudioMux, []) 613 | } 614 | 615 | /// Add a voice media routing handler. 616 | pub fn voice_fn(&mut self, handler: H) -> &mut AwesomeBot 617 | where 618 | H: Fn(&AwesomeBot, &Message, Voice) + Send + Sync + 'static, 619 | { 620 | add_muxer!(self, handler, Muxer::VoiceMux, []) 621 | } 622 | 623 | /// Add a routing handler that is triggered when an `Audio` or a `Voice` is received. 624 | pub fn all_music_fn(&mut self, handler: H) -> &mut AwesomeBot 625 | where 626 | H: Fn(&AwesomeBot, &Message, GeneralSound) + Send + Sync + 'static, 627 | { 628 | add_muxer!(self, handler, Muxer::GeneralAudioMux, []) 629 | } 630 | 631 | /// Add a contact routing handler. 632 | pub fn contact_fn(&mut self, handler: H) -> &mut AwesomeBot 633 | where 634 | H: Fn(&AwesomeBot, &Message, Contact) + Send + Sync + 'static, 635 | { 636 | add_muxer!(self, handler, Muxer::ContactMux, []) 637 | } 638 | 639 | /// Add a location routing handler. 640 | pub fn location_fn(&mut self, handler: H) -> &mut AwesomeBot 641 | where 642 | H: Fn(&AwesomeBot, &Message, Float, Float) + Send + Sync + 'static, 643 | { 644 | add_muxer!(self, handler, Muxer::LocationMux, []) 645 | } 646 | 647 | /// Add a routing handler that is triggered when a new participant enters a group. 648 | pub fn new_participant_fn(&mut self, handler: H) -> &mut AwesomeBot 649 | where 650 | H: Fn(&AwesomeBot, &Message, User) + Send + Sync + 'static, 651 | { 652 | add_muxer!(self, handler, Muxer::NewParticipantMux, []) 653 | } 654 | 655 | /// Add a routing handler that is triggered when a participant leaves a group. 656 | pub fn left_participant_fn(&mut self, handler: H) -> &mut AwesomeBot 657 | where 658 | H: Fn(&AwesomeBot, &Message, User) + Send + Sync + 'static, 659 | { 660 | add_muxer!(self, handler, Muxer::LeftParticipantMux, []) 661 | } 662 | 663 | /// Add a routing handler that is triggered when the title of a group chat is changed. 664 | pub fn new_title_fn(&mut self, handler: H) -> &mut AwesomeBot 665 | where 666 | H: Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static, 667 | { 668 | add_muxer!(self, handler, Muxer::NewTitleMux, []) 669 | } 670 | 671 | /// Add a routing handler that is triggered when the photo of a group chat is changed. 672 | pub fn new_chat_photo_fn(&mut self, handler: H) -> &mut AwesomeBot 673 | where 674 | H: Fn(&AwesomeBot, &Message, Vec) + Send + Sync + 'static, 675 | { 676 | add_muxer!(self, handler, Muxer::NewChatPhotoMux, []) 677 | } 678 | 679 | /// Add a routing handler that is triggered when the photo of a group chat is deleted. 680 | pub fn delete_chat_photo_fn(&mut self, handler: H) -> &mut AwesomeBot 681 | where 682 | H: Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static, 683 | { 684 | add_muxer!(self, handler, Muxer::DeleteChatPhotoMux, []) 685 | } 686 | 687 | /// Add a routing handler that is triggered when a group chat is created. 688 | pub fn group_chat_created_fn(&mut self, handler: H) -> &mut AwesomeBot 689 | where 690 | H: Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static, 691 | { 692 | add_muxer!(self, handler, Muxer::GroupChatCreatedMux, []) 693 | } 694 | 695 | /// Add a routing handler that is triggered when a super group chat is created. 696 | pub fn super_group_chat_created_fn(&mut self, handler: H) -> &mut AwesomeBot 697 | where 698 | H: Fn(&AwesomeBot, &Message, GroupToSuperGroupMigration) + Send + Sync + 'static, 699 | { 700 | add_muxer!(self, handler, Muxer::SuperGroupChatCreatedMux, []) 701 | } 702 | 703 | /// Add a routing handler that is triggered when a channel chat is created. 704 | pub fn channel_chat_created_fn(&mut self, handler: H) -> &mut AwesomeBot 705 | where 706 | H: Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static, 707 | { 708 | add_muxer!(self, handler, Muxer::ChannelChatCreatedMux, []) 709 | } 710 | } 711 | 712 | // fn detect_file_or_id(name: &str, path: String) -> SendPath { 713 | // // When PathExt becomes stable, use Path::new(&path).exists() instead of this! 714 | // let check = fs::metadata(&path); 715 | // if path.contains(".") && check.is_ok() && check.unwrap().is_file() { 716 | // SendPath::File(name.to_owned(), Path::new(&path).to_path_buf()) 717 | // } else { 718 | // SendPath::Id(name.to_owned(), path) 719 | // } 720 | // } 721 | --------------------------------------------------------------------------------