Skip to content

Commit

Permalink
inline partial complete
Browse files Browse the repository at this point in the history
  • Loading branch information
orzklv committed Nov 16, 2023
1 parent dd986e8 commit f730657
Show file tree
Hide file tree
Showing 12 changed files with 211 additions and 21 deletions.
30 changes: 30 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ log = "0.4"
pretty_env_logger = "0.5.0"
tokio = { version = "1.8", features = ["rt-multi-thread", "macros"] }
url = "2.4.1"
crates_io_api = "0.8.2"
uuid = { version = "1.5.0", features = ["v4"] }
9 changes: 3 additions & 6 deletions src/functions/about.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{utils::kbmng::Keyboard, hooks};
use crate::{hooks, utils::kbmng::Keyboard};
use teloxide::{
payloads::SendMessageSetters,
prelude::*,
Expand All @@ -13,18 +13,15 @@ Bizning botimiz aktiv tarzda shakllantirib boriladi. Buning ustida esa bir necha

pub fn keyboard() -> InlineKeyboardMarkup {
let mut keyboard = Keyboard::new();
keyboard.url(
"Ochiq Havolalar",
"https://github.com/rust-lang-uz/rustina",
)
keyboard.url("Ochiq Havolalar", "https://github.com/rust-lang-uz/rustina")
}

pub async fn command(bot: &Bot, msg: &Message) -> ResponseResult<()> {
if !msg.chat.is_private() {
return {
hooks::is_private(bot, msg).await.unwrap();
Ok(())
}
};
}

bot.send_message(msg.chat.id, TEXT)
Expand Down
88 changes: 88 additions & 0 deletions src/functions/inline.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use crates_io_api::AsyncClient;
use crates_io_api::CratesQuery;
use std::error::Error;
use teloxide::prelude::*;
use teloxide::types::*;

use crate::utils::inmgr::*;

pub async fn inline(
bot: Bot,
crates_client: AsyncClient,
q: InlineQuery,
) -> Result<(), Box<dyn Error + Send + Sync>> {
if q.query.is_empty() {
return {
bot.answer_inline_query(
q.id,
vec![InlineQueryResultArticle::new(
"101",
"Qidirishni boshlang!",
InputMessageContent::Text(
InputMessageContentText::new(NO_INPUT)
.parse_mode(ParseMode::Html)
.disable_web_page_preview(true),
),
)
.reply_markup(err_keyboard())
.into()],
)
.await?;
Ok(())
};
}

let query = CratesQuery::builder()
.search(q.query.clone())
.page(1)
.page_size(50)
.build();

let request = crates_client.crates(query).await.unwrap().crates;

if request.is_empty() {
return {
bot.answer_inline_query(
q.id,
vec![InlineQueryResultArticle::new(
"404",
"Xatolik yuz berdi!",
InputMessageContent::Text(
InputMessageContentText::new(
format!("<b>{} ga oid natija mavjud emas!</b>\n{}",
q.query.clone(), "Iltimos, boshqattan ushbu qidirmoqchi bo'lgan paketingiz yozib qidirib ko'ring!")
)
.parse_mode(ParseMode::Html)
.disable_web_page_preview(true),
),
)
.reply_markup(err_keyboard())
.into()],
)
.await?;
Ok(())
};
}

let mut result: Vec<InlineQueryResult> = Vec::new();

for c in request.iter() {
result.push(InlineQueryResult::Article(
InlineQueryResultArticle::new(
uuid::Uuid::new_v4(),
c.name.clone(),
InputMessageContent::Text(
InputMessageContentText::new(view_generate(c))
.parse_mode(ParseMode::Html)
.disable_web_page_preview(true),
),
)
.description(c.description.clone().unwrap())
.url(url::Url::parse(&format!("https://crates.io/crates/{}", c.id)).unwrap())
.into(),
));
}

bot.answer_inline_query(q.id, result).send().await?;
Ok(())
}
6 changes: 4 additions & 2 deletions src/functions/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
pub mod about;
pub mod help;
pub mod inline;
pub mod rules;
pub mod start;
pub mod about;

pub use teloxide::prelude::*;
pub use inline::inline;

use crate::Command;
use std::error::Error;
use teloxide::prelude::*;

pub async fn commands(
bot: Bot,
Expand Down
7 changes: 2 additions & 5 deletions src/functions/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,15 @@ Iltimos qoidalarga oz bo'lsada vaqt ajratishni unutmang, bu muhim! Ushbu guruhda

pub fn keyboard() -> InlineKeyboardMarkup {
let mut keyboard = Keyboard::new();
keyboard.url(
"Guruhga qaytish",
"https://t.me/rustlanguz",
)
keyboard.url("Guruhga qaytish", "https://t.me/rustlanguz")
}

pub async fn command(bot: &Bot, msg: &Message) -> ResponseResult<()> {
if !msg.chat.is_private() {
return {
hooks::is_private(bot, msg).await.unwrap();
Ok(())
}
};
}

bot.send_message(msg.chat.id, TEXT)
Expand Down
10 changes: 2 additions & 8 deletions src/functions/start.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,8 @@ Sizni ko'rib turganimdan bag'oyatda xursandman. Men O'zbek Rust jamiyati tomonid

pub fn keyboard() -> InlineKeyboardMarkup {
let mut keyboard = Keyboard::new();
keyboard.url(
"Jamiyat",
"https://t.me/rustlanguz",
);
keyboard.url(
"Web Sahifa",
"https://rust-lang.uz",
)
keyboard.url("Jamiyat", "https://t.me/rustlanguz");
keyboard.url("Web Sahifa", "https://rust-lang.uz")
}

pub async fn command(bot: &Bot, msg: &Message) -> ResponseResult<()> {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub enum Command {

pub fn handler() -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>> {
dptree::entry()
// Inline Queries
.branch(Update::filter_inline_query().endpoint(functions::inline))
// Commands
.branch(
Update::filter_message()
Expand Down
8 changes: 8 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crates_io_api::AsyncClient;
use rustina::handler;
use std::error::Error;
use teloxide::prelude::*;
Expand All @@ -9,7 +10,14 @@ async fn main() -> Result<(), Box<dyn Error>> {

let bot = Bot::from_env();

let crates_client = AsyncClient::new(
"Rustina Assistant ([email protected])",
std::time::Duration::from_millis(100),
)
.unwrap();

Dispatcher::builder(bot, handler())
.dependencies(dptree::deps![crates_client])
// If no handler succeeded to handle an update, this closure will be called
.default_handler(|upd| async move {
log::warn!("Unhandled update: {:?}", upd);
Expand Down
60 changes: 60 additions & 0 deletions src/utils/inmgr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use super::kbmng::Keyboard;
use crates_io_api::Crate;
use teloxide::types::*;

pub static NO_INPUT: &str = r#"
<b>Salom foydalanuvchi!</b>
Siz inline rejim ishga tushurdingiz. Ushbu qulaylik yordamida siz crates.io Rust dasturlash tili paketlar registridan web sahifani ishlatmasdan turib telegram o'zida kerakli paketlarni qidirishingiz mumkin! Ushbu qulaylik yozish uchun o'zimizning <a href="https://github.com/rust-lang-uz/crates.ts">API SDK</a> ishlatildi.
Qidirishni boshlash uchun:
<code>@rustaceanbot &lt;nomi&gt;</code>
"#;

pub fn view_generate(c: &Crate) -> String {
let mut result = String::from("<b>🦀 Rust Telegram Cratelari 🦀</b>\n\n");

result.push_str(&format!("📦 <b>Nomi:</b> {}\n", c.name));
result.push_str(&format!(
"🚨 <b>Oxirgi versiya:</b> <code>{}</code>\n",
c.max_version
));
result.push_str(&format!(
"🎚 <b>Yuklab olingan:</b> yaqin orada: <code>{}</code> | hammasi: <code>{}</code>\n",
c.recent_downloads.unwrap(),
c.downloads
));
result.push_str(&format!(
"⌚️ <b>Yaratilgan:</b> <code>{}</code\n>",
c.created_at.naive_local().to_string()
));
result.push_str(&format!(
"📡 <b>Yangilangan:</b> <code>{}</code>\n",
c.updated_at.date_naive().to_string()
));
result.push_str(&format!(
"📰 <b>Ma'lumot:</b> <code>{}{}</code>\n\n",
if c.description.clone().unwrap().len() > 100 {
c.description
.clone()
.unwrap()
.chars()
.take(100)
.collect::<String>()
} else {
c.description.clone().unwrap()
},
if c.description.clone().unwrap().len() > 100 {
"..."
} else {
""
}
));

result
}

pub fn err_keyboard() -> InlineKeyboardMarkup {
let mut keyboard = Keyboard::new();
keyboard.switch_inline_current("Qayta urinib ko'ramizmi?", "rand")
}
9 changes: 9 additions & 0 deletions src/utils/kbmng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ impl Keyboard {
self.get()
}

pub fn switch_inline_current(&mut self, text: &str, query: &str) -> InlineKeyboardMarkup {
self.keyboard
.last_mut()
.unwrap()
.push(InlineKeyboardButton::switch_inline_query_current_chat(text, query));

self.get()
}

/// Add next buttons from new line
pub fn row(&mut self) -> InlineKeyboardMarkup {
self.keyboard.push(vec![]);
Expand Down
1 change: 1 addition & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod inmgr;
pub mod kbmng;

0 comments on commit f730657

Please sign in to comment.