├── .github ├── FUNDING.yml └── workflows │ └── rust.yml ├── pawn-examples └── basic-bot │ ├── pawn.json │ └── main.pwn ├── src ├── encode.rs ├── callbacks.rs ├── macros.rs ├── methods.rs ├── types.rs ├── http.rs ├── lib.rs ├── plugin.rs ├── internals.rs ├── api.rs └── natives.rs ├── bintray.json ├── .gitignore ├── Cargo.toml ├── pawn.json ├── makefile ├── appveyor.yml ├── .travis.yml ├── README.md ├── include └── tgconnector.inc ├── pawn-tests └── test.pwn ├── Cargo.lock └── LICENSE /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: sreyas-sreelal 4 | -------------------------------------------------------------------------------- /pawn-examples/basic-bot/pawn.json: -------------------------------------------------------------------------------- 1 | { 2 | "user": "SyS", 3 | "repo": "basic-bot", 4 | "entry": "main.pwn", 5 | "output": "main.amx", 6 | "dependencies": [ 7 | "sampctl/samp-stdlib", 8 | "sreyas-sreelal/tgconnector", 9 | "Southclaws/zcmd" 10 | ] 11 | } -------------------------------------------------------------------------------- /src/encode.rs: -------------------------------------------------------------------------------- 1 | use encoding::all::UTF_8; 2 | use encoding::{EncoderTrap, Encoding}; 3 | use std::error; 4 | use std::str::from_utf8; 5 | 6 | pub fn encode_replace(string: &str) -> Result> { 7 | let bytes = UTF_8.encode(string, EncoderTrap::Replace)?; 8 | let data = from_utf8(&bytes)?; 9 | Ok(data.to_string()) 10 | } 11 | -------------------------------------------------------------------------------- /bintray.json: -------------------------------------------------------------------------------- 1 | { 2 | "package": { 3 | "name": "builds", 4 | "repo": "tgconnector", 5 | "subject": "sreyas-sreelal" 6 | }, 7 | "version": { 8 | "name": "latest" 9 | }, 10 | "files": [ 11 | { 12 | "includePattern": "plugins/tgconnector.so", 13 | "uploadPattern": "tgconnector.so", 14 | "matrixParams": { 15 | "override": 1 16 | } 17 | } 18 | ], 19 | "publish": true 20 | } 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # These are backup files generated by rustfmt 6 | **/*.rs.bk 7 | 8 | *amx 9 | *dll 10 | *so 11 | *zip 12 | *log 13 | 14 | */*/dependencies/ 15 | /dependencies/ 16 | /gamemodes/ 17 | /plugins/ 18 | /scriptfiles/ 19 | /filterscripts/ 20 | 21 | announce 22 | samp03svr 23 | samp-npc 24 | 25 | announce.exe 26 | samp-server.exe 27 | samp-npc.exe 28 | 29 | server.cfg 30 | server_log.txt 31 | TgConnector.sublime-workspace 32 | crashinfo.txt -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tgconnector" 3 | version = "1.1.1" 4 | authors = ["Sreyas-Sreelal"] 5 | edition = "2018" 6 | 7 | [lib] 8 | name = "tgconnector" 9 | crate-type = ["cdylib"] 10 | 11 | [profile.release] 12 | lto = true 13 | panic = "abort" 14 | 15 | [dependencies] 16 | samp = {git="https://github.com/Pycckue-Bnepeg/samp-rs/"} 17 | log = "0.4.6" 18 | fern = "0.5.7" 19 | threadpool = "1.7.1" 20 | minihttp = {git = "https://github.com/Sreyas-Sreelal/minihttp"} 21 | serde_json = "1.0.38" 22 | serde = "1.0.86" 23 | serde_derive = "1.0.86" 24 | encoding = "0.2.33" -------------------------------------------------------------------------------- /src/callbacks.rs: -------------------------------------------------------------------------------- 1 | use log::error; 2 | use samp::amx::AmxIdent; 3 | use samp::exec_public; 4 | pub fn on_tg_message( 5 | amx_list: &[AmxIdent], 6 | botid: usize, 7 | fromid: String, 8 | message_id: i32, 9 | message_thread_id: i32, 10 | ) { 11 | execute!(amx_list,"OnTGMessage",botid;&fromid => string,message_id,message_thread_id); 12 | } 13 | 14 | pub fn on_tg_send_message(amx_list: &[AmxIdent], name: &str, botid: usize, message_id: i32) { 15 | execute!(amx_list,name,botid;message_id); 16 | } 17 | 18 | pub fn on_tg_channel_post(amx_list: &[AmxIdent], botid: usize, message_id: i32) { 19 | execute!(amx_list,"OnTGChannelPost",botid;message_id); 20 | } 21 | 22 | pub fn on_tg_user_joined(amx_list: &[AmxIdent], botid: usize, userid: String) { 23 | execute!(amx_list,"OnTGUserJoined",botid;&userid => string); 24 | } 25 | 26 | pub fn on_tg_user_left(amx_list: &[AmxIdent], botid: usize, userid: String) { 27 | execute!(amx_list,"OnTGUserLeft",botid;&userid => string); 28 | } 29 | -------------------------------------------------------------------------------- /pawn.json: -------------------------------------------------------------------------------- 1 | { 2 | "user": "Sreyas-Sreelal", 3 | "repo": "tgconnector", 4 | "entry": "pawn-tests/test.pwn", 5 | "output": "gamemodes/test.amx", 6 | "dependencies": ["sampctl/pawn-stdlib"], 7 | "dev_dependencies": ["pawn-lang/YSI-Includes@5.x"], 8 | "include_path": "include", 9 | "local": true, 10 | "builds": [ 11 | { 12 | "name": "test", 13 | "includes": ["./include"] 14 | } 15 | ], 16 | "runtimes": [ 17 | { 18 | "rcon_password": "|%GuRd324$\u0026|", 19 | "port": 7777, 20 | "plugins":["../target/debug/tgconnector"], 21 | "gamemodes":["test"], 22 | "hostname": "test", 23 | "maxplayers": 32, 24 | "mode" :"y_testing" 25 | } 26 | ], 27 | "resources": [ 28 | { 29 | "name": "tgconnector-linux-x86.zip", 30 | "platform": "linux", 31 | "archive": true, 32 | "plugins": ["plugins/tgconnector.so"] 33 | }, 34 | { 35 | "name": "tgconnector-windows-x86.zip", 36 | "platform": "windows", 37 | "archive": true, 38 | "plugins": ["plugins/tgconnector.dll"] 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /makefile: -------------------------------------------------------------------------------- 1 | ifdef OS 2 | TOOLCHAIN = +stable-i686-pc-windows-msvc 3 | BINARYNAME = tgconnector.dll 4 | OUPUTNAME = tgconnector.dll 5 | CP_RELEASE = cp .\target\release\$(BINARYNAME) .\plugins\$(OUPUTNAME) 6 | CP_DEBUG = cp .\target\debug\$(BINARYNAME) .\plugins\$(OUPUTNAME) 7 | else 8 | ifeq ($(shell uname), Linux) 9 | TOOLCHAIN = +stable-i686-unknown-linux-gnu 10 | BINARYNAME = libtgconnector.so 11 | OUPUTNAME = tgconnector.so 12 | CP_RELEASE = cp target/release/$(BINARYNAME) plugins/$(OUPUTNAME) 13 | CP_DEBUG = cp target/debug/$(BINARYNAME) plugins/$(OUPUTNAME) 14 | endif 15 | endif 16 | 17 | release: 18 | cargo $(TOOLCHAIN) build --release 19 | $(CP_RELEASE) 20 | 21 | debug: 22 | cargo $(TOOLCHAIN) build 23 | $(CP_DEBUG) 24 | 25 | setup: 26 | sampctl package ensure 27 | sampctl package build 28 | 29 | ensure: 30 | sampctl package ensure 31 | 32 | run: 33 | sampctl package build 34 | sampctl package run 35 | 36 | clean: 37 | cargo clean 38 | 39 | dev: 40 | cargo $(TOOLCHAIN) build 41 | sampctl package build 42 | sampctl package run -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - TARGET: i686-pc-windows-msvc 4 | CHANNEL: stable 5 | 6 | install: 7 | - curl -sSf -o rustup-init.exe https://win.rustup.rs 8 | - rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y 9 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 10 | - rustc -Vv 11 | - cargo -V 12 | - ps: iex (new-object net.webclient).downloadstring('https://get.scoop.sh') 13 | - scoop bucket add southclaws https://github.com/Southclaws/scoops.git 14 | - scoop install sampctl 15 | - appveyor-retry choco install make 16 | matrix: 17 | fast_finish: true 18 | 19 | before_build: 20 | - make setup 21 | 22 | build_script: 23 | - make release 24 | 25 | test_script: 26 | - make run 27 | 28 | artifacts: 29 | - path: plugins/tgconnector.dll 30 | name: tgconnector 31 | 32 | deploy: 33 | - provider: BinTray 34 | username: Sreyas-Sreelal 35 | api_key: 36 | secure: avSVuY8Q8nSYesj3ce2v8cM6+aTSivkTzGozcCBMpJr+I0Td73+fVHTp6dAHcGw6 37 | subject: sreyas-sreelal 38 | repo: tgconnector 39 | package: builds 40 | publish: true 41 | version: latest 42 | override: true -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! execute { 2 | ($amx_list:ident,$name:tt,$botid:ident;$($args:tt)*) => { 3 | let mut executed: bool = false; 4 | for amx in $amx_list { 5 | if let Some(amx) = samp::amx::get(*amx) { 6 | let botid: usize = $botid; 7 | let _= exec_public!(amx,$name,botid,$($args)*); 8 | executed = true; 9 | } 10 | } 11 | if !executed { 12 | error!("**[TGConnector] Error executing callback {}",$name); 13 | } 14 | }; 15 | } 16 | 17 | macro_rules! cache_get { 18 | ($cache_list:ident,$dest:ident,$size:ident) => { 19 | if $cache_list.front() != None { 20 | match encode_replace(&$cache_list.front().unwrap()) { 21 | Ok(encoded) => { 22 | let mut dest = $dest.into_sized_buffer($size); 23 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 24 | Ok(1) 25 | } 26 | Err(err) => { 27 | error!( 28 | "**[TGConnector] Failed encoding {:?} \n {:?}", 29 | $cache_list.front().unwrap(), 30 | err 31 | ); 32 | Ok(0) 33 | } 34 | } 35 | } else { 36 | Ok(0) 37 | } 38 | }; 39 | } 40 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: cargo 3 | dist: trusty 4 | matrix: 5 | fast_finish: true 6 | include: 7 | - rust: stable-i686 8 | os: linux 9 | addons: 10 | apt: 11 | packages: 12 | - gcc-multilib 13 | - libssl-dev:i386 14 | - g++-multilib 15 | - apt-transport-https 16 | before_install: 17 | - cd $HOME && curl -Ls https://github.com/Southclaws/sampctl/releases/download/1.8.38/sampctl_1.8.38_linux_amd64.tar.gz 18 | -o ./bin/tmp.tar.gz 19 | - cd bin && tar xzf tmp.tar.gz && rm tmp.tar.gz 20 | - alias sampctl=$HOME/bin/sampctl 21 | - cd $HOME/build/Sreyas-Sreelal/tgconnector 22 | script: 23 | - make setup 24 | - make release 25 | - make run 26 | deploy: 27 | on: 28 | all_branches: true 29 | provider: bintray 30 | file: bintray.json 31 | user: Sreyas-Sreelal 32 | key: 33 | secure: MPt5AkV7odW/9i4gUG+Alr7Bgerhz6MWGRKWge8XF+r62ykosUzdSSuOalOapBzO5CkN5OzwMEyij8qsfbkXMBM1IR4d8Px8zicL1y5VyiEDrFK6WWAldvQCF+kAFuATxavXjKh5BEUV+eKD3p/4kt64+JzOsCAON3qHue0yse1ofzpb8Eqe9EccwiLSelEU+iOgZYce4KEXZahW/sVbq7YduySkMja8vq/UqygKXn55yJtJPge6vd02kHyokqcRRYfQU6xIMoiBCjuKoKKj/K1CR5VXdgcHSdzu7v92jKDi3/goaXBZQX9/JcbZ15Cm1zl+J6kJLQ+jS8gRJ+W47hlKH2F5w/fXLsWbB6nzGwxgdN+OVwynWduCpB8B2ci8OBZt97mgRGU9eYP+ApU82vGrtDxiad/nmXZqqqXLI5W3rVJDxqxdlSI8mnk5eKLuMAo95UqdU8LPC+RK37x2XZtGu+deipAN5lhrnrdqqhLZTNg55ol2BKUex9PwgCrgj4xr320k556+DSBjjD8whq63fZgnK+/jswud+4qV3VQd+whf2rClrnhu9c8DfYVyRwAv/f8OM4GXW8/wj7bkfZ8ERVwwwKJes2PlrQlJKNMoH4L6u33kok2TTW36J6vepOJCJEmUaGjR9EhVqJfD9/y/yV/CmqZxql3AOq8ZzZo= 34 | skip_cleanup: true 35 | -------------------------------------------------------------------------------- /src/methods.rs: -------------------------------------------------------------------------------- 1 | use serde_derive::Serialize; 2 | 3 | #[derive(Serialize, Debug, Clone)] 4 | pub struct GetUpdates { 5 | pub offset: i32, 6 | } 7 | 8 | #[derive(Serialize, Debug, Clone)] 9 | pub struct SendMessage { 10 | pub chat_id: String, 11 | pub text: String, 12 | pub reply_to_message_id: Option, 13 | #[serde(skip_serializing_if = "Option::is_none")] 14 | pub parse_mode: Option<&'static str>, 15 | pub disable_web_page_preview: bool, 16 | } 17 | 18 | #[derive(Serialize, Debug, Clone)] 19 | pub struct DeleteMessage { 20 | pub chat_id: String, 21 | pub message_id: i32, 22 | } 23 | 24 | #[derive(Serialize, Debug, Clone)] 25 | pub struct EditMessageText { 26 | pub chat_id: String, 27 | pub message_id: i32, 28 | pub text: String, 29 | #[serde(skip_serializing_if = "Option::is_none")] 30 | pub parse_mode: Option<&'static str>, 31 | } 32 | 33 | #[derive(Serialize, Debug, Clone)] 34 | pub struct GetChat { 35 | pub chat_id: String, 36 | } 37 | 38 | #[derive(Serialize, Debug, Clone)] 39 | pub struct GetChatMember { 40 | pub chat_id: String, 41 | pub user_id: String, 42 | } 43 | 44 | #[derive(Serialize, Debug, Clone)] 45 | pub struct GetChatMembersCount { 46 | pub chat_id: String, 47 | } 48 | 49 | #[derive(Serialize, Debug, Clone)] 50 | pub struct BanChatMember { 51 | pub chat_id: String, 52 | pub user_id: String, 53 | pub until_date: Option, 54 | pub revoke_messages: bool, 55 | } 56 | 57 | #[derive(Serialize, Debug, Clone)] 58 | pub struct UnbanChatMember { 59 | pub chat_id: String, 60 | pub user_id: String, 61 | pub only_if_banned: bool, 62 | } 63 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Deserializer}; 2 | use serde_derive::Deserialize; 3 | use std::collections::VecDeque; 4 | 5 | pub enum UpdateType { 6 | Message, 7 | ChannelPost, 8 | UserJoined, 9 | UserLeft, 10 | UnknownUpdate, 11 | } 12 | 13 | #[derive(Deserialize, Debug, Clone)] 14 | pub struct APIResponse { 15 | pub ok: bool, 16 | #[serde(rename = "result")] 17 | pub body: Option, 18 | pub description: Option, 19 | } 20 | 21 | #[derive(Deserialize, Debug, Clone)] 22 | pub struct Update { 23 | pub message: Option, 24 | pub channel_post: Option, 25 | pub update_id: i32, 26 | } 27 | 28 | #[derive(Deserialize, Debug, Clone)] 29 | pub struct Message { 30 | pub text: Option, 31 | pub from: Option, 32 | pub chat: Chat, 33 | pub message_id: i32, 34 | pub new_chat_members: Option>, 35 | pub left_chat_member: Option, 36 | pub message_thread_id: Option, 37 | } 38 | 39 | #[derive(Deserialize, Debug, Clone)] 40 | pub struct User { 41 | #[serde(deserialize_with = "de_from_int")] 42 | pub id: String, 43 | pub first_name: String, 44 | pub last_name: Option, 45 | pub username: Option, 46 | } 47 | 48 | #[derive(Deserialize, Debug, Clone)] 49 | pub struct Chat { 50 | #[serde(deserialize_with = "de_from_int")] 51 | pub id: String, 52 | #[serde(rename = "type")] 53 | pub chat_type: String, 54 | pub title: Option, 55 | pub description: Option, 56 | } 57 | 58 | #[derive(Deserialize, Debug, Clone)] 59 | pub struct ChatMember { 60 | pub user: User, 61 | pub status: String, 62 | } 63 | 64 | fn de_from_int<'de, D>(deserializer: D) -> Result 65 | where 66 | D: Deserializer<'de>, 67 | { 68 | let integer = i64::deserialize(deserializer)?; 69 | Ok(integer.to_string()) 70 | } 71 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Build 3 | 4 | on: 5 | push: 6 | branches: [ master ] 7 | pull_request: 8 | branches: [ master ] 9 | 10 | env: 11 | RELEASE_BIN: tgconnector 12 | RELEASE_ADDS: README.md LICENSE 13 | 14 | jobs: 15 | build: 16 | name: Build release 17 | 18 | runs-on: ${{ matrix.os }} 19 | strategy: 20 | matrix: 21 | build: [linux, windows] 22 | include: 23 | - build: linux 24 | os: ubuntu-20.04 25 | rust: stable-i686 26 | - build: windows 27 | os: windows-latest 28 | rust: stable-i686 29 | 30 | steps: 31 | - uses: actions/checkout@v1 32 | 33 | - name: Install dependencies 34 | run: | 35 | sudo dpkg --add-architecture i386 36 | sudo apt update 37 | sudo apt install gcc-multilib libssl-dev:i386 -y 38 | if: matrix.os == 'ubuntu-20.04' 39 | 40 | - name: Install Rust (rustup) 41 | run: rustup update ${{ matrix.rust }} --no-self-update && rustup default ${{ matrix.rust }} 42 | shell: bash 43 | 44 | - name: Build 45 | run: cargo build --verbose --release 46 | 47 | - name: Create artifact directory 48 | run: mkdir artifacts 49 | 50 | - name: Create archive for Linux 51 | run: 7z a -ttar -so -an ./target/release/lib${{ env.RELEASE_BIN }}.so ${{ env.RELEASE_ADDS }} | 7z a -si ./artifacts/${{ env.RELEASE_BIN }}-linux-x86.tar.gz 52 | if: matrix.os == 'ubuntu-20.04' 53 | 54 | - name: Create archive for Windows 55 | run: 7z a -tzip ./artifacts/${{ env.RELEASE_BIN }}-windows-x86.zip ./target/release/${{ env.RELEASE_BIN }}.dll ${{ env.RELEASE_ADDS }} 56 | if: matrix.os == 'windows-latest' 57 | 58 | - uses: actions/upload-artifact@v1 59 | name: Upload archive 60 | with: 61 | name: ${{ runner.os }} 62 | path: artifacts/ 63 | 64 | 65 | -------------------------------------------------------------------------------- /pawn-examples/basic-bot/main.pwn: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define CHAT_ID (TGChatId:"-1001445898764") 6 | 7 | new TGBot:g_bot; 8 | 9 | main() { 10 | g_bot = TG_ConnectFromEnv("SAMP_TG_BOT"); 11 | if(g_bot != INVALID_BOT_ID) { 12 | printf("bot connected successfully!"); 13 | } else { 14 | printf("Error: bot couldn't connect"); 15 | } 16 | } 17 | 18 | public OnTGMessage(TGBot:bot,TGUser:fromid[],TGMessage:messageid) { 19 | 20 | if(g_bot != bot){ 21 | return 1; 22 | } 23 | 24 | new 25 | message[50], 26 | username[24], 27 | chatname[56], 28 | server_msg[128]; 29 | 30 | TG_CacheGetMessage(message); 31 | TG_CacheGetUserName(username); 32 | TG_CacheGetChatName(chatname); 33 | 34 | format(server_msg,128,"[%s] %s(%s): %s",chatname,username,_:fromid,message); 35 | print(server_msg); 36 | SendClientMessageToAll(-1,server_msg); 37 | 38 | return 1; 39 | } 40 | 41 | 42 | public OnTGUserJoined(TGBot:bot,TGUser:userid[]) { 43 | new 44 | TGChatId:chatid[12], 45 | username[24], 46 | chatname[56], 47 | server_msg[128]; 48 | 49 | TG_CacheGetUserName(username); 50 | TG_CacheGetChatId(chatid); 51 | TG_CacheGetChatName(chatname); 52 | 53 | format(server_msg,128,"User %s(%s) joined %s(%s)",username,_:userid,chatname,_:chatid); 54 | print(server_msg); 55 | SendClientMessageToAll(-1,server_msg); 56 | return 1; 57 | } 58 | 59 | public OnTGUserLeft(TGBot:bot,TGUser:userid) { 60 | new 61 | TGChatId:chatid[12], 62 | username[24], 63 | chatname[56], 64 | server_msg[128]; 65 | 66 | TG_CacheGetUserName(username); 67 | TG_CacheGetChatId(chatid); 68 | TG_CacheGetChatName(chatname); 69 | 70 | format(server_msg,128,"User %s(%s) left %s(%s)",username,_:userid,chatname,_:chatid); 71 | print(server_msg); 72 | SendClientMessageToAll(-1,server_msg); 73 | return 1; 74 | } 75 | 76 | CMD:sendtgmessage(playerid,params[]) { 77 | TG_SendMessage(g_bot,CHAT_ID,params); 78 | return 1; 79 | } -------------------------------------------------------------------------------- /src/http.rs: -------------------------------------------------------------------------------- 1 | use minihttp::request::Request; 2 | use std::collections::HashMap; 3 | 4 | pub enum HttpMethod { 5 | Get, 6 | Post, 7 | } 8 | 9 | pub struct HttpRequest { 10 | pub url: String, 11 | pub method: HttpMethod, 12 | pub body: Option, 13 | pub proxy_url: Option, 14 | } 15 | 16 | impl HttpRequest { 17 | pub fn make_request(&self) -> Result { 18 | let mut requests_obj = match Request::new(&self.url) { 19 | Ok(requests_obj) => requests_obj, 20 | 21 | Err(err) => { 22 | return Err(format!("Error building request to telegram api\n{:?}", err)); 23 | } 24 | }; 25 | let method = match self.method { 26 | HttpMethod::Get => { 27 | if let Some(proxy_url) = &self.proxy_url { 28 | match requests_obj.proxy(proxy_url) { 29 | Ok(method) => method.get(), 30 | Err(err) => { 31 | return Err(format!("Error connecting to proxy server \n{:?}", err)); 32 | } 33 | } 34 | } else { 35 | requests_obj.get() 36 | } 37 | } 38 | 39 | HttpMethod::Post => { 40 | let body = &self.body.clone().unwrap(); 41 | requests_obj.body_str(body); 42 | let mut headers = HashMap::new(); 43 | headers.insert("Content-Type".to_string(), "application/json".to_string()); 44 | requests_obj.headers(headers); 45 | if let Some(proxy_url) = &self.proxy_url { 46 | match requests_obj.proxy(proxy_url) { 47 | Ok(method) => method.post(), 48 | Err(err) => { 49 | return Err(format!("Error connecting to proxy server \n{:?}", err)); 50 | } 51 | } 52 | } else { 53 | requests_obj.post() 54 | } 55 | } 56 | }; 57 | match method.send() { 58 | Ok(data) => Ok(data.text()), 59 | 60 | Err(err) => Err(format!("Error sending request to telegram api\n{:?}", err)), 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | mod macros; 3 | mod api; 4 | mod callbacks; 5 | mod encode; 6 | mod http; 7 | mod internals; 8 | mod methods; 9 | mod natives; 10 | mod plugin; 11 | mod types; 12 | 13 | use crate::plugin::TgConnector; 14 | use samp::initialize_plugin; 15 | 16 | use std::collections::{HashMap, LinkedList}; 17 | initialize_plugin!( 18 | natives: [ 19 | TgConnector::bot_connect, 20 | TgConnector::bot_connect_from_env, 21 | TgConnector::bot_send_message, 22 | TgConnector::bot_delete_message, 23 | TgConnector::bot_edit_message, 24 | TgConnector::get_bot_user_id, 25 | TgConnector::cache_get_message, 26 | TgConnector::cache_get_username, 27 | TgConnector::cache_get_user_first_name, 28 | TgConnector::cache_get_user_last_name, 29 | TgConnector::cache_get_chatid, 30 | TgConnector::cache_get_chatname, 31 | TgConnector::cache_get_chattype, 32 | TgConnector::get_user_status, 33 | TgConnector::get_username_from_id, 34 | TgConnector::get_display_name_from_id, 35 | TgConnector::get_chat_members_count, 36 | TgConnector::get_chat_title, 37 | TgConnector::get_chat_description, 38 | TgConnector::ban_chat_member, 39 | TgConnector::unban_chat_member, 40 | TgConnector::get_bot_user_id_old, 41 | TgConnector::get_user_status_old, 42 | TgConnector::get_username_from_id_old, 43 | TgConnector::get_display_name_from_id_old 44 | ], 45 | { 46 | samp::plugin::enable_process_tick(); 47 | let samp_logger = samp::plugin::logger() 48 | .level(log::LevelFilter::Info); 49 | 50 | let _ = fern::Dispatch::new() 51 | .format(|callback, message, record| { 52 | callback.finish(format_args!("[TgConnector] [{}]: {}", record.level().to_string().to_lowercase(), message)) 53 | }) 54 | .chain(samp_logger) 55 | .apply(); 56 | 57 | TgConnector { 58 | plugin_version: 111, 59 | amx_list: Vec::new(), 60 | bots: HashMap::new(), 61 | bot_context_id: 0, 62 | telegram_messages: LinkedList::new(), 63 | telegram_username: LinkedList::new(), 64 | telegram_chatname: LinkedList::new(), 65 | telegram_chatid: LinkedList::new(), 66 | telegram_firstname: LinkedList::new(), 67 | telegram_lastname: LinkedList::new(), 68 | telegram_chattype: LinkedList::new(), 69 | } 70 | } 71 | ); 72 | -------------------------------------------------------------------------------- /src/plugin.rs: -------------------------------------------------------------------------------- 1 | use crate::api::Bot; 2 | use crate::internals; 3 | use log::{error, info}; 4 | use samp::amx::AmxIdent; 5 | use samp::prelude::*; 6 | use std::collections::{HashMap, LinkedList}; 7 | 8 | pub struct TgConnector { 9 | pub plugin_version: i32, 10 | pub amx_list: Vec, 11 | pub bots: HashMap, 12 | pub bot_context_id: usize, 13 | pub telegram_messages: LinkedList, 14 | pub telegram_username: LinkedList, 15 | pub telegram_firstname: LinkedList, 16 | pub telegram_lastname: LinkedList, 17 | pub telegram_chatname: LinkedList, 18 | pub telegram_chatid: LinkedList, 19 | pub telegram_chattype: LinkedList, 20 | } 21 | 22 | impl SampPlugin for TgConnector { 23 | fn on_load(&mut self) { 24 | info!( 25 | " 26 | ############################################################### 27 | # TGConnector # 28 | # v1.1.1 # 29 | # Found any bugs? Report it here: # 30 | # https://github.com/Sreyas-Sreelal/tgconnector/issues # 31 | # # 32 | ############################################################### 33 | " 34 | ); 35 | } 36 | 37 | fn on_unload(self: &mut TgConnector) { 38 | info!("**TGConnector v1.1.1!"); 39 | } 40 | 41 | fn on_amx_load(&mut self, amx: &Amx) { 42 | self.amx_list.push(amx.ident()); 43 | 44 | let get_version = amx.find_pubvar::("_tgconnector_version"); 45 | 46 | match get_version { 47 | Ok(version) => { 48 | if *version != self.plugin_version { 49 | info!("Warning plugin and include version doesnot match : Include {:?} Plugin {:?}",*version,self.plugin_version); 50 | } 51 | } 52 | Err(err) => error!("Failed to retrive include version Reason:{:?}", err), 53 | } 54 | } 55 | 56 | fn on_amx_unload(&mut self, amx: &Amx) { 57 | let raw = amx.ident(); 58 | let index = self.amx_list.iter().position(|x| *x == raw).unwrap(); 59 | self.amx_list.remove(index); 60 | } 61 | 62 | fn process_tick(&mut self) { 63 | internals::update_process(self); 64 | internals::on_send_message_process(self); 65 | 66 | internals::clear_caches(&mut self.telegram_chatname); 67 | internals::clear_caches(&mut self.telegram_messages); 68 | internals::clear_caches(&mut self.telegram_username); 69 | internals::clear_caches(&mut self.telegram_firstname); 70 | internals::clear_caches(&mut self.telegram_lastname); 71 | internals::clear_caches(&mut self.telegram_chattype); 72 | internals::clear_caches(&mut self.telegram_chatid); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TgConnector 2 | [![Build Status](https://travis-ci.org/Sreyas-Sreelal/tgconnector.svg?branch=master)](https://travis-ci.org/Sreyas-Sreelal/tgconnector) [![Build status](https://ci.appveyor.com/api/projects/status/snip8i9cd6xh2x1u?svg=true)](https://ci.appveyor.com/project/Sreyas-Sreelal/tgconnector) 3 | [![sampctl-supported](https://shields.southcla.ws/badge/sampctl-TGConnector-2f2f2f.svg)](https://github.com/Sreyas-Sreelal/tgconnector) 4 | [![GitHub issues](https://img.shields.io/github/issues/Sreyas-Sreelal/tgconnector.svg)](https://github.com/Sreyas-Sreelal/tgconnector/issues) [![GitHub pull requests](https://img.shields.io/github/issues-pr-raw/sreyas-sreelal/tgconnector.svg)](https://github.com/Sreyas-Sreelal/tgconnector/pulls) [![GitHub pull license](https://img.shields.io/github/license/sreyas-sreelal/tgconnector.svg)](LICENSE) 5 | 6 | A telegram connector plugin that helps to interact with telgram bots through SA-MP. 7 | ## Installing 8 | 9 | If you are a sampctl user 10 | 11 | `sampctl p install Sreyas-Sreelal/tgconnector` 12 | 13 | #### OR 14 | * Download suitable binary files from releases for your operating system 15 | * Add it your `plugins` folder 16 | * Add `tgconnector` to server.cfg or `tgconnector.so` (for linux) 17 | * Add [tgconnector.inc](include/tgconnector.inc) in includes folder 18 | 19 | ## Building 20 | * Clone the repo 21 | 22 | `git clone https://github.com/Sreyas-Sreelal/tgconnector.git` 23 | 24 | * Use makefile to compile and test 25 | * Setup testing environment 26 | 27 | `make setup` 28 | * To build release version 29 | 30 | `make release` 31 | * Run tests 32 | 33 | `make run` 34 | 35 | ## API 36 | 37 | Checkout the [Wiki](https://github.com/Sreyas-Sreelal/tgconnector/wiki) 38 | 39 | ## Example 40 | **A basic bot** 41 | ```Pawn 42 | #include 43 | #include 44 | #include 45 | 46 | #define CHAT_ID (TGChatId:"YOUR_CHAT_ID_HERE") 47 | 48 | new TGBot:g_bot; 49 | 50 | main() { 51 | //Store bot token in SAMP_TG_BOT environment variable and connect from it 52 | g_bot = TG_ConnectFromEnv("SAMP_TG_BOT"); 53 | if(g_bot != INVALID_BOT_ID) { 54 | printf("bot connected successfully!"); 55 | } else { 56 | printf("Error: bot couldn't connect"); 57 | } 58 | } 59 | 60 | public OnTGMessage(TGBot:bot,TGUser:fromid[],TGMessage:messageid) { 61 | 62 | if(g_bot != bot){ 63 | return 1; 64 | } 65 | 66 | new 67 | message[50], 68 | username[24], 69 | chatname[56], 70 | server_msg[128]; 71 | 72 | TG_CacheGetMessage(message); 73 | TG_CacheGetUserName(username); 74 | TG_CacheGetChatName(chatname); 75 | 76 | format(server_msg,128,"[%s] %s(%s): %s",chatname,username,_:fromid,message); 77 | SendClientMessageToAll(-1,server_msg); 78 | 79 | return 1; 80 | } 81 | 82 | 83 | public OnTGUserJoined(TGBot:bot,TGUser:userid[]) { 84 | new 85 | TGChatId:chatid[12], 86 | username[24], 87 | chatname[56], 88 | server_msg[128]; 89 | 90 | TG_CacheGetUserName(username); 91 | TG_CacheGetChatId(chatid); 92 | TG_CacheGetChatName(chatname); 93 | 94 | format(server_msg,128,"User %s(%d) joined %s(%s)",username,_:userid,chatname,_:chatid); 95 | SendClientMessageToAll(-1,server_msg); 96 | return 1; 97 | } 98 | 99 | public OnTGUserLeft(TGBot:bot,TGUser:userid[]) { 100 | new 101 | TGChatId:chatid[12], 102 | username[24], 103 | chatname[56], 104 | server_msg[128]; 105 | 106 | TG_CacheGetUserName(username); 107 | TG_CacheGetChatID(chatid); 108 | TG_CacheGetChatName(chatname); 109 | 110 | format(server_msg,128,"User %s(%s) left %s(%s)",username,_:userid,chatname,_:chatid); 111 | SendClientMessageToAll(-1,server_msg); 112 | return 1; 113 | } 114 | 115 | CMD:sendtgmessage(playerid,params[]) { 116 | TG_SendMessage(g_bot,CHAT_ID,params); 117 | return 1; 118 | } 119 | ``` -------------------------------------------------------------------------------- /include/tgconnector.inc: -------------------------------------------------------------------------------- 1 | #if defined _inc_tgconnector 2 | #undef _inc_tgconnector 3 | #endif 4 | 5 | #if defined _tgconnector_included 6 | #endinput 7 | #endif 8 | #define _tgconnector_included 9 | 10 | #define TGCONNECTOR_VERSION 111 11 | #define INVALID_MESSAGE_ID (TGMessage:-1) 12 | #define INVALID_BOT_ID (TGBot:-1) 13 | #define INVALID_TOPIC_ID (TGTopic:-1) 14 | 15 | public _tgconnector_version = TGCONNECTOR_VERSION; 16 | #pragma unused _tgconnector_version 17 | 18 | enum TGParseMode { 19 | HTML, 20 | MARKDOWN, 21 | MARKDOWN2 22 | }; 23 | 24 | enum TGUserStatus { 25 | TG_CREATOR = 1, 26 | TG_ADMINISTRATOR, 27 | TG_MEMBER, 28 | TG_RESTRICTED, 29 | TG_LEFT, 30 | TG_KICKED, 31 | }; 32 | 33 | // old aliases 34 | native TGBot:TGConnect(const token[],const proxy[]="",thread_limit=3)=TG_Connect; 35 | native TGBot:TGConnectFromEnv(const variable[],const proxy[]="",thread_limit=3)=TG_ConnectFromEnv; 36 | native TGSendMessage(TGBot:bot,const TGChatId:chatid[],const text[],TGMessage:reply_id=INVALID_MESSAGE_ID,TGParseMode:parse_mode=TGParseMode:-1,bool:disable_web_page_preview=false,const callback[]="") = TG_SendMessage; 37 | native TGDeleteMessage(TGBot:bot,TGChatId:chatid[],TGMessage:messageid)=TG_DeleteMessage; 38 | native TGEditMessage(TGBot:bot,const TGChatId:chatid[],const TGMessage:messageid,const text[],TGParseMode:parse_mode=TGParseMode:-1)=TG_EditMessage; 39 | native TGGetChatMembersCount(TGBot:bot,const TGChatId:chatid[])=TG_GetChatMembersCount; 40 | native TGGetChatTitle(TGBot:bot,const TGChatId:chatid[],title[],size=sizeof(title)) = TG_GetChatTitle; 41 | native TGGetChatDescription(TGBot:bot,const TGChatId:chatid[],description[],size=sizeof(description)) = TG_GetChatDescription; 42 | native TGCacheGetUserFirstName(str[],size=sizeof(str)) = TG_CacheGetUserFirstName; 43 | native TGCacheGetUserLastName(str[],size=sizeof(str)) = TG_CacheGetUserLastName; 44 | native TGCacheGetUserName(str[],size=sizeof(str)) = TG_CacheGetUserName; 45 | native TGCacheGetChatName(str[],size=sizeof(str)) = TG_CacheGetChatName; 46 | native TGCacheGetChatType(str[],size=sizeof(str)) = TG_CacheGetChatType; 47 | native TGCacheGetChatId(TGChatId:str[],size=sizeof(str)) = TG_CacheGetChatID; 48 | native TGCacheGetMessage(str[],size=sizeof(str)) = TG_CacheGetMessage; 49 | 50 | //basic 51 | native TGBot:TG_Connect(const token[],const proxy[]="",thread_limit=3); 52 | native TGBot:TG_ConnectFromEnv(const variable[],const proxy[]="",thread_limit=3); 53 | native TG_SendMessage(TGBot:bot,const TGChatId:chatid[],const text[],TGMessage:reply_id=INVALID_MESSAGE_ID,TGParseMode:parse_mode=TGParseMode:-1,bool:disable_web_page_preview=false,const callback[]=""); 54 | native TG_DeleteMessage(TGBot:bot,TGChatId:chatid[],TGMessage:messageid); 55 | native TG_EditMessage(TGBot:bot,const TGChatId:chatid[],const TGMessage:messageid,const text[],TGParseMode:parse_mode=TGParseMode:-1); 56 | native TG_BanChatMember(TGBot:bot,const TGChatId:chatid[],const TGUser:userid[],until_date=-1,bool:revoke_messages=true); 57 | native TG_UnbanChatMember(TGBot:bot,const TGChatId:chatid[],const TGUser:userid[],only_if_banned=false); 58 | 59 | //bot 60 | native TGUser:TG_GetBotUserID(TGBot:bot,TGUser:userid[],size = sizeof(userid)); 61 | 62 | //user 63 | native TGUserStatus:TG_GetUserChatStatus(TGBot:bot,const TGUser:userid[],const TGChatId:chatid[]); 64 | native TG_GetUserNameFromID(TGBot:bot,const TGUser:userid[],const TGChatId:chatid[],username[],size=sizeof(username)); 65 | native TG_GetDisplayNameFromID(TGBot:bot,const TGUser:userid[],const TGChatId:chatid[],displayname[],size=sizeof(displayname)); 66 | 67 | //chat 68 | native TG_GetChatMembersCount(TGBot:bot,const TGChatId:chatid[]); 69 | native TG_GetChatTitle(TGBot:bot,const TGChatId:chatid[],title[],size=sizeof(title)); 70 | native TG_GetChatDescription(TGBot:bot,const TGChatId:chatid[],description[],size=sizeof(description)); 71 | 72 | //cache functions 73 | native TG_CacheGetUserFirstName(str[],size=sizeof(str)); 74 | native TG_CacheGetUserLastName(str[],size=sizeof(str)); 75 | native TG_CacheGetUserName(str[],size=sizeof(str)); 76 | native TG_CacheGetChatName(str[],size=sizeof(str)); 77 | native TG_CacheGetChatType(str[],size=sizeof(str)); 78 | native TG_CacheGetChatID(TGChatId:str[],size=sizeof(str)); 79 | native TG_CacheGetMessage(str[],size=sizeof(str)); 80 | 81 | //callbacks 82 | forward OnTGMessage(TGBot:bot,TGUser:fromid[],TGMessage:messageid,TGTopic:messagethreadid); 83 | forward OnTGChannelPost(TGBot:bot,TGMessage:postid); 84 | forward OnTGUserJoined(TGBot:bot,TGUser:userid[]); 85 | forward OnTGUserLeft(TGBot:bot,TGUser:userid[]); -------------------------------------------------------------------------------- /pawn-tests/test.pwn: -------------------------------------------------------------------------------- 1 | #define RUN_TESTS 2 | 3 | #include 4 | #include 5 | 6 | #include "../include/tgconnector.inc" 7 | 8 | new TGBot:g_bot; 9 | 10 | main() { 11 | g_bot = TG_ConnectFromEnv("SAMP_TG_BOT"); 12 | } 13 | 14 | Test:TestInvalidToken() { 15 | new TGBot:invalidbot = TG_Connect(""); 16 | ASSERT(invalidbot == INVALID_BOT_ID); 17 | } 18 | 19 | Test:TestValidToken() { 20 | printf("id is %d",_:g_bot); 21 | TG_SendMessage(g_bot,TGChatId:"@testtgconnector","`markdown text` ***bold*** _italic_ 123",.parse_mode=MARKDOWN,.callback="SendingMessage"); 22 | TG_SendMessage(g_bot,TGChatId:"@testtgconnector","__underline__",.parse_mode=MARKDOWN2); 23 | 24 | ASSERT(g_bot != INVALID_BOT_ID); 25 | } 26 | Test:TG_GetBotUserID() { 27 | new 28 | TGUser:userid[64], 29 | name[34], 30 | username[32]; 31 | TG_GetBotUserID(g_bot,userid); 32 | TG_GetDisplayNameFromID(g_bot,userid,TGChatId:"562896556",name); 33 | new bool:name_check = !strcmp("samp",name); 34 | ASSERT(name_check); 35 | 36 | TG_GetUserNameFromID(g_bot,userid,TGChatId:"562896556",username); 37 | new bool:username_check = !strcmp("samptg_bot",username); 38 | ASSERT(username_check); 39 | 40 | new TGUserStatus:status = TG_GetUserChatStatus(g_bot,userid,TGChatId:"562896556"); 41 | ASSERT(status == TG_MEMBER); 42 | 43 | } 44 | 45 | Test:TG_GetUserChatStatus() { 46 | new TGUserStatus:status = TG_GetUserChatStatus(g_bot,TGUser:"562896556",TGChatId:"-1001961091419"); 47 | ASSERT(status == TG_CREATOR); 48 | } 49 | 50 | Test:TG_GetChatMembersCount() { 51 | new count = TG_GetChatMembersCount(g_bot,TGChatId:"-1001961091419"); 52 | printf("count %d",count); 53 | ASSERT(count == 2); 54 | } 55 | 56 | Test:TG_GetUserNameFromId() { 57 | new username[32]; 58 | TG_GetUserNameFromID(g_bot,TGUser:"562896556",TGChatId:"562896556",username); 59 | new check = !strcmp("SyS54",username) && username[0] != '\0'; 60 | ASSERT(check == 1); 61 | } 62 | 63 | Test:TG_GetDisplayNameFromId() { 64 | new displayname[32]; 65 | TG_GetDisplayNameFromID(g_bot,TGUser:"562896556",TGChatId:"562896556",displayname); 66 | new check = !strcmp("Crow's Eye",displayname) && displayname[0] != '\0'; 67 | ASSERT(check == 1); 68 | } 69 | 70 | Test:TG_GetChatTitle() { 71 | new title[132]; 72 | TG_GetChatTitle(g_bot,TGChatId:"-1001961091419",title); 73 | printf("title : %s",title); 74 | new check = !strcmp("bot_developement",title) && title[0] != '\0'; 75 | ASSERT(check == 1); 76 | } 77 | 78 | Test:TG_GetChatDescription() { 79 | new description[132]; 80 | TG_GetChatDescription(g_bot,TGChatId:"-1001961091419",description); 81 | printf("description : %s",description); 82 | new check = !strcmp("testing bots",description) && description[0] != '\0'; 83 | ASSERT(check == 1); 84 | } 85 | 86 | public OnTGMessage(TGBot:bot,TGUser:fromid[],TGMessage:messageid) { 87 | new 88 | TGChatId:chatid[15], 89 | message[128], 90 | chattype[15], 91 | username[24], 92 | chatname[56], 93 | firstname[34], 94 | lastname[34]; 95 | 96 | TG_CacheGetChatID(chatid); 97 | TG_CacheGetMessage(message); 98 | TG_CacheGetUserName(username); 99 | TG_CacheGetChatName(chatname); 100 | TG_CacheGetChatType(chattype); 101 | TG_CacheGetUserLastName(lastname); 102 | TG_CacheGetUserFirstName(firstname); 103 | 104 | printf("chattid: %s chatname:%s chattype:%s",_:chatid,chatname,chattype); 105 | printf("userid:%d username:%s firstname:%s lastname:%s message:%s messageid:%d\n",_:fromid,username,firstname,lastname,message,_:messageid); 106 | 107 | TG_DeleteMessage(bot,chatid,messageid); 108 | TG_SendMessage(bot,chatid,message,.callback="SendingMessage"); 109 | return 1; 110 | } 111 | 112 | forward SendingMessage(TGBot:bot,TGMessage:messageid); 113 | public SendingMessage(TGBot:bot,TGMessage:messageid) { 114 | new TGChatId:chatid[15]; 115 | TG_CacheGetChatID(chatid); 116 | TG_EditMessage(bot,chatid,messageid,"***edited message***",.parse_mode=MARKDOWN); 117 | return 1; 118 | } 119 | public OnTGChannelPost(TGBot:bot,TGMessage:postid) { 120 | new 121 | post[200], 122 | chatname[56], 123 | TGChatId:chatid[15]; 124 | 125 | TG_CacheGetMessage(post); 126 | TG_CacheGetChatName(chatname); 127 | TG_CacheGetChatID(chatid); 128 | 129 | printf("[%s](%s):%s(%d)",chatname,_:chatid,post,_:postid); 130 | } 131 | public OnTGUserJoined(TGBot:bot,TGUser:userid[]) { 132 | new 133 | TGChatId:chatid[15], 134 | username[24], 135 | chatname[129]; 136 | 137 | TG_CacheGetUserName(username); 138 | TG_CacheGetChatID(chatid); 139 | TG_CacheGetChatName(chatname); 140 | 141 | printf("User %s(%s) joined %s(%s)",username,_:userid,chatname,_:chatid); 142 | return 1; 143 | } 144 | 145 | public OnTGUserLeft(TGBot:bot,TGUser:userid[]) { 146 | new 147 | TGChatId:chatid[15], 148 | username[24], 149 | chatname[129]; 150 | 151 | TG_CacheGetUserName(username); 152 | TG_CacheGetChatID(chatid); 153 | TG_CacheGetChatName(chatname); 154 | 155 | printf("User %s(%s) left %s(%s)",username,_:userid,chatname,_:chatid); 156 | return 1; 157 | } -------------------------------------------------------------------------------- /src/internals.rs: -------------------------------------------------------------------------------- 1 | use crate::api::Bot; 2 | use crate::callbacks; 3 | use crate::types::*; 4 | use samp::prelude::*; 5 | use std::collections::LinkedList; 6 | 7 | pub fn clear_caches(cache: &mut LinkedList) { 8 | if !cache.is_empty() { 9 | cache.clear(); 10 | } 11 | } 12 | 13 | pub fn update_process(plugin: &mut super::TgConnector) { 14 | for (id, bot) in &plugin.bots { 15 | for update in bot.update_reciever.as_ref().unwrap().try_iter() { 16 | match get_update_type(&update) { 17 | UpdateType::Message => { 18 | let message = update.message.unwrap(); 19 | let user = message.from.unwrap(); 20 | 21 | plugin.telegram_firstname.push_front(user.first_name); 22 | plugin.telegram_messages.push_front(message.text.unwrap()); 23 | plugin.telegram_chatid.push_front(message.chat.id); 24 | plugin.telegram_chattype.push_front(message.chat.chat_type); 25 | 26 | if let Some(lastname) = user.last_name { 27 | plugin.telegram_lastname.push_front(lastname); 28 | } 29 | 30 | if let Some(username) = user.username { 31 | plugin.telegram_username.push_front(username); 32 | } 33 | 34 | if let Some(chatname) = message.chat.title { 35 | plugin.telegram_chatname.push_front(chatname); 36 | } 37 | 38 | callbacks::on_tg_message( 39 | &plugin.amx_list, 40 | *id, 41 | user.id, 42 | message.message_id, 43 | message.message_thread_id.unwrap_or(-1), 44 | ); 45 | } 46 | 47 | UpdateType::ChannelPost => { 48 | let message = update.channel_post.unwrap(); 49 | plugin.telegram_messages.push_front(message.text.unwrap()); 50 | plugin.telegram_chatid.push_front(message.chat.id); 51 | 52 | if let Some(chatname) = message.chat.title { 53 | plugin.telegram_chatname.push_front(chatname); 54 | } 55 | callbacks::on_tg_channel_post(&plugin.amx_list, *id, message.message_id); 56 | } 57 | 58 | UpdateType::UserJoined => { 59 | let message = update.message.unwrap(); 60 | let user = message.from.unwrap(); 61 | 62 | plugin.telegram_firstname.push_front(user.first_name); 63 | 64 | if let Some(lastname) = user.last_name { 65 | plugin.telegram_lastname.push_front(lastname); 66 | } 67 | 68 | if let Some(chatname) = message.chat.title { 69 | plugin.telegram_chatname.push_front(chatname); 70 | } 71 | 72 | plugin.telegram_chatid.push_front(message.chat.id); 73 | 74 | for user in message.new_chat_members.unwrap() { 75 | if let Some(username) = user.username { 76 | plugin.telegram_username.push_front(username); 77 | } 78 | 79 | callbacks::on_tg_user_joined(&plugin.amx_list, *id, user.id); 80 | } 81 | } 82 | 83 | UpdateType::UserLeft => { 84 | let message = update.message.unwrap(); 85 | let user = message.from.unwrap(); 86 | 87 | plugin.telegram_firstname.push_front(user.first_name); 88 | 89 | if let Some(lastname) = user.last_name { 90 | plugin.telegram_lastname.push_front(lastname); 91 | } 92 | 93 | if let Some(chatname) = message.chat.title { 94 | plugin.telegram_chatname.push_front(chatname); 95 | } 96 | 97 | plugin.telegram_chatid.push_front(message.chat.id); 98 | 99 | let user = message.left_chat_member.unwrap(); 100 | 101 | if let Some(username) = user.username { 102 | plugin.telegram_username.push_front(username); 103 | } 104 | 105 | callbacks::on_tg_user_left(&plugin.amx_list, *id, user.id); 106 | } 107 | 108 | UpdateType::UnknownUpdate => { 109 | continue; 110 | } 111 | } 112 | } 113 | } 114 | } 115 | 116 | fn get_update_type(update: &Update) -> UpdateType { 117 | if update.message.is_some() { 118 | let message = update.message.as_ref().unwrap(); 119 | if message.text.is_some() { 120 | return UpdateType::Message; 121 | } else if message.new_chat_members.is_some() { 122 | return UpdateType::UserJoined; 123 | } else if message.left_chat_member.is_some() { 124 | return UpdateType::UserLeft; 125 | } 126 | } else if update.channel_post.is_some() { 127 | let post = update.channel_post.as_ref().unwrap(); 128 | if post.text.is_some() { 129 | return UpdateType::ChannelPost; 130 | } 131 | } 132 | UpdateType::UnknownUpdate 133 | } 134 | 135 | pub fn on_send_message_process(plugin: &mut super::TgConnector) { 136 | for (id, bot) in &plugin.bots { 137 | for (message, callback) in bot.send_message_reciever.as_ref().unwrap().try_iter() { 138 | if message.text != None { 139 | plugin.telegram_messages.push_front(message.text.unwrap()); 140 | plugin.telegram_chatid.push_front(message.chat.id); 141 | callbacks::on_tg_send_message(&plugin.amx_list, &callback, *id, message.message_id); 142 | } 143 | } 144 | } 145 | } 146 | 147 | pub fn create_bot( 148 | plugin: &mut super::TgConnector, 149 | mut api: Bot, 150 | proxy_url: Option, 151 | ) -> AmxResult { 152 | if api.connect(proxy_url) { 153 | plugin.bots.insert(plugin.bot_context_id, api); 154 | plugin.bot_context_id += 1; 155 | Ok(plugin.bot_context_id as i32 - 1) 156 | } else { 157 | Ok(-1) 158 | } 159 | } 160 | 161 | pub fn get_parse_mode(numerical_code: i32) -> Option<&'static str> { 162 | match numerical_code { 163 | 0 => Some("HTML"), 164 | 1 => Some("markdown"), 165 | 2 => Some("MarkdownV2"), 166 | _ => None, 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/api.rs: -------------------------------------------------------------------------------- 1 | use crate::http::{HttpMethod, HttpRequest}; 2 | use crate::methods::*; 3 | use crate::types::*; 4 | use log::error; 5 | use serde::de::DeserializeOwned; 6 | use serde::Serialize; 7 | use serde_json::{from_str, to_string}; 8 | use std::collections::VecDeque; 9 | use std::sync::mpsc::{channel, Receiver, Sender}; 10 | use threadpool::ThreadPool; 11 | 12 | pub struct Bot { 13 | pub api_request_link: String, 14 | pub user_id: String, 15 | pub update_reciever: Option>, 16 | pub update_sender: Option>, 17 | pub send_message_reciever: Option>, 18 | pub send_message_sender: Option>, 19 | pub pool: ThreadPool, 20 | pub proxy_url: Option, 21 | } 22 | 23 | impl Bot { 24 | pub fn new(bot_token: String, thread_count: i32, proxy_url: Option) -> Self { 25 | let (update_sender, update_reciever) = channel(); 26 | let (send_message_sender, send_message_reciever) = channel(); 27 | 28 | Bot { 29 | api_request_link: String::from("https://api.telegram.org/bot") + &bot_token, 30 | user_id: String::new(), 31 | update_reciever: Some(update_reciever), 32 | update_sender: Some(update_sender), 33 | send_message_reciever: Some(send_message_reciever), 34 | send_message_sender: Some(send_message_sender), 35 | pool: ThreadPool::new(thread_count as usize), 36 | proxy_url, 37 | } 38 | } 39 | 40 | pub fn connect(&mut self, proxy_url: Option) -> bool { 41 | let request = HttpRequest { 42 | url: format!("{}/getme", self.api_request_link), 43 | method: HttpMethod::Get, 44 | body: None, 45 | proxy_url, 46 | }; 47 | 48 | match request.make_request() { 49 | Ok(response) => { 50 | let response: APIResponse = from_str(&response).unwrap(); 51 | 52 | if response.ok { 53 | self.user_id = response.body.unwrap().id; 54 | self.get_updates(); 55 | true 56 | } else { 57 | error!("Bot couldn't connect.{:?}", response); 58 | false 59 | } 60 | } 61 | Err(err) => { 62 | error!("{:?}", err); 63 | false 64 | } 65 | } 66 | } 67 | 68 | fn get_updates(&self) { 69 | let update_move = self.update_sender.clone(); 70 | let api_link = self.api_request_link.clone(); 71 | let proxy_url = self.proxy_url.clone(); 72 | let mut getupdate = GetUpdates { offset: -2 }; 73 | 74 | self.pool.execute(move || loop { 75 | let update: Result>, String> = 76 | telegram_request("getUpdates", &api_link, &getupdate, &proxy_url); 77 | match update { 78 | Ok(update) => { 79 | let mut check_result: VecDeque = match update.body { 80 | None => { 81 | continue; 82 | } 83 | Some(check_result) => check_result, 84 | }; 85 | 86 | let first_update = check_result.pop_front(); 87 | 88 | match first_update { 89 | Some(result) => { 90 | getupdate.offset = result.update_id + 1; 91 | update_move.as_ref().unwrap().send(result).unwrap(); 92 | } 93 | 94 | None => { 95 | continue; 96 | } 97 | } 98 | } 99 | 100 | Err(err) => { 101 | error!("{:?}", err); 102 | continue; 103 | } 104 | } 105 | }); 106 | } 107 | 108 | pub fn send_message(&self, send_message_obj: SendMessage, callback: Option) { 109 | let send_message_move = self.send_message_sender.clone(); 110 | let api_link = self.api_request_link.clone(); 111 | let proxy_url = self.proxy_url.clone(); 112 | 113 | self.pool.execute(move || { 114 | let response: Result, String> = 115 | telegram_request("sendmessage", &api_link, &send_message_obj, &proxy_url); 116 | match response { 117 | Ok(response) => { 118 | if !response.ok { 119 | error!("Couldn't send message.{:?}", response); 120 | } else if callback != None { 121 | let sender = send_message_move.as_ref().unwrap(); 122 | let send_data = (response.body.unwrap(), callback.unwrap()); 123 | sender.send(send_data).unwrap(); 124 | } 125 | } 126 | 127 | Err(err) => { 128 | error!("{:?}", err); 129 | } 130 | } 131 | }); 132 | } 133 | 134 | pub fn delete_message(&self, delete_message_obj: DeleteMessage) { 135 | let api_link = self.api_request_link.clone(); 136 | let proxy_url = self.proxy_url.clone(); 137 | 138 | self.pool.execute(move || { 139 | let response: Result, String> = 140 | telegram_request("deletemessage", &api_link, &delete_message_obj, &proxy_url); 141 | 142 | match response { 143 | Ok(response) => { 144 | if !response.ok { 145 | error!( 146 | "Message {:?} couldn't delete. {:?}", 147 | delete_message_obj, response 148 | ); 149 | } 150 | } 151 | 152 | Err(err) => { 153 | error!("{:?}", err); 154 | } 155 | } 156 | }); 157 | } 158 | 159 | pub fn edit_message(&self, edit_message_obj: EditMessageText) { 160 | let api_link = self.api_request_link.clone(); 161 | let proxy_url = self.proxy_url.clone(); 162 | 163 | self.pool.execute(move || { 164 | let response: Result, String> = 165 | telegram_request("editmessagetext", &api_link, &edit_message_obj, &proxy_url); 166 | match response { 167 | Ok(response) => { 168 | if !response.ok { 169 | error!( 170 | "Message {:?} couldn't edit {:?}", 171 | edit_message_obj, response 172 | ); 173 | } 174 | } 175 | 176 | Err(err) => { 177 | error!("{:?}", err); 178 | } 179 | } 180 | }); 181 | } 182 | 183 | pub fn get_chat_member(&self, getchatmember: GetChatMember) -> Option { 184 | let response: Result, String> = telegram_request( 185 | "getchatmember", 186 | &self.api_request_link, 187 | &getchatmember, 188 | &self.proxy_url, 189 | ); 190 | 191 | match response { 192 | Ok(response) => { 193 | if response.ok { 194 | response.body 195 | } else { 196 | error!("get_chat_member.{:?}", response); 197 | None 198 | } 199 | } 200 | 201 | Err(err) => { 202 | error!("{:?}", err); 203 | None 204 | } 205 | } 206 | } 207 | 208 | pub fn get_chat_members_count(&self, getchatmemberscount: GetChatMembersCount) -> Option { 209 | let response: Result, String> = telegram_request( 210 | "getchatmemberscount", 211 | &self.api_request_link, 212 | &getchatmemberscount, 213 | &self.proxy_url, 214 | ); 215 | 216 | match response { 217 | Ok(response) => { 218 | if response.ok { 219 | response.body 220 | } else { 221 | error!("get_chat_members_count.{:?}", response); 222 | None 223 | } 224 | } 225 | 226 | Err(err) => { 227 | error!("{:?}", err); 228 | None 229 | } 230 | } 231 | } 232 | 233 | pub fn get_chat(&self, getchat: GetChat) -> Option { 234 | let response: Result, String> = 235 | telegram_request("getchat", &self.api_request_link, &getchat, &self.proxy_url); 236 | 237 | match response { 238 | Ok(response) => { 239 | if response.ok { 240 | response.body 241 | } else { 242 | error!("get_chat.{:?}", response); 243 | None 244 | } 245 | } 246 | 247 | Err(err) => { 248 | error!("{:?}", err); 249 | None 250 | } 251 | } 252 | } 253 | 254 | pub fn ban_chat_member(&self, banchatmember: BanChatMember) { 255 | let api_link = self.api_request_link.clone(); 256 | let proxy_url = self.proxy_url.clone(); 257 | 258 | self.pool.execute(move || { 259 | let response: Result, String> = 260 | telegram_request("banChatMember", &api_link, &banchatmember, &proxy_url); 261 | match response { 262 | Ok(response) => { 263 | if !response.ok { 264 | error!("ban_chat_member.{:?}", response); 265 | } 266 | } 267 | 268 | Err(err) => { 269 | error!("{:?}", err); 270 | } 271 | } 272 | }); 273 | } 274 | 275 | pub fn unban_chat_member(&self, unbanchatmember: UnbanChatMember) { 276 | let api_link = self.api_request_link.clone(); 277 | let proxy_url = self.proxy_url.clone(); 278 | 279 | self.pool.execute(move || { 280 | let response: Result, String> = 281 | telegram_request("unbanChatMember", &api_link, &unbanchatmember, &proxy_url); 282 | match response { 283 | Ok(response) => { 284 | if !response.ok { 285 | error!("unban_chat_member.{:?}", response); 286 | } 287 | } 288 | 289 | Err(err) => { 290 | error!("{:?}", err); 291 | } 292 | } 293 | }); 294 | } 295 | } 296 | 297 | fn telegram_request( 298 | endpoint: &str, 299 | api_link: &str, 300 | body: B, 301 | proxy_url: &Option, 302 | ) -> Result, String> { 303 | let request = HttpRequest { 304 | url: format!("{}/{}", api_link, endpoint), 305 | method: HttpMethod::Post, 306 | body: Some(to_string(&body).unwrap()), 307 | proxy_url: proxy_url.clone(), 308 | }; 309 | 310 | match request.make_request() { 311 | Ok(response) => Ok(from_str(&response).unwrap()), 312 | Err(err) => Err(err), 313 | } 314 | } 315 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "MacTypes-sys" 7 | version = "2.1.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "eaf9f0d0b1cc33a4d2aee14fb4b2eac03462ef4db29c8ac4057327d8a71ad86f" 10 | dependencies = [ 11 | "libc", 12 | ] 13 | 14 | [[package]] 15 | name = "approx" 16 | version = "0.1.1" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "08abcc3b4e9339e33a3d0a5ed15d84a687350c05689d825e0f6655eef9e76a94" 19 | 20 | [[package]] 21 | name = "autocfg" 22 | version = "0.1.2" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "a6d640bee2da49f60a4068a7fae53acde8982514ab7bae8b8cea9e88cbcfd799" 25 | 26 | [[package]] 27 | name = "bitflags" 28 | version = "1.0.4" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" 31 | 32 | [[package]] 33 | name = "cc" 34 | version = "1.0.28" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "bb4a8b715cb4597106ea87c7c84b2f1d452c7492033765df7f32651e66fcf749" 37 | 38 | [[package]] 39 | name = "cfg-if" 40 | version = "0.1.6" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "082bb9b28e00d3c9d39cc03e64ce4cea0f1bb9b3fde493f0cbc008472d22bdf4" 43 | 44 | [[package]] 45 | name = "cgmath" 46 | version = "0.16.1" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "64a4b57c8f4e3a2e9ac07e0f6abc9c24b6fc9e1b54c3478cfb598f3d0023e51c" 49 | dependencies = [ 50 | "approx", 51 | "num-traits 0.1.43", 52 | "rand 0.4.6", 53 | ] 54 | 55 | [[package]] 56 | name = "cloudabi" 57 | version = "0.0.3" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" 60 | dependencies = [ 61 | "bitflags", 62 | ] 63 | 64 | [[package]] 65 | name = "colored" 66 | version = "1.8.0" 67 | source = "registry+https://github.com/rust-lang/crates.io-index" 68 | checksum = "6cdb90b60f2927f8d76139c72dbde7e10c3a2bc47c8594c9c7a66529f2687c03" 69 | dependencies = [ 70 | "lazy_static", 71 | "winconsole", 72 | ] 73 | 74 | [[package]] 75 | name = "core-foundation" 76 | version = "0.5.1" 77 | source = "registry+https://github.com/rust-lang/crates.io-index" 78 | checksum = "286e0b41c3a20da26536c6000a280585d519fd07b3956b43aed8a79e9edce980" 79 | dependencies = [ 80 | "core-foundation-sys", 81 | "libc", 82 | ] 83 | 84 | [[package]] 85 | name = "core-foundation-sys" 86 | version = "0.5.1" 87 | source = "registry+https://github.com/rust-lang/crates.io-index" 88 | checksum = "716c271e8613ace48344f723b60b900a93150271e5be206212d052bbc0883efa" 89 | dependencies = [ 90 | "libc", 91 | ] 92 | 93 | [[package]] 94 | name = "encoding" 95 | version = "0.2.33" 96 | source = "registry+https://github.com/rust-lang/crates.io-index" 97 | checksum = "6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec" 98 | dependencies = [ 99 | "encoding-index-japanese", 100 | "encoding-index-korean", 101 | "encoding-index-simpchinese", 102 | "encoding-index-singlebyte", 103 | "encoding-index-tradchinese", 104 | ] 105 | 106 | [[package]] 107 | name = "encoding-index-japanese" 108 | version = "1.20141219.5" 109 | source = "registry+https://github.com/rust-lang/crates.io-index" 110 | checksum = "04e8b2ff42e9a05335dbf8b5c6f7567e5591d0d916ccef4e0b1710d32a0d0c91" 111 | dependencies = [ 112 | "encoding_index_tests", 113 | ] 114 | 115 | [[package]] 116 | name = "encoding-index-korean" 117 | version = "1.20141219.5" 118 | source = "registry+https://github.com/rust-lang/crates.io-index" 119 | checksum = "4dc33fb8e6bcba213fe2f14275f0963fd16f0a02c878e3095ecfdf5bee529d81" 120 | dependencies = [ 121 | "encoding_index_tests", 122 | ] 123 | 124 | [[package]] 125 | name = "encoding-index-simpchinese" 126 | version = "1.20141219.5" 127 | source = "registry+https://github.com/rust-lang/crates.io-index" 128 | checksum = "d87a7194909b9118fc707194baa434a4e3b0fb6a5a757c73c3adb07aa25031f7" 129 | dependencies = [ 130 | "encoding_index_tests", 131 | ] 132 | 133 | [[package]] 134 | name = "encoding-index-singlebyte" 135 | version = "1.20141219.5" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | checksum = "3351d5acffb224af9ca265f435b859c7c01537c0849754d3db3fdf2bfe2ae84a" 138 | dependencies = [ 139 | "encoding_index_tests", 140 | ] 141 | 142 | [[package]] 143 | name = "encoding-index-tradchinese" 144 | version = "1.20141219.5" 145 | source = "registry+https://github.com/rust-lang/crates.io-index" 146 | checksum = "fd0e20d5688ce3cab59eb3ef3a2083a5c77bf496cb798dc6fcdb75f323890c18" 147 | dependencies = [ 148 | "encoding_index_tests", 149 | ] 150 | 151 | [[package]] 152 | name = "encoding_index_tests" 153 | version = "0.1.4" 154 | source = "registry+https://github.com/rust-lang/crates.io-index" 155 | checksum = "a246d82be1c9d791c5dfde9a2bd045fc3cbba3fa2b11ad558f27d01712f00569" 156 | 157 | [[package]] 158 | name = "fern" 159 | version = "0.5.8" 160 | source = "registry+https://github.com/rust-lang/crates.io-index" 161 | checksum = "29d26fa0f4d433d1956746e66ec10d6bf4d6c8b93cd39965cceea7f7cc78c7dd" 162 | dependencies = [ 163 | "log", 164 | ] 165 | 166 | [[package]] 167 | name = "foreign-types" 168 | version = "0.3.2" 169 | source = "registry+https://github.com/rust-lang/crates.io-index" 170 | checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" 171 | dependencies = [ 172 | "foreign-types-shared", 173 | ] 174 | 175 | [[package]] 176 | name = "foreign-types-shared" 177 | version = "0.1.1" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" 180 | 181 | [[package]] 182 | name = "fuchsia-cprng" 183 | version = "0.1.0" 184 | source = "registry+https://github.com/rust-lang/crates.io-index" 185 | checksum = "81f7f8eb465745ea9b02e2704612a9946a59fa40572086c6fd49d6ddcf30bf31" 186 | 187 | [[package]] 188 | name = "itoa" 189 | version = "0.4.3" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" 192 | 193 | [[package]] 194 | name = "lazy_static" 195 | version = "1.2.0" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "a374c89b9db55895453a74c1e38861d9deec0b01b405a82516e9d5de4820dea1" 198 | 199 | [[package]] 200 | name = "libc" 201 | version = "0.2.48" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "e962c7641008ac010fa60a7dfdc1712449f29c44ef2d4702394aea943ee75047" 204 | 205 | [[package]] 206 | name = "log" 207 | version = "0.4.6" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "c84ec4b527950aa83a329754b01dbe3f58361d1c5efacd1f6d68c494d08a17c6" 210 | dependencies = [ 211 | "cfg-if", 212 | ] 213 | 214 | [[package]] 215 | name = "minihttp" 216 | version = "0.1.9" 217 | source = "git+https://github.com/Sreyas-Sreelal/minihttp#20e6a48dc6cbdb1b38d66140819092d37c663163" 218 | dependencies = [ 219 | "minihttpse", 220 | "miniurl", 221 | "native-tls", 222 | ] 223 | 224 | [[package]] 225 | name = "minihttpse" 226 | version = "0.1.6" 227 | source = "registry+https://github.com/rust-lang/crates.io-index" 228 | checksum = "8e50e8cee436b4318ec759930d6ea5f839d14dab94e81b6fba37d492d07ebf55" 229 | 230 | [[package]] 231 | name = "miniurl" 232 | version = "0.1.3" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "1346e28b38a4554e6fa7f8fc49874cac3f9ecb781408bac3274fb948fee303e0" 235 | 236 | [[package]] 237 | name = "native-tls" 238 | version = "0.2.2" 239 | source = "registry+https://github.com/rust-lang/crates.io-index" 240 | checksum = "ff8e08de0070bbf4c31f452ea2a70db092f36f6f2e4d897adf5674477d488fb2" 241 | dependencies = [ 242 | "lazy_static", 243 | "libc", 244 | "log", 245 | "openssl", 246 | "openssl-probe", 247 | "openssl-sys", 248 | "schannel", 249 | "security-framework", 250 | "security-framework-sys", 251 | "tempfile", 252 | ] 253 | 254 | [[package]] 255 | name = "num-traits" 256 | version = "0.1.43" 257 | source = "registry+https://github.com/rust-lang/crates.io-index" 258 | checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" 259 | dependencies = [ 260 | "num-traits 0.2.6", 261 | ] 262 | 263 | [[package]] 264 | name = "num-traits" 265 | version = "0.2.6" 266 | source = "registry+https://github.com/rust-lang/crates.io-index" 267 | checksum = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1" 268 | 269 | [[package]] 270 | name = "num_cpus" 271 | version = "1.10.0" 272 | source = "registry+https://github.com/rust-lang/crates.io-index" 273 | checksum = "1a23f0ed30a54abaa0c7e83b1d2d87ada7c3c23078d1d87815af3e3b6385fbba" 274 | dependencies = [ 275 | "libc", 276 | ] 277 | 278 | [[package]] 279 | name = "openssl" 280 | version = "0.10.16" 281 | source = "registry+https://github.com/rust-lang/crates.io-index" 282 | checksum = "ec7bd7ca4cce6dbdc77e7c1230682740d307d1218a87fb0349a571272be749f9" 283 | dependencies = [ 284 | "bitflags", 285 | "cfg-if", 286 | "foreign-types", 287 | "lazy_static", 288 | "libc", 289 | "openssl-sys", 290 | ] 291 | 292 | [[package]] 293 | name = "openssl-probe" 294 | version = "0.1.2" 295 | source = "registry+https://github.com/rust-lang/crates.io-index" 296 | checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" 297 | 298 | [[package]] 299 | name = "openssl-sys" 300 | version = "0.9.40" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "1bb974e77de925ef426b6bc82fce15fd45bdcbeb5728bffcfc7cdeeb7ce1c2d6" 303 | dependencies = [ 304 | "cc", 305 | "libc", 306 | "pkg-config", 307 | "vcpkg", 308 | ] 309 | 310 | [[package]] 311 | name = "pkg-config" 312 | version = "0.3.14" 313 | source = "registry+https://github.com/rust-lang/crates.io-index" 314 | checksum = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c" 315 | 316 | [[package]] 317 | name = "proc-macro2" 318 | version = "0.4.27" 319 | source = "registry+https://github.com/rust-lang/crates.io-index" 320 | checksum = "4d317f9caece796be1980837fd5cb3dfec5613ebdb04ad0956deea83ce168915" 321 | dependencies = [ 322 | "unicode-xid", 323 | ] 324 | 325 | [[package]] 326 | name = "quote" 327 | version = "0.6.11" 328 | source = "registry+https://github.com/rust-lang/crates.io-index" 329 | checksum = "cdd8e04bd9c52e0342b406469d494fcb033be4bdbe5c606016defbb1681411e1" 330 | dependencies = [ 331 | "proc-macro2", 332 | ] 333 | 334 | [[package]] 335 | name = "rand" 336 | version = "0.4.6" 337 | source = "registry+https://github.com/rust-lang/crates.io-index" 338 | checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" 339 | dependencies = [ 340 | "fuchsia-cprng", 341 | "libc", 342 | "rand_core 0.3.1", 343 | "rdrand", 344 | "winapi", 345 | ] 346 | 347 | [[package]] 348 | name = "rand" 349 | version = "0.6.5" 350 | source = "registry+https://github.com/rust-lang/crates.io-index" 351 | checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" 352 | dependencies = [ 353 | "autocfg", 354 | "libc", 355 | "rand_chacha", 356 | "rand_core 0.4.0", 357 | "rand_hc", 358 | "rand_isaac", 359 | "rand_jitter", 360 | "rand_os", 361 | "rand_pcg", 362 | "rand_xorshift", 363 | "winapi", 364 | ] 365 | 366 | [[package]] 367 | name = "rand_chacha" 368 | version = "0.1.1" 369 | source = "registry+https://github.com/rust-lang/crates.io-index" 370 | checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" 371 | dependencies = [ 372 | "autocfg", 373 | "rand_core 0.3.1", 374 | ] 375 | 376 | [[package]] 377 | name = "rand_core" 378 | version = "0.3.1" 379 | source = "registry+https://github.com/rust-lang/crates.io-index" 380 | checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" 381 | dependencies = [ 382 | "rand_core 0.4.0", 383 | ] 384 | 385 | [[package]] 386 | name = "rand_core" 387 | version = "0.4.0" 388 | source = "registry+https://github.com/rust-lang/crates.io-index" 389 | checksum = "d0e7a549d590831370895ab7ba4ea0c1b6b011d106b5ff2da6eee112615e6dc0" 390 | 391 | [[package]] 392 | name = "rand_hc" 393 | version = "0.1.0" 394 | source = "registry+https://github.com/rust-lang/crates.io-index" 395 | checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" 396 | dependencies = [ 397 | "rand_core 0.3.1", 398 | ] 399 | 400 | [[package]] 401 | name = "rand_isaac" 402 | version = "0.1.1" 403 | source = "registry+https://github.com/rust-lang/crates.io-index" 404 | checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" 405 | dependencies = [ 406 | "rand_core 0.3.1", 407 | ] 408 | 409 | [[package]] 410 | name = "rand_jitter" 411 | version = "0.1.2" 412 | source = "registry+https://github.com/rust-lang/crates.io-index" 413 | checksum = "080723c6145e37503a2224f801f252e14ac5531cb450f4502698542d188cb3c0" 414 | dependencies = [ 415 | "libc", 416 | "rand_core 0.4.0", 417 | "winapi", 418 | ] 419 | 420 | [[package]] 421 | name = "rand_os" 422 | version = "0.1.2" 423 | source = "registry+https://github.com/rust-lang/crates.io-index" 424 | checksum = "b7c690732391ae0abafced5015ffb53656abfaec61b342290e5eb56b286a679d" 425 | dependencies = [ 426 | "cloudabi", 427 | "fuchsia-cprng", 428 | "libc", 429 | "rand_core 0.4.0", 430 | "rdrand", 431 | "winapi", 432 | ] 433 | 434 | [[package]] 435 | name = "rand_pcg" 436 | version = "0.1.1" 437 | source = "registry+https://github.com/rust-lang/crates.io-index" 438 | checksum = "086bd09a33c7044e56bb44d5bdde5a60e7f119a9e95b0775f545de759a32fe05" 439 | dependencies = [ 440 | "rand_core 0.3.1", 441 | "rustc_version", 442 | ] 443 | 444 | [[package]] 445 | name = "rand_xorshift" 446 | version = "0.1.1" 447 | source = "registry+https://github.com/rust-lang/crates.io-index" 448 | checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" 449 | dependencies = [ 450 | "rand_core 0.3.1", 451 | ] 452 | 453 | [[package]] 454 | name = "rdrand" 455 | version = "0.4.0" 456 | source = "registry+https://github.com/rust-lang/crates.io-index" 457 | checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" 458 | dependencies = [ 459 | "rand_core 0.3.1", 460 | ] 461 | 462 | [[package]] 463 | name = "redox_syscall" 464 | version = "0.1.51" 465 | source = "registry+https://github.com/rust-lang/crates.io-index" 466 | checksum = "423e376fffca3dfa06c9e9790a9ccd282fafb3cc6e6397d01dbf64f9bacc6b85" 467 | 468 | [[package]] 469 | name = "remove_dir_all" 470 | version = "0.5.1" 471 | source = "registry+https://github.com/rust-lang/crates.io-index" 472 | checksum = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5" 473 | dependencies = [ 474 | "winapi", 475 | ] 476 | 477 | [[package]] 478 | name = "rgb" 479 | version = "0.8.13" 480 | source = "registry+https://github.com/rust-lang/crates.io-index" 481 | checksum = "4f089652ca87f5a82a62935ec6172a534066c7b97be003cc8f702ee9a7a59c92" 482 | 483 | [[package]] 484 | name = "rustc_version" 485 | version = "0.2.3" 486 | source = "registry+https://github.com/rust-lang/crates.io-index" 487 | checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" 488 | dependencies = [ 489 | "semver", 490 | ] 491 | 492 | [[package]] 493 | name = "ryu" 494 | version = "0.2.7" 495 | source = "registry+https://github.com/rust-lang/crates.io-index" 496 | checksum = "eb9e9b8cde282a9fe6a42dd4681319bfb63f121b8a8ee9439c6f4107e58a46f7" 497 | 498 | [[package]] 499 | name = "samp" 500 | version = "0.1.3" 501 | source = "git+https://github.com/Pycckue-Bnepeg/samp-rs/#17ecb2f722bf0d74a98eb782745cd77e41c3c60a" 502 | dependencies = [ 503 | "fern", 504 | "samp-codegen", 505 | "samp-sdk", 506 | ] 507 | 508 | [[package]] 509 | name = "samp-codegen" 510 | version = "0.1.2" 511 | source = "git+https://github.com/Pycckue-Bnepeg/samp-rs/#17ecb2f722bf0d74a98eb782745cd77e41c3c60a" 512 | dependencies = [ 513 | "proc-macro2", 514 | "quote", 515 | "syn", 516 | ] 517 | 518 | [[package]] 519 | name = "samp-sdk" 520 | version = "0.9.2" 521 | source = "git+https://github.com/Pycckue-Bnepeg/samp-rs/#17ecb2f722bf0d74a98eb782745cd77e41c3c60a" 522 | dependencies = [ 523 | "bitflags", 524 | "colored", 525 | ] 526 | 527 | [[package]] 528 | name = "schannel" 529 | version = "0.1.14" 530 | source = "registry+https://github.com/rust-lang/crates.io-index" 531 | checksum = "0e1a231dc10abf6749cfa5d7767f25888d484201accbd919b66ab5413c502d56" 532 | dependencies = [ 533 | "lazy_static", 534 | "winapi", 535 | ] 536 | 537 | [[package]] 538 | name = "security-framework" 539 | version = "0.2.2" 540 | source = "registry+https://github.com/rust-lang/crates.io-index" 541 | checksum = "bfab8dda0e7a327c696d893df9ffa19cadc4bd195797997f5223cf5831beaf05" 542 | dependencies = [ 543 | "core-foundation", 544 | "core-foundation-sys", 545 | "libc", 546 | "security-framework-sys", 547 | ] 548 | 549 | [[package]] 550 | name = "security-framework-sys" 551 | version = "0.2.3" 552 | source = "registry+https://github.com/rust-lang/crates.io-index" 553 | checksum = "3d6696852716b589dff9e886ff83778bb635150168e83afa8ac6b8a78cb82abc" 554 | dependencies = [ 555 | "MacTypes-sys", 556 | "core-foundation-sys", 557 | "libc", 558 | ] 559 | 560 | [[package]] 561 | name = "semver" 562 | version = "0.9.0" 563 | source = "registry+https://github.com/rust-lang/crates.io-index" 564 | checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" 565 | dependencies = [ 566 | "semver-parser", 567 | ] 568 | 569 | [[package]] 570 | name = "semver-parser" 571 | version = "0.7.0" 572 | source = "registry+https://github.com/rust-lang/crates.io-index" 573 | checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" 574 | 575 | [[package]] 576 | name = "serde" 577 | version = "1.0.86" 578 | source = "registry+https://github.com/rust-lang/crates.io-index" 579 | checksum = "52ab457c27b091c27b887eef7181b3ea11ab4f92f66e3a99b2e556b77f9cc6bd" 580 | 581 | [[package]] 582 | name = "serde_derive" 583 | version = "1.0.86" 584 | source = "registry+https://github.com/rust-lang/crates.io-index" 585 | checksum = "51eac71e1171246f337655221882f2f55a9c2e1d8ddc6990cee766509f15b702" 586 | dependencies = [ 587 | "proc-macro2", 588 | "quote", 589 | "syn", 590 | ] 591 | 592 | [[package]] 593 | name = "serde_json" 594 | version = "1.0.38" 595 | source = "registry+https://github.com/rust-lang/crates.io-index" 596 | checksum = "27dce848e7467aa0e2fcaf0a413641499c0b745452aaca1194d24dedde9e13c9" 597 | dependencies = [ 598 | "itoa", 599 | "ryu", 600 | "serde", 601 | ] 602 | 603 | [[package]] 604 | name = "syn" 605 | version = "0.15.26" 606 | source = "registry+https://github.com/rust-lang/crates.io-index" 607 | checksum = "f92e629aa1d9c827b2bb8297046c1ccffc57c99b947a680d3ccff1f136a3bee9" 608 | dependencies = [ 609 | "proc-macro2", 610 | "quote", 611 | "unicode-xid", 612 | ] 613 | 614 | [[package]] 615 | name = "tempfile" 616 | version = "3.0.5" 617 | source = "registry+https://github.com/rust-lang/crates.io-index" 618 | checksum = "7e91405c14320e5c79b3d148e1c86f40749a36e490642202a31689cb1a3452b2" 619 | dependencies = [ 620 | "cfg-if", 621 | "libc", 622 | "rand 0.6.5", 623 | "redox_syscall", 624 | "remove_dir_all", 625 | "winapi", 626 | ] 627 | 628 | [[package]] 629 | name = "tgconnector" 630 | version = "1.1.1" 631 | dependencies = [ 632 | "encoding", 633 | "fern", 634 | "log", 635 | "minihttp", 636 | "samp", 637 | "serde", 638 | "serde_derive", 639 | "serde_json", 640 | "threadpool", 641 | ] 642 | 643 | [[package]] 644 | name = "threadpool" 645 | version = "1.7.1" 646 | source = "registry+https://github.com/rust-lang/crates.io-index" 647 | checksum = "e2f0c90a5f3459330ac8bc0d2f879c693bb7a2f59689c1083fc4ef83834da865" 648 | dependencies = [ 649 | "num_cpus", 650 | ] 651 | 652 | [[package]] 653 | name = "unicode-xid" 654 | version = "0.1.0" 655 | source = "registry+https://github.com/rust-lang/crates.io-index" 656 | checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" 657 | 658 | [[package]] 659 | name = "vcpkg" 660 | version = "0.2.6" 661 | source = "registry+https://github.com/rust-lang/crates.io-index" 662 | checksum = "def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d" 663 | 664 | [[package]] 665 | name = "winapi" 666 | version = "0.3.6" 667 | source = "registry+https://github.com/rust-lang/crates.io-index" 668 | checksum = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" 669 | dependencies = [ 670 | "winapi-i686-pc-windows-gnu", 671 | "winapi-x86_64-pc-windows-gnu", 672 | ] 673 | 674 | [[package]] 675 | name = "winapi-i686-pc-windows-gnu" 676 | version = "0.4.0" 677 | source = "registry+https://github.com/rust-lang/crates.io-index" 678 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 679 | 680 | [[package]] 681 | name = "winapi-x86_64-pc-windows-gnu" 682 | version = "0.4.0" 683 | source = "registry+https://github.com/rust-lang/crates.io-index" 684 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 685 | 686 | [[package]] 687 | name = "winconsole" 688 | version = "0.10.0" 689 | source = "registry+https://github.com/rust-lang/crates.io-index" 690 | checksum = "3ef84b96d10db72dd980056666d7f1e7663ce93d82fa33b63e71c966f4cf5032" 691 | dependencies = [ 692 | "cgmath", 693 | "lazy_static", 694 | "rgb", 695 | "winapi", 696 | ] 697 | -------------------------------------------------------------------------------- /src/natives.rs: -------------------------------------------------------------------------------- 1 | use crate::api::Bot; 2 | use crate::encode::encode_replace; 3 | use crate::internals::{create_bot, get_parse_mode}; 4 | use crate::methods::*; 5 | use log::{error, warn}; 6 | use samp::native; 7 | use samp::prelude::*; 8 | 9 | impl super::TgConnector { 10 | #[native(name = "TG_Connect")] 11 | pub fn bot_connect( 12 | &mut self, 13 | _amx: &Amx, 14 | token: AmxString, 15 | proxy_url: AmxString, 16 | thread_count: i32, 17 | ) -> AmxResult { 18 | let proxy_url = proxy_url.to_string(); 19 | let proxy_url = if proxy_url.is_empty() { 20 | None 21 | } else { 22 | Some(proxy_url) 23 | }; 24 | 25 | let api = Bot::new(token.to_string(), thread_count, proxy_url.clone()); 26 | create_bot(self, api, proxy_url) 27 | } 28 | 29 | #[native(name = "TG_ConnectFromEnv")] 30 | pub fn bot_connect_from_env( 31 | &mut self, 32 | _amx: &Amx, 33 | variable: AmxString, 34 | proxy_url: AmxString, 35 | thread_count: i32, 36 | ) -> AmxResult { 37 | let variable = variable.to_string(); 38 | let token = std::env::var_os(&variable); 39 | let proxy_url = proxy_url.to_string(); 40 | let proxy_url = if proxy_url.is_empty() { 41 | None 42 | } else { 43 | Some(proxy_url) 44 | }; 45 | 46 | if token == None { 47 | error!("Environment variable {:?} is not set", variable); 48 | return Ok(-1); 49 | } 50 | 51 | let token = token.unwrap().into_string().unwrap(); 52 | let api = Bot::new(token, thread_count, proxy_url.clone()); 53 | 54 | create_bot(self, api, proxy_url) 55 | } 56 | 57 | #[allow(clippy::too_many_arguments)] 58 | #[native(name = "TG_SendMessage")] 59 | pub fn bot_send_message( 60 | &self, 61 | _amx: &Amx, 62 | botid: usize, 63 | chatid: AmxString, 64 | text: AmxString, 65 | reply_id: i32, 66 | parse_mode: i32, 67 | disable_web_page_preview: bool, 68 | callback: AmxString, 69 | ) -> AmxResult { 70 | if !self.bots.contains_key(&botid) { 71 | error!("Invalid bot id {} passed", botid); 72 | return Ok(0); 73 | } 74 | 75 | let reply = if reply_id == -1 { None } else { Some(reply_id) }; 76 | let callback = callback.to_string(); 77 | let parsemode = get_parse_mode(parse_mode); 78 | 79 | let callback = if callback.is_empty() { 80 | None 81 | } else { 82 | Some(callback) 83 | }; 84 | 85 | let send_message_obj = SendMessage { 86 | chat_id: chatid.to_string(), 87 | text: text.to_string(), 88 | reply_to_message_id: reply, 89 | parse_mode: parsemode, 90 | disable_web_page_preview, 91 | }; 92 | 93 | self.bots[&botid].send_message(send_message_obj, callback); 94 | Ok(1) 95 | } 96 | 97 | #[native(name = "TG_DeleteMessage")] 98 | pub fn bot_delete_message( 99 | &self, 100 | _amx: &Amx, 101 | botid: usize, 102 | chatid: AmxString, 103 | messageid: i32, 104 | ) -> AmxResult { 105 | if !self.bots.contains_key(&botid) { 106 | error!("Invalid bot id {} passed", botid); 107 | return Ok(0); 108 | } 109 | 110 | let delete_message_obj = DeleteMessage { 111 | chat_id: chatid.to_string(), 112 | message_id: messageid, 113 | }; 114 | 115 | self.bots[&botid].delete_message(delete_message_obj); 116 | Ok(1) 117 | } 118 | 119 | #[native(name = "TG_EditMessage")] 120 | pub fn bot_edit_message( 121 | &self, 122 | _amx: &Amx, 123 | botid: usize, 124 | chatid: AmxString, 125 | messageid: i32, 126 | text: AmxString, 127 | parse_mode: i32, 128 | ) -> AmxResult { 129 | let parsemode = get_parse_mode(parse_mode); 130 | 131 | if !self.bots.contains_key(&botid) { 132 | error!("Error Invalid bot id {} passed", botid); 133 | return Ok(0); 134 | } 135 | 136 | let edit_message_obj = EditMessageText { 137 | chat_id: chatid.to_string(), 138 | text: text.to_string(), 139 | message_id: messageid, 140 | parse_mode: parsemode, 141 | }; 142 | 143 | self.bots[&botid].edit_message(edit_message_obj); 144 | Ok(1) 145 | } 146 | 147 | #[native(name = "TG_GetBotUserID")] 148 | pub fn get_bot_user_id( 149 | &self, 150 | _amx: &Amx, 151 | botid: usize, 152 | dest: UnsizedBuffer, 153 | size: usize, 154 | ) -> AmxResult { 155 | if !self.bots.contains_key(&botid) { 156 | error!("Invalid bot id {} passed", botid); 157 | return Ok(0); 158 | } 159 | let userid = self.bots.get(&botid).unwrap(); 160 | let mut dest = dest.into_sized_buffer(size); 161 | let _ = samp::cell::string::put_in_buffer(&mut dest, &userid.user_id); 162 | Ok(1) 163 | } 164 | 165 | #[native(name = "TG_CacheGetMessage")] 166 | pub fn cache_get_message( 167 | &self, 168 | _amx: &Amx, 169 | dest: UnsizedBuffer, 170 | size: usize, 171 | ) -> AmxResult { 172 | let cache_list = &self.telegram_messages; 173 | cache_get!(cache_list, dest, size) 174 | } 175 | 176 | #[native(name = "TG_CacheGetUserName")] 177 | pub fn cache_get_username( 178 | &self, 179 | _amx: &Amx, 180 | dest: UnsizedBuffer, 181 | size: usize, 182 | ) -> AmxResult { 183 | let cache_list = &self.telegram_username; 184 | cache_get!(cache_list, dest, size) 185 | } 186 | 187 | #[native(name = "TG_CacheGetUserFirstName")] 188 | pub fn cache_get_user_first_name( 189 | &self, 190 | _amx: &Amx, 191 | dest: UnsizedBuffer, 192 | size: usize, 193 | ) -> AmxResult { 194 | let cache_list = &self.telegram_firstname; 195 | cache_get!(cache_list, dest, size) 196 | } 197 | 198 | #[native(name = "TG_CacheGetUserLastName")] 199 | pub fn cache_get_user_last_name( 200 | &self, 201 | _amx: &Amx, 202 | dest: UnsizedBuffer, 203 | size: usize, 204 | ) -> AmxResult { 205 | let cache_list = &self.telegram_lastname; 206 | cache_get!(cache_list, dest, size) 207 | } 208 | 209 | #[native(name = "TG_CacheGetChatID")] 210 | pub fn cache_get_chatid(&self, _amx: &Amx, dest: UnsizedBuffer, size: usize) -> AmxResult { 211 | let cache_list = &self.telegram_chatid; 212 | cache_get!(cache_list, dest, size) 213 | } 214 | 215 | #[native(name = "TG_CacheGetChatName")] 216 | pub fn cache_get_chatname( 217 | &self, 218 | _amx: &Amx, 219 | dest: UnsizedBuffer, 220 | size: usize, 221 | ) -> AmxResult { 222 | let cache_list = &self.telegram_chatname; 223 | cache_get!(cache_list, dest, size) 224 | } 225 | 226 | #[native(name = "TG_CacheGetChatType")] 227 | pub fn cache_get_chattype( 228 | &self, 229 | _amx: &Amx, 230 | dest: UnsizedBuffer, 231 | size: usize, 232 | ) -> AmxResult { 233 | let cache_list = &self.telegram_chattype; 234 | cache_get!(cache_list, dest, size) 235 | } 236 | 237 | #[native(name = "TG_GetUserChatStatus")] 238 | pub fn get_user_status( 239 | &self, 240 | _amx: &Amx, 241 | botid: usize, 242 | userid: AmxString, 243 | chatid: AmxString, 244 | ) -> AmxResult { 245 | if !self.bots.contains_key(&botid) { 246 | error!("**[TGConnector] Error Invalid bot id {} passed", botid); 247 | return Ok(0); 248 | } 249 | 250 | let getchatmember = GetChatMember { 251 | user_id: userid.to_string(), 252 | chat_id: chatid.to_string(), 253 | }; 254 | let chatmember = self.bots[&botid].get_chat_member(getchatmember); 255 | if chatmember.is_none() { 256 | return Ok(0); 257 | } 258 | 259 | let chatmember = chatmember.unwrap(); 260 | 261 | match chatmember.status.as_ref() { 262 | "creator" => Ok(1), 263 | "adminstrator" => Ok(2), 264 | "member" => Ok(3), 265 | "restricted" => Ok(4), 266 | "left" => Ok(5), 267 | "kicked" => Ok(6), 268 | _ => Ok(0), 269 | } 270 | } 271 | 272 | #[native(name = "TG_GetUserNameFromID")] 273 | pub fn get_username_from_id( 274 | &self, 275 | _amx: &Amx, 276 | botid: usize, 277 | userid: AmxString, 278 | chatid: AmxString, 279 | dest: UnsizedBuffer, 280 | size: usize, 281 | ) -> AmxResult { 282 | if !self.bots.contains_key(&botid) { 283 | error!("Invalid bot id {} passed", botid); 284 | return Ok(0); 285 | } 286 | 287 | let getchatmember = GetChatMember { 288 | user_id: userid.to_string(), 289 | chat_id: chatid.to_string(), 290 | }; 291 | let chatmember = self.bots[&botid].get_chat_member(getchatmember); 292 | 293 | if chatmember.is_none() { 294 | return Ok(0); 295 | } 296 | 297 | let chatmember = chatmember.unwrap(); 298 | let username = &chatmember.user.username; 299 | if *username == None { 300 | return Ok(0); 301 | } 302 | 303 | match encode_replace(username.as_ref().unwrap()) { 304 | Ok(encoded) => { 305 | let mut dest = dest.into_sized_buffer(size); 306 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 307 | Ok(1) 308 | } 309 | Err(err) => { 310 | error!( 311 | "[get_username_from_id] Failed encoding {:?} \n {:?}", 312 | username.as_ref().unwrap(), 313 | err 314 | ); 315 | Ok(0) 316 | } 317 | } 318 | } 319 | 320 | #[native(name = "TG_GetDisplayNameFromID")] 321 | pub fn get_display_name_from_id( 322 | &self, 323 | _amx: &Amx, 324 | botid: usize, 325 | userid: AmxString, 326 | chatid: AmxString, 327 | dest: UnsizedBuffer, 328 | size: usize, 329 | ) -> AmxResult { 330 | if !self.bots.contains_key(&botid) { 331 | error!("Invalid bot id {} passed", botid); 332 | return Ok(0); 333 | } 334 | 335 | let getchatmember = GetChatMember { 336 | user_id: userid.to_string(), 337 | chat_id: chatid.to_string(), 338 | }; 339 | 340 | let chatmember = self.bots[&botid].get_chat_member(getchatmember); 341 | if chatmember.is_none() { 342 | return Ok(0); 343 | } 344 | 345 | let chatmember = chatmember.unwrap(); 346 | let displayname = match &chatmember.user.last_name { 347 | None => chatmember.user.first_name, 348 | Some(lastname) => chatmember.user.first_name + " " + lastname, 349 | }; 350 | 351 | match encode_replace(&displayname) { 352 | Ok(encoded) => { 353 | let mut dest = dest.into_sized_buffer(size); 354 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 355 | Ok(1) 356 | } 357 | Err(err) => { 358 | error!( 359 | "get_display_name_from_id] Failed encoding {:?} \n {:?}", 360 | displayname, err 361 | ); 362 | Ok(0) 363 | } 364 | } 365 | } 366 | 367 | #[native(name = "TG_GetChatMembersCount")] 368 | pub fn get_chat_members_count( 369 | &self, 370 | _amx: &Amx, 371 | botid: usize, 372 | chatid: AmxString, 373 | ) -> AmxResult { 374 | if !self.bots.contains_key(&botid) { 375 | error!("Invalid bot id {} passed", botid); 376 | return Ok(-1); 377 | } 378 | 379 | let getchatmembercount = GetChatMembersCount { 380 | chat_id: chatid.to_string(), 381 | }; 382 | 383 | match self.bots[&botid].get_chat_members_count(getchatmembercount) { 384 | None => Ok(-1), 385 | Some(count) => Ok(count), 386 | } 387 | } 388 | 389 | #[native(name = "TG_GetChatTitle")] 390 | pub fn get_chat_title( 391 | &self, 392 | _amx: &Amx, 393 | botid: usize, 394 | chatid: AmxString, 395 | dest: UnsizedBuffer, 396 | size: usize, 397 | ) -> AmxResult { 398 | if !self.bots.contains_key(&botid) { 399 | error!("Invalid bot id {} passed", botid); 400 | return Ok(0); 401 | } 402 | 403 | let getchat = GetChat { 404 | chat_id: chatid.to_string(), 405 | }; 406 | 407 | let chat = self.bots[&botid].get_chat(getchat); 408 | if chat.is_none() { 409 | return Ok(0); 410 | } 411 | 412 | if chat.as_ref().unwrap().title.is_none() { 413 | return Ok(0); 414 | } 415 | 416 | let chat_title = chat.unwrap().title.unwrap(); 417 | match encode_replace(&chat_title) { 418 | Ok(encoded) => { 419 | let mut dest = dest.into_sized_buffer(size); 420 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 421 | Ok(1) 422 | } 423 | Err(err) => { 424 | error!( 425 | "[get_chat_title] Failed encoding {:?} \n {:?}", 426 | chat_title, err 427 | ); 428 | Ok(0) 429 | } 430 | } 431 | } 432 | 433 | #[native(name = "TG_GetChatDescription")] 434 | pub fn get_chat_description( 435 | &self, 436 | _amx: &Amx, 437 | botid: usize, 438 | chatid: AmxString, 439 | dest: UnsizedBuffer, 440 | size: usize, 441 | ) -> AmxResult { 442 | if !self.bots.contains_key(&botid) { 443 | error!("Invalid bot id {} passed", botid); 444 | return Ok(0); 445 | } 446 | 447 | let getchat = GetChat { 448 | chat_id: chatid.to_string(), 449 | }; 450 | 451 | let chat = self.bots[&botid].get_chat(getchat); 452 | if chat.is_none() { 453 | return Ok(0); 454 | } 455 | 456 | if chat.as_ref().unwrap().description.is_none() { 457 | return Ok(0); 458 | } 459 | 460 | let chat_description = chat.unwrap().description.unwrap(); 461 | match encode_replace(&chat_description) { 462 | Ok(encoded) => { 463 | let mut dest = dest.into_sized_buffer(size); 464 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 465 | Ok(1) 466 | } 467 | Err(err) => { 468 | error!( 469 | "[get_chat_description] Failed encoding {:?} \n {:?}", 470 | chat_description, err 471 | ); 472 | Ok(0) 473 | } 474 | } 475 | } 476 | 477 | #[native(name = "TG_BanChatMember")] 478 | pub fn ban_chat_member( 479 | &self, 480 | _amx: &Amx, 481 | botid: usize, 482 | chatid: AmxString, 483 | userid: AmxString, 484 | until_date: i32, 485 | revoke_messages: bool, 486 | ) -> AmxResult { 487 | let time = if until_date < 0 { 488 | None 489 | } else { 490 | Some(until_date) 491 | }; 492 | let banchatmember = BanChatMember { 493 | chat_id: chatid.to_string(), 494 | user_id: userid.to_string(), 495 | until_date: time, 496 | revoke_messages, 497 | }; 498 | self.bots[&botid].ban_chat_member(banchatmember); 499 | Ok(1) 500 | } 501 | 502 | #[native(name = "TG_UnbanChatMember")] 503 | pub fn unban_chat_member( 504 | &self, 505 | _amx: &Amx, 506 | botid: usize, 507 | chatid: AmxString, 508 | userid: AmxString, 509 | only_if_banned: bool, 510 | ) -> AmxResult { 511 | let unbanchatmember = UnbanChatMember { 512 | chat_id: chatid.to_string(), 513 | user_id: userid.to_string(), 514 | only_if_banned, 515 | }; 516 | self.bots[&botid].unban_chat_member(unbanchatmember); 517 | Ok(1) 518 | } 519 | 520 | // Deprecated Natives 521 | #[native(name = "TGGetBotUserId")] 522 | pub fn get_bot_user_id_old(&self, _amx: &Amx, botid: usize) -> AmxResult { 523 | warn!("TGGetBotUserId is deprecated use TG_GetBotUserID instead"); 524 | 525 | if !self.bots.contains_key(&botid) { 526 | error!("Invalid bot id {} passed", botid); 527 | return Ok(-1); 528 | } 529 | if let Ok(userid) = self.bots[&botid].user_id.parse() { 530 | Ok(userid) 531 | } else { 532 | error!("Couldn't convert userid into int32, use TG_GetBotUserID instead of deprecated TGGetBotUserId"); 533 | Ok(-1) 534 | } 535 | } 536 | 537 | #[native(name = "TGGetUserChatStatus")] 538 | pub fn get_user_status_old( 539 | &self, 540 | _amx: &Amx, 541 | botid: usize, 542 | userid: i32, 543 | chatid: AmxString, 544 | ) -> AmxResult { 545 | warn!("TGGetUserChatStatus is deprecated use TG_GetUserChatStatus instead"); 546 | 547 | if !self.bots.contains_key(&botid) { 548 | error!("**[TGConnector] Error Invalid bot id {} passed", botid); 549 | return Ok(0); 550 | } 551 | 552 | let getchatmember = GetChatMember { 553 | user_id: userid.to_string(), 554 | chat_id: chatid.to_string(), 555 | }; 556 | let chatmember = self.bots[&botid].get_chat_member(getchatmember); 557 | if chatmember.is_none() { 558 | return Ok(0); 559 | } 560 | let chatmember = chatmember.unwrap(); 561 | match chatmember.status.as_ref() { 562 | "creator" => Ok(1), 563 | "adminstrator" => Ok(2), 564 | "member" => Ok(3), 565 | "restricted" => Ok(4), 566 | "left" => Ok(5), 567 | "kicked" => Ok(6), 568 | _ => Ok(0), 569 | } 570 | } 571 | 572 | #[native(name = "TGGetUserNameFromId")] 573 | pub fn get_username_from_id_old( 574 | &self, 575 | _amx: &Amx, 576 | botid: usize, 577 | userid: i32, 578 | chatid: AmxString, 579 | dest: UnsizedBuffer, 580 | size: usize, 581 | ) -> AmxResult { 582 | warn!("TGGetUserNameFromId is deprecated use TG_GetUserNameFromID instead"); 583 | 584 | if !self.bots.contains_key(&botid) { 585 | error!("Invalid bot id {} passed", botid); 586 | return Ok(0); 587 | } 588 | 589 | let getchatmember = GetChatMember { 590 | user_id: userid.to_string(), 591 | chat_id: chatid.to_string(), 592 | }; 593 | let chatmember = self.bots[&botid].get_chat_member(getchatmember); 594 | if chatmember.is_none() { 595 | return Ok(0); 596 | } 597 | let chatmember = chatmember.unwrap(); 598 | let username = &chatmember.user.username; 599 | if *username == None { 600 | return Ok(0); 601 | } 602 | match encode_replace(username.as_ref().unwrap()) { 603 | Ok(encoded) => { 604 | let mut dest = dest.into_sized_buffer(size); 605 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 606 | Ok(1) 607 | } 608 | Err(err) => { 609 | error!( 610 | "[get_username_from_id] Failed encoding {:?} \n {:?}", 611 | username.as_ref().unwrap(), 612 | err 613 | ); 614 | Ok(0) 615 | } 616 | } 617 | } 618 | 619 | #[native(name = "TGGetDisplayNameFromId")] 620 | pub fn get_display_name_from_id_old( 621 | &self, 622 | _amx: &Amx, 623 | botid: usize, 624 | userid: i32, 625 | chatid: AmxString, 626 | dest: UnsizedBuffer, 627 | size: usize, 628 | ) -> AmxResult { 629 | warn!("TGGetDisplayNameFromId is deprecated use TG_GetDisplayNameFromID instead"); 630 | if !self.bots.contains_key(&botid) { 631 | error!("Invalid bot id {} passed", botid); 632 | return Ok(0); 633 | } 634 | 635 | let getchatmember = GetChatMember { 636 | user_id: userid.to_string(), 637 | chat_id: chatid.to_string(), 638 | }; 639 | 640 | let chatmember = self.bots[&botid].get_chat_member(getchatmember); 641 | if chatmember.is_none() { 642 | return Ok(0); 643 | } 644 | let chatmember = chatmember.unwrap(); 645 | let displayname = match &chatmember.user.last_name { 646 | None => chatmember.user.first_name, 647 | Some(lastname) => chatmember.user.first_name + " " + lastname, 648 | }; 649 | match encode_replace(&displayname) { 650 | Ok(encoded) => { 651 | let mut dest = dest.into_sized_buffer(size); 652 | let _ = samp::cell::string::put_in_buffer(&mut dest, &encoded); 653 | Ok(1) 654 | } 655 | Err(err) => { 656 | error!( 657 | "get_display_name_from_id] Failed encoding {:?} \n {:?}", 658 | displayname, err 659 | ); 660 | Ok(0) 661 | } 662 | } 663 | } 664 | } 665 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------