Skip to content

Commit

Permalink
Add InlineSend and more cleanup (#256)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimentyy authored Aug 13, 2024
1 parent 49aa302 commit dbdd88c
Show file tree
Hide file tree
Showing 15 changed files with 198 additions and 70 deletions.
2 changes: 1 addition & 1 deletion lib/grammers-client/examples/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ 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>>;

Expand Down
19 changes: 6 additions & 13 deletions lib/grammers-client/examples/echo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,24 +71,17 @@ async fn async_main() -> Result {
// This code uses `select` on Ctrl+C to gracefully stop the client and have a chance to
// 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?`.
// `while let Some(updates) = client.next_updates().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 });
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 = match select(exit, upd).await {
Either::Left(_) => break,
Either::Right((u, _)) => u?,
};

let handle = client.clone();
Expand Down
33 changes: 16 additions & 17 deletions lib/grammers-client/examples/inline-pagination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
//! how much data a button's payload can contain, and to keep it simple, we're storing it inline
//! in decimal, so the numbers can't get too large).
use futures_util::future::{select, Either};
use grammers_client::session::Session;
use grammers_client::{button, reply_markup, Client, Config, InputMessage, Update};
use simple_logger::SimpleLogger;
use std::env;
use std::pin::pin;
use tokio::{runtime, task};

type Result = std::result::Result<(), Box<dyn std::error::Error>>;
Expand Down Expand Up @@ -132,26 +134,23 @@ async fn async_main() -> Result {

println!("Waiting for messages...");
loop {
tokio::select! {
let exit = pin!(async { tokio::signal::ctrl_c().await });
let upd = pin!(async { client.next_update().await });

// A way to exit the loop
_ = tokio::signal::ctrl_c() => {
let update = match select(exit, upd).await {
Either::Left(_) => {
println!("Exiting...");
break
},

res = client.next_update() => {
let update = res?;

let handle = client.clone();
task::spawn(async move {
match handle_update(handle, update).await {
Ok(_) => {}
Err(e) => eprintln!("Error handling updates!: {e}"),
}
});
break;
}
}
Either::Right((u, _)) => u?,
};

let handle = client.clone();
task::spawn(async move {
if let Err(e) = handle_update(handle, update).await {
eprintln!("Error handling updates!: {e}")
}
});
}

println!("Saving session file...");
Expand Down
21 changes: 12 additions & 9 deletions lib/grammers-client/src/client/bots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,18 @@ 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,
message: Some(message.text),
media: message.media,
entities,
no_webpage: !message.link_preview,
reply_markup: message.reply_markup,
invert_media: false,
})
.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: 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
18 changes: 6 additions & 12 deletions lib/grammers-client/src/client/updates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,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 +181,12 @@ impl Client {
continue;
}

let step = {
let sleep = pin!(async { sleep_until(deadline.into()).await });
let step = pin!(async { self.step().await });
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?;
match select(sleep, step).await {
Either::Left(_) => {}
Either::Right((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;
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
// <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.
use super::{Chat, ChatMap, User};

use super::super::{Chat, ChatMap, User};
use crate::{client::Client, utils::generate_random_id, InputMessage};
use grammers_mtsender::InvocationError;
use grammers_tl_types as tl;
Expand Down Expand Up @@ -52,7 +53,7 @@ impl InlineQuery {
}
}

// User that sent the query.
/// User that sent the query
pub fn sender(&self) -> &User {
match self
.chats
Expand All @@ -69,12 +70,12 @@ impl InlineQuery {
}
}

// The text of the inline query.
/// The text of the inline query.
pub fn text(&self) -> &str {
self.raw.query.as_str()
}

// The offset of the inline query.
/// The offset of the inline query.
pub fn offset(&self) -> &str {
self.raw.offset.as_str()
}
Expand All @@ -96,6 +97,16 @@ impl InlineQuery {
client: self.client.clone(),
}
}

/// Type of the chat from which the inline query was sent.
pub fn peer_type(&self) -> Option<tl::enums::InlineQueryPeerType> {
self.raw.peer_type.clone()
}

/// Query ID
pub fn query_id(&self) -> i64 {
self.raw.query_id
}
}

impl Answer {
Expand Down Expand Up @@ -217,7 +228,7 @@ impl From<Article> for InlineResult {
send_message: tl::enums::InputBotInlineMessage::Text(
tl::types::InputBotInlineMessageText {
no_webpage: !article.input_message.link_preview,
invert_media: false,
invert_media: article.input_message.invert_media,
message: article.input_message.text,
entities: Some(article.input_message.entities),
reply_markup: article.input_message.reply_markup,
Expand All @@ -232,7 +243,9 @@ impl fmt::Debug for InlineQuery {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InlineQuery")
.field("text", &self.text())
.field("peer_type", &self.peer_type())
.field("sender", &self.sender())
.field("query_id", &self.query_id())
.finish()
}
}
Expand Down
99 changes: 99 additions & 0 deletions lib/grammers-client/src/types/inline/send.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// 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.

use crate::types::{Chat, User};
use crate::{ChatMap, Client, InputMessage};
use grammers_mtsender::InvocationError;
use grammers_tl_types as tl;
use std::fmt;
use std::sync::Arc;

#[derive(Clone)]
pub struct InlineSend {
raw: tl::types::UpdateBotInlineSend,
client: Client,
chats: Arc<ChatMap>,
}

impl InlineSend {
pub fn from_raw(
query: tl::types::UpdateBotInlineSend,
client: &Client,
chats: &Arc<ChatMap>,
) -> Self {
Self {
raw: query,
client: client.clone(),
chats: chats.clone(),
}
}

/// The query that was used to obtain the result.
pub fn text(&self) -> &str {
self.raw.query.as_str()
}

/// The user that chose the result.
pub fn sender(&self) -> &User {
match self
.chats
.get(
&tl::types::PeerUser {
user_id: self.raw.user_id,
}
.into(),
)
.unwrap()
{
Chat::User(user) => user,
_ => unreachable!(),
}
}

/// The unique identifier for the result that was chosen
pub fn result_id(&self) -> &str {
self.raw.id.as_str()
}

/// Identifier of sent inline message.
/// Available only if there is an inline keyboard attached.
/// Will be also received in callback queries and can be used to edit the message.
pub fn msg_id(&self) -> Option<tl::enums::InputBotInlineMessageId> {
self.raw.msg_id.clone()
}

/// Edits this inline message.
///
/// **This method will return Ok(None) if message id is None (e.g. if an inline keyboard is not attached)**
pub async fn edit_msg(
&self,
input_message: impl Into<InputMessage>,
) -> Result<Option<bool>, InvocationError> {
let msg_id = match self.raw.msg_id.clone() {
None => return Ok(None),
Some(msg_id) => msg_id,
};

Ok(Some(
self.client
.edit_inline_message(msg_id, input_message)
.await?,
))
}
}

impl fmt::Debug for InlineSend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("InlineSend")
.field("text", &self.text())
.field("sender", &self.sender())
.field("result_id", &self.result_id())
.field("msg_id", &self.msg_id())
.finish()
}
}
Loading

0 comments on commit dbdd88c

Please sign in to comment.