实现 Telegram 中文词法搜索核心与 Bot 查询逻辑 #1

Merged
Zayden-Jung merged 4 commits from codex/01-search-engine into main 2026-12-02 13:09:29 +00:00
6 changed files with 189 additions and 1 deletions
Showing only changes of commit dc9baa4dec - Show all commits
Generated
+7
View File
@@ -2,6 +2,13 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "telefind-bot"
version = "0.1.0"
dependencies = [
"telefind-core",
]
[[package]]
name = "telefind-core"
version = "0.1.0"
+1 -1
View File
@@ -1,5 +1,5 @@
[workspace]
members = ["crates/telefind-core"]
members = ["crates/telefind-core", "crates/telefind-bot"]
resolver = "2"
[workspace.package]
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "telefind-bot"
version.workspace = true
edition.workspace = true
[dependencies]
telefind-core = { path = "../telefind-core" }
+43
View File
@@ -0,0 +1,43 @@
pub(crate) enum Input<'a> {
Ignore,
Help,
Search(telefind_core::Query<'a>),
}
pub(crate) fn parse<'a>(bot: &str, text: &'a str) -> Input<'a> {
let text = text.trim();
if text.is_empty() {
return Input::Ignore;
}
if !text.starts_with('/') {
return Input::Search(telefind_core::Query::new(text));
}
let (command, args) = text.split_once(char::is_whitespace).unwrap_or((text, ""));
let (command, target) = command
.split_once('@')
.map_or((command, None), |(cmd, target)| (cmd, Some(target)));
if target.is_some_and(|name| !name.eq_ignore_ascii_case(bot.trim_start_matches('@'))) {
return Input::Ignore;
}
match (command, args.trim()) {
("/search", "") | ("/help" | "/start", _) => Input::Help,
("/search", query) => Input::Search(telefind_core::Query::new(query)),
("/page", args) => {
let Some((number, text)) = args.split_once(char::is_whitespace) else {
return Input::Help;
};
let mut query = telefind_core::Query::new(text.trim());
let Some(offset) = number
.parse::<usize>()
.ok()
.and_then(|n| n.checked_sub(1))
.and_then(|n| n.checked_mul(query.limit))
else {
return Input::Help;
};
query.offset = offset;
Input::Search(query)
}
_ => Input::Ignore,
}
}
+61
View File
@@ -0,0 +1,61 @@
//! Transport-independent Telegram search interaction. The host supplies
//! incoming text and sends the returned plain-text labels and URL buttons.
mod command;
use telefind_core::{Document, Kind, SearchIndex};
#[derive(Debug, PartialEq)]
pub struct ResultLink {
pub label: String,
pub url: String,
}
#[derive(Debug, PartialEq)]
pub enum Reply {
Ignored,
Help,
Results {
total: usize,
links: Vec<ResultLink>,
},
}
/// Accept a keyword message or /search. The bot username is needed for
/// commands addressed to a particular bot in a group. Use /page N keywords
/// to fetch a later page without storing per-user sessions.
pub fn handle<S: SearchIndex>(index: &S, bot: &str, text: &str) -> Result<Reply, S::Error> {
let request = match command::parse(bot, text) {
command::Input::Ignore => return Ok(Reply::Ignored),
command::Input::Help => return Ok(Reply::Help),
command::Input::Search(query) => query,
};
let page = index.search(&request)?;
Ok(Reply::Results {
total: page.total,
links: page.hits.iter().map(link).collect(),
})
}
fn link(doc: &Document) -> ResultLink {
let kind = match doc.kind() {
Kind::Channel => "频道",
Kind::Group => "群组",
Kind::Bot => "Bot",
Kind::Post => "帖子",
};
let name = [&doc.title[..], &doc.body[..], doc.username.as_str()]
.into_iter()
.map(str::trim)
.find(|s| !s.is_empty())
.unwrap_or_default();
let compact: String = name
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.chars()
.take(60)
.collect();
ResultLink {
label: format!("{kind} · {compact}"),
url: doc.url(),
}
}
+70
View File
@@ -0,0 +1,70 @@
use telefind_bot::{handle, Reply};
use telefind_core::{Document, DocumentId, MemoryIndex, PublicName, SearchIndex};
#[test]
fn plain_and_addressed_search_return_public_post_link() {
let mut index = MemoryIndex::default();
index
.upsert(Document {
id: DocumentId::Post {
chat: 9,
message: 4,
},
username: PublicName::new("techfeed").unwrap(),
title: "".into(),
body: "Rust 教程".into(),
media: None,
})
.unwrap();
for text in ["rust", "/search@MyBot RUST", "/search 教程"] {
let Reply::Results { total, links } = handle(&index, "mybot", text).unwrap() else {
panic!("expected results")
};
assert_eq!(total, 1);
assert_eq!(links[0].url, "https://t.me/techfeed/4");
assert_eq!(links[0].label, "帖子 · Rust 教程");
}
}
#[test]
fn missing_queries_and_foreign_commands_are_distinct() {
let index = MemoryIndex::default();
for text in ["/start", "/search@me ", "/help"] {
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help);
}
for text in [" ", "/search@another x", "/status"] {
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Ignored);
}
assert_eq!(
handle(&index, "me", "中文").unwrap(),
Reply::Results {
total: 0,
links: vec![]
}
);
}
#[test]
fn paging_is_stateless_and_rejects_invalid_numbers() {
let mut index = MemoryIndex::default();
for message in 1..=11 {
index
.upsert(Document {
id: DocumentId::Post { chat: 1, message },
username: PublicName::new("books").unwrap(),
title: "book".into(),
body: String::new(),
media: None,
})
.unwrap();
}
let Reply::Results { total, links } = handle(&index, "me", "/page@me 2 book").unwrap() else {
panic!("expected page")
};
assert_eq!(total, 11);
assert_eq!(links.len(), 1);
assert_eq!(links[0].url, "https://t.me/books/11");
for text in ["/page 0 book", "/page x book", "/page 2"] {
assert_eq!(handle(&index, "me", text).unwrap(), Reply::Help);
}
}