Skip to content

Commit

Permalink
Update to tdlib 1.7.0
Browse files Browse the repository at this point in the history
  • Loading branch information
felixgborrego committed May 11, 2021
1 parent 22961df commit 49c6424
Show file tree
Hide file tree
Showing 9 changed files with 166 additions and 58 deletions.
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
[package]
name = "telegram-tracker"
version = "0.1.4"
version = "0.1.5"
authors = ["Felix <felix.g.borrego@gmail.com>"]
readme = "README.md"
edition = "2018"

[dependencies]
telegram-client = "1.6.3"
rtdlib = { version = "=1.6.5", features = [ "sys" ] }

telegram-client = { version="1.7.0"}
rtdlib = { version = "=1.7.0", features = [ "sys" ] }
log = "0.4"
simple_logger = "1.3"
toolkit = "0.1"
colored = "1.9"
regex = "1"
clap = "3.0.0-beta.2"
chrono = "0.4"
futures = "0.3"
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ RUN apt install -y g++ ccache openssl cmake gperf make git libssl-dev libreadlin
RUN openssl version
RUN uname -a
WORKDIR /
RUN git clone --depth 1 --branch v1.6.0 https://github.com/tdlib/td.git /td
RUN git clone --depth 1 --branch v1.7.0 https://github.com/tdlib/td.git /td
WORKDIR /td
RUN mkdir build
WORKDIR build
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ If you somehow are still interested, you will get something like this, with the

* Get your Telegram API and Hash — which can be obtained at https://my.telegram.org.

Other than the `crate` declared at `Cargo.toml`, this crate needs `tdjson 1.6.0 dylib` in your path
Other than the `crate` declared at `Cargo.toml`, this crate needs `tdjson 1.7.0 dylib` in your path
for building and running your application.

* Install the dependencies:
`brew install gperf cmake openssl`

* Add the libtdjson dynamic library to path (warning: it must be 1.6.0):
* Add the libtdjson dynamic library to path (warning: it must be 1.7.0).
You can compile it following the [Tdlib build instructions](https://github.com/tdlib/td#building)
```
export LD_LIBRARY_PATH=$PWD/lib/
```
Expand All @@ -28,7 +29,7 @@ LD_LIBRARY_PATH=lib cargo build --release
```

* Build with Docker
```docker build -t telegram-tracker:0.1.2 .```
```docker build -t telegram-tracker:0.1.5 .```

## Run
```
Expand Down
2 changes: 1 addition & 1 deletion lib/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Telegram precompiled libs following
# Telegram precompiled 1.7.0 libs following

Build and install following https://github.com/tdlib/td#installing-dependencies
```
Expand Down
40 changes: 40 additions & 0 deletions src/forward_stdin.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use std::io::{self, BufRead};

use futures::executor::block_on;
use log::info;
use rtdlib::types::*;
//use rtdlib::*;
use telegram_client::api::aasync::AsyncApi;
use telegram_client::api::Api;

const TELEGRAM_START_MSG: &str = "TELEGRAM BOT<<<";
/// Read stdin and forward to channel
pub fn forward_stdin_to_channel_id(api: Api, chat_id: i64) {
info!("Listening stdin to forward to channel... {}", chat_id);
let api = AsyncApi::new(api);
let stdin = io::stdin();

for line in stdin.lock().lines() {
let msg_to_send = line.unwrap().trim().to_owned();
if msg_to_send.starts_with(TELEGRAM_START_MSG) {
let msg_to_send = msg_to_send.replace(TELEGRAM_START_MSG, "");
let result = block_on(send_msg(&api, chat_id, msg_to_send));
}
}
}

async fn send_msg(api: &AsyncApi, chat_id: i64, msg_to_send: String) {
let msg_content = InputMessageContent::InputMessageText(
InputMessageText::builder()
.text(FormattedText::builder().text(msg_to_send).build())
.clear_draft(true)
.build(),
);

let msg: SendMessage = SendMessage::builder()
.chat_id(chat_id)
.input_message_content(msg_content)
.build();

api.send_message(msg).await.unwrap();
}
44 changes: 31 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use clap::{AppSettings, Clap};
use log::LevelFilter;
use simple_logger::SimpleLogger;

use std::thread;
mod forward_stdin;
mod telegram;
mod tgfn;
mod thelp;
mod telegram;

#[derive(Clap)]
#[clap(
version = "0.1.3",
author = "Felix G. Borrego <felix.g.borrego@gmail.com>"
version = "0.1.5",
author = "Felix G. Borrego <felix.g.borrego@gmail.com>"
)]
#[clap(setting = AppSettings::ColoredHelp)]
struct Opts {
Expand All @@ -23,41 +24,58 @@ struct Opts {
print_outgoing: String,
#[clap(long)]
follow_channel_id: Option<String>,
#[clap(long)]
forward_stdin_to_channel_id: Option<String>,
}

fn main(){
fn main() {
const VERSION: &'static str = env!("CARGO_PKG_VERSION");

let opts: Opts = Opts::parse();

SimpleLogger::new()
.with_level(LevelFilter::Info)
.with_module_level("telegram_client::api", LevelFilter::Info)
.with_module_level("telegram_client::handler", LevelFilter::Info)
.with_module_level("telegram_client::handler", LevelFilter::Off)
.init()
.unwrap();


let channel_id = opts.follow_channel_id.map(|id| format!("-100{}", id).parse::<i64>().expect("Expected a valid chat_id"));
let channel_id = opts.follow_channel_id.map(|id| {
format!("-100{}", id)
.parse::<i64>()
.expect("Expected a valid chat_id")
});
let forward_channel_id = opts.forward_stdin_to_channel_id.map(|id| {
format!("-100{}", id)
.parse::<i64>()
.expect("Expected a valid chat_id")
});

if let Some(id) = channel_id {
println!(
"Starting Telegram Tracker {} following channel {} for: {}, api key: {}",
VERSION,id, opts.phone, opts.telegram_api_id
VERSION, id, opts.phone, opts.telegram_api_id
);
} else {
println!(
"Starting Telegram Tracker {} for: {}, api key: {}", VERSION,
opts.phone, opts.telegram_api_id
"Starting Telegram Tracker {} for: {}, api key: {}",
VERSION, opts.phone, opts.telegram_api_id
);
}


telegram::start(
let api = telegram::start(
opts.phone,
opts.telegram_api_id,
opts.telegram_api_hash,
opts.print_outgoing.parse().expect("It must be a bool"),
channel_id,
);

if let Some(channel_id) = forward_channel_id {
println!("Stdin to Telegram channel {} is ENABLED", channel_id);
forward_stdin::forward_stdin_to_channel_id(api, channel_id);
} else {
println!("Stdin to Telegram is disabled.");
thread::park();
}
}
110 changes: 79 additions & 31 deletions src/telegram.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
use std::fs::File;
use std::thread;

use chrono;
use chrono::Local;
use colored::Colorize;
use log::{debug, error, info, warn};
use rtdlib::types::*;
use rtdlib::types::MessageContent::*;
use rtdlib::types::*;
use telegram_client::api::aevent::EventApi;
use telegram_client::api::Api;
use telegram_client::client::Client;

use telegram_client::api::aevent::EventApi;
use crate::{thelp, tgfn};
use crate::{tgfn, thelp};

fn on_new_message(event_info: String, message: &Message, only_channel_id: &Option<i64>) {
if message.is_outgoing() {
Expand All @@ -34,25 +35,43 @@ fn on_new_message(event_info: String, message: &Message, only_channel_id: &Optio
}

if *only_channel_id == Some(message.chat_id()) {
on_new_message_in_room(event_info, &msg_text, message.chat_id(), message.id(), message.sender_user_id());
on_new_message_in_room(
event_info,
&msg_text,
message.chat_id(),
message.id(),
message.sender(),
);
} else {
info!("Ignoring message chat: {}; sender_id:{}; message_id: {}, time:{:?}; event_info: {}, msg: {}",
message.chat_id(),
message.sender_user_id(),
message.id(),
Local::now().to_rfc3339(),
event_info,
&msg_text
info!(
"Ignoring message chat: {}; message_id: {}, time:{:?}; event_info: {}, msg: {}",
message.chat_id(),
message.id(),
Local::now().to_rfc3339(),
event_info,
&msg_text
);
}
}

fn on_new_message_in_room(event_info: String, msg: &String, chat_id: i64, message_id: i64, sender_user_id: i64) {
fn on_new_message_in_room(
event_info: String,
msg: &String,
chat_id: i64,
message_id: i64,
sender: &MessageSender,
) {
let sender_id = match sender {
MessageSender::_Default(d) => -1,
MessageSender::Chat(c) => c.chat_id(),
MessageSender::User(u) => u.user_id(),
};

let line_msg = str::replace(msg, "\n", "; ");
println!(
"### chat: {};sender_id: {};message_id: {};time: {:?};event_info: {}; msg:==> {}",
chat_id,
sender_user_id,
sender_id,
message_id,
Local::now().to_rfc3339(),
event_info,
Expand All @@ -66,8 +85,29 @@ pub fn start(
telegram_api_hash: String,
print_outgoing: bool,
follow_channel: Option<i64>,
) -> Api {
let (mut client, api) = config();
thread::spawn(move || {
start_telegram_tracking(
client,
phone,
telegram_api_id,
telegram_api_hash,
print_outgoing,
follow_channel,
);
});
api
}

fn start_telegram_tracking(
mut client: Client,
phone: String,
telegram_api_id: String,
telegram_api_hash: String,
print_outgoing: bool,
follow_channel: Option<i64>,
) {
let mut client = config();
let listener = client.listener();

listener.on_update_authorization_state(move |(api, update)| {
Expand Down Expand Up @@ -184,7 +224,10 @@ pub fn start(
429 => thelp::wait_too_many_requests(api, &message),
3 => {
let result = api.get_chats(GetChats::builder().limit(100).build());
info!("⚠️ Chat request not found, trying to refresh channels...{:?}", result);
info!(
"⚠️ Chat request not found, trying to refresh channels...{:?}",
result
);
}
_ => thelp::unknown(code, &message),
};
Expand All @@ -206,7 +249,9 @@ pub fn start(
info!(
"Receive new chat, title: '{}', id: {}, title: {}",
chat.title(),
chat.id(), chat.title());
chat.id(),
chat.title()
);

if follow_channel == Some(chat.id()) {
info!("📡 Found the required chat, opening...");
Expand Down Expand Up @@ -234,7 +279,11 @@ pub fn start(
debug!("Ignoring outgoing message ");
return Ok(());
}
on_new_message("on_update_new_message".to_string(), message, &follow_channel);
on_new_message(
"on_update_new_message".to_string(),
message,
&follow_channel,
);
Ok(())
});

Expand All @@ -246,21 +295,13 @@ pub fn start(
Ok(())
});

listener.on_update_have_pending_notifications(|(_, _)| {
Ok(())
});
listener.on_update_have_pending_notifications(|(_, _)| Ok(()));

listener.on_update_user(|(_, _)| {
Ok(())
});
listener.on_update_user(|(_, _)| Ok(()));

listener.on_update_have_pending_notifications(|(_, _)| {
Ok(())
});
listener.on_update_have_pending_notifications(|(_, _)| Ok(()));

listener.on_update_unread_chat_count(|(_, _)| {
Ok(())
});
listener.on_update_unread_chat_count(|(_, _)| Ok(()));

listener.on_update_selected_background(|_| Ok(()));

Expand All @@ -270,12 +311,19 @@ pub fn start(
fn open_channel(follow_channel: &Option<i64>, api: &EventApi) {
if let Some(channel_id) = &follow_channel {
info!("📡 Opening channel to follow...");
let option_value: OptionValueBoolean = OptionValueBoolean::builder().value(true).build();
api.set_option(
SetOption::builder()
.name("online")
.value(OptionValue::Boolean(option_value)),
);

let _ = api.open_chat(OpenChat::builder().chat_id(*channel_id).build());
}
}

// Configure client
fn config() -> Client {
fn config() -> (Client, Api) {
// Log File
let log_file = toolkit::path::root_dir().join("telegram_logs.log");
if log_file.exists() {
Expand All @@ -290,5 +338,5 @@ fn config() -> Client {
let mut client = Client::new(api.clone());
client.warn_unregister_listener(false); // No show errors for unregistered listeners

client
(client, api)
}
Loading

0 comments on commit 49c6424

Please sign in to comment.