Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add InlineSend #256

Merged
merged 5 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions lib/grammers-client/examples/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use grammers_client::{Client, Config, SignInError};
use simple_logger::SimpleLogger;
use std::env;
use std::io::{self, BufRead as _, Write as _};
use tokio::runtime;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

Expand All @@ -35,7 +34,8 @@ fn prompt(message: &str) -> Result<String> {
Ok(line)
}

async fn async_main() -> Result<()> {
#[tokio::main]
Lonami marked this conversation as resolved.
Show resolved Hide resolved
async fn main() -> Result<()> {
SimpleLogger::new()
.with_level(log::LevelFilter::Debug)
.init()
Expand Down Expand Up @@ -103,11 +103,3 @@ async fn async_main() -> Result<()> {

Ok(())
}

fn main() -> Result<()> {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}
14 changes: 3 additions & 11 deletions lib/grammers-client/examples/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ use grammers_client::{Client, Config, SignInError};
use mime::Mime;
use mime_guess::mime;
use simple_logger::SimpleLogger;
use tokio::runtime;

use grammers_client::session::Session;
use grammers_client::types::Media::{Contact, Document, Photo, Sticker};
use grammers_client::types::*;
use grammers_client::types::{Downloadable, Media};

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

const SESSION_FILE: &str = "downloader.session";

async fn async_main() -> Result<()> {
#[tokio::main]
async fn main() -> Result<()> {
SimpleLogger::new()
.with_level(log::LevelFilter::Info)
.init()
Expand Down Expand Up @@ -125,14 +125,6 @@ async fn async_main() -> Result<()> {
Ok(())
}

fn main() -> Result<()> {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}

fn get_file_extension(media: &Media) -> String {
match media {
Photo(_) => ".jpg".to_string(),
Expand Down
37 changes: 8 additions & 29 deletions lib/grammers-client/examples/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@
//! cargo run --example echo -- BOT_TOKEN
//! ```

use futures_util::future::{select, Either};
use grammers_client::session::Session;
use grammers_client::{Client, Config, InitParams, Update};
use simple_logger::SimpleLogger;
use std::env;
use std::pin::pin;
use tokio::{runtime, task};
use tokio::task;

type Result = std::result::Result<(), Box<dyn std::error::Error>>;

Expand All @@ -35,7 +33,8 @@ async fn handle_update(client: Client, update: Update) -> Result {
Ok(())
}

async fn async_main() -> Result {
#[tokio::main]
async fn main() -> Result {
SimpleLogger::new()
.with_level(log::LevelFilter::Debug)
.init()
Expand Down Expand Up @@ -68,30 +67,18 @@ async fn async_main() -> Result {

println!("Waiting for messages...");

// This code uses `select` on Ctrl+C to gracefully stop the client and have a chance to
// This code uses `tokio::select!` on Ctrl+C to gracefully stop the client and have a chance to
Lonami marked this conversation as resolved.
Show resolved Hide resolved
// save the session. You could have fancier logic to save the session if you wanted to
// (or even save it on every update). Or you could also ignore Ctrl+C and just use
// `let update = client.next_update().await?`.
//
// Using `tokio::select!` would be a lot cleaner but add a heavy dependency,
// so a manual `select` is used instead by pinning async blocks by hand.
loop {
let update = {
let exit = pin!(async { tokio::signal::ctrl_c().await });
let upd = pin!(async { client.next_update().await });

match select(exit, upd).await {
Either::Left(_) => None,
Either::Right((u, _)) => Some(u),
}
};

let update = match update {
None => break,
Some(u) => u?,
let update = tokio::select! {
_ = tokio::signal::ctrl_c() => break,
upd = client.next_update() => upd?
};

let handle = client.clone();

task::spawn(async move {
match handle_update(handle, update).await {
Ok(_) => {}
Expand All @@ -104,11 +91,3 @@ async fn async_main() -> Result {
client.session().save_to_file(SESSION_FILE)?;
Ok(())
}

fn main() -> Result {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}
20 changes: 6 additions & 14 deletions lib/grammers-client/examples/inline-pagination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use grammers_client::session::Session;
use grammers_client::{button, reply_markup, Client, Config, InputMessage, Update};
use simple_logger::SimpleLogger;
use std::env;
use tokio::{runtime, task};
use tokio::task;

type Result = std::result::Result<(), Box<dyn std::error::Error>>;

Expand Down Expand Up @@ -103,7 +103,8 @@ async fn handle_update(_client: Client, update: Update) -> Result {
Ok(())
}

async fn async_main() -> Result {
#[tokio::main]
async fn main() -> Result {
SimpleLogger::new()
.with_level(log::LevelFilter::Debug)
.init()
Expand Down Expand Up @@ -145,10 +146,9 @@ async fn async_main() -> Result {

let handle = client.clone();
task::spawn(async move {
match handle_update(handle, update).await {
Ok(_) => {}
Err(e) => eprintln!("Error handling updates!: {e}"),
}
handle_update(handle, update).await.unwrap_or_else(|e| {
eprintln!("Error handling updates!: {e}")
});
});
}
}
Expand All @@ -158,11 +158,3 @@ async fn async_main() -> Result {
client.session().save_to_file(SESSION_FILE)?;
Ok(())
}

fn main() -> Result {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}
12 changes: 2 additions & 10 deletions lib/grammers-client/examples/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
use grammers_client::session::Session;
use grammers_client::{Client, Config};
use grammers_tl_types as tl;
use tokio::runtime;

type Result = std::result::Result<(), Box<dyn std::error::Error>>;

async fn async_main() -> Result {
#[tokio::main]
async fn main() -> Result {
println!("Connecting to Telegram...");
let client = Client::connect(Config {
session: Session::load_file_or_create("ping.session")?,
Expand All @@ -28,11 +28,3 @@ async fn async_main() -> Result {

Ok(())
}

fn main() -> Result {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}
12 changes: 2 additions & 10 deletions lib/grammers-client/examples/reconnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use grammers_client::session::Session;
use grammers_client::{Client, Config, InitParams, ReconnectionPolicy};
use std::ops::ControlFlow;
use std::time::Duration;
use tokio::runtime;

type Result = std::result::Result<(), Box<dyn std::error::Error>>;

Expand All @@ -26,7 +25,8 @@ impl ReconnectionPolicy for MyPolicy {
}
}

async fn async_main() -> Result {
#[tokio::main]
async fn main() -> Result {
println!("Connecting to Telegram...");
let client = Client::connect(Config {
session: Session::load_file_or_create("ping.session")?,
Expand All @@ -53,11 +53,3 @@ async fn async_main() -> Result {
}
}
}

fn main() -> Result {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async_main())
}
8 changes: 4 additions & 4 deletions lib/grammers-client/src/client/bots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,15 @@ impl Client {
let message: InputMessage = input_message.into();
let entities = parse_mention_entities(self, message.entities);
let result = self
.invoke(&tl::functions::messages::EditInlineBotMessage {
id: message_id,
.invoke_in_dc(&tl::functions::messages::EditInlineBotMessage {
id: message_id.clone(),
message: Some(message.text),
media: message.media,
entities,
no_webpage: !message.link_preview,
reply_markup: message.reply_markup,
invert_media: false,
})
invert_media: message.invert_media,
}, message_id.dc_id())
.await?;
Ok(result)
}
Expand Down
6 changes: 3 additions & 3 deletions lib/grammers-client/src/client/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ impl Client {
send_as: None,
noforwards: false,
update_stickersets_order: false,
invert_media: false,
invert_media: message.invert_media,
quick_reply_shortcut: None,
effect: None,
})
Expand Down Expand Up @@ -536,7 +536,7 @@ impl Client {
send_as: None,
noforwards: false,
update_stickersets_order: false,
invert_media: false,
invert_media: message.invert_media,
quick_reply_shortcut: None,
effect: None,
})
Expand Down Expand Up @@ -583,7 +583,7 @@ impl Client {
let entities = parse_mention_entities(self, new_message.entities);
self.invoke(&tl::functions::messages::EditMessage {
no_webpage: !new_message.link_preview,
invert_media: false,
invert_media: new_message.invert_media,
peer: chat.into().to_input_peer(),
id: message_id,
message: Some(new_message.text),
Expand Down
19 changes: 4 additions & 15 deletions lib/grammers-client/src/client/updates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@

use super::Client;
use crate::types::{ChatMap, Update};
use futures_util::future::{select, Either};
pub use grammers_mtsender::{AuthorizationError, InvocationError};
use grammers_session::channel_id;
pub use grammers_session::{PrematureEndReason, UpdateState};
use grammers_tl_types as tl;
use std::pin::pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::time::sleep_until;
Expand Down Expand Up @@ -72,7 +70,7 @@ impl Client {
///
/// ```
///
/// P.S. To receive updateBotInlineSend, go to [@BotFather](https://t.me/BotFather), select your bot and click "Bot Settings", then "Inline Feedback" and select probability.
/// P.S. If you don't receive updateBotInlineSend, go to [@BotFather](https://t.me/BotFather), select your bot and click "Bot Settings", then "Inline Feedback" and select probability.
///
pub async fn next_raw_update(
&self,
Expand Down Expand Up @@ -181,18 +179,9 @@ impl Client {
continue;
}

let step = {
let sleep = pin!(async { sleep_until(deadline.into()).await });
let step = pin!(async { self.step().await });

match select(sleep, step).await {
Either::Left(_) => None,
Either::Right((step, _)) => Some(step),
}
};

if let Some(step) = step {
step?;
tokio::select! {
Lonami marked this conversation as resolved.
Show resolved Hide resolved
_ = sleep_until(deadline.into()) => (),
step = self.step() => step?
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/grammers-client/src/parsers/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ pub fn parse_html_message(message: &str) -> (String, Vec<tl::enums::MessageEntit
tl::types::MessageEntityMentionName {
offset,
length,
user_id: user_id,
user_id,
}
.into(),
);
Expand All @@ -134,7 +134,7 @@ pub fn parse_html_message(message: &str) -> (String, Vec<tl::enums::MessageEntit
tl::types::MessageEntityTextUrl {
offset,
length,
url: url,
url,
}
.into(),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/grammers-client/src/parsers/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub fn parse_markdown_message(message: &str) -> (String, Vec<tl::enums::MessageE
tl::types::MessageEntityMentionName {
offset,
length,
user_id: user_id,
user_id,
}
.into(),
);
Expand Down
10 changes: 10 additions & 0 deletions lib/grammers-client/src/types/inline.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

pub mod query;
pub mod send;
Loading
Loading