Skip to content

Commit 51a773c

Browse files
committed
chore: nix friendly api
1 parent 412007d commit 51a773c

File tree

14 files changed

+364
-118
lines changed

14 files changed

+364
-118
lines changed

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
name = "bot"
33
version = "0.1.0"
44
edition = "2021"
5+
license = "Apache-2.0"
6+
homepage = "https://github.com/rust-lang-uz/telegram"
7+
repository = "https://github.com/rust-lang-uz/telegram"
58

69
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
710

default.nix

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,9 @@ in
4242
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
4343

4444
meta = with lib; {
45-
homepage = manifest.workspace.package.homepage;
45+
homepage = manifest.homepage;
4646
description = "Telegram bot manager for Uzbek Rust community";
47-
license = with lib.licenses; [gpl3Only];
47+
license = with lib.licenses; [asl20];
4848

4949
platforms = with platforms; linux ++ darwin;
5050

result

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/nix/store/58np2nh1iiap7j5j5d9cj3qj15qm10r4-bot-0.1.0

src/bot.rs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
use crate::functions;
2+
use teloxide::{
3+
dispatching::{UpdateFilterExt, UpdateHandler},
4+
prelude::*,
5+
utils::command::BotCommands,
6+
};
7+
8+
#[derive(BotCommands, Clone, Debug)]
9+
#[command(rename_rule = "lowercase", parse_with = "split")]
10+
#[command(description = "These are the commands that I can understand:")]
11+
pub enum Command {
12+
/// List existing commands
13+
Help,
14+
15+
/// Starting point of the bot
16+
Start,
17+
18+
/// Rules of our chat
19+
Rules,
20+
21+
/// About the bot
22+
About,
23+
24+
/// Available groups
25+
Group,
26+
27+
/// Latest version
28+
Latest,
29+
30+
/// Specific version
31+
Version,
32+
33+
/// Report offtopic
34+
Off,
35+
36+
/// Useful resources
37+
Useful,
38+
39+
/// Roadmap for newbies,
40+
Roadmap,
41+
42+
/// Check for chatid
43+
Check,
44+
}
45+
46+
pub fn handler() -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>> {
47+
dptree::entry()
48+
// Inline Queries
49+
.branch(Update::filter_inline_query().endpoint(functions::inline))
50+
// Callbacks
51+
.branch(Update::filter_callback_query().endpoint(functions::callback))
52+
// Commands
53+
.branch(
54+
Update::filter_message()
55+
.filter_command::<Command>()
56+
.endpoint(functions::commands),
57+
)
58+
.branch(Update::filter_message().endpoint(functions::triggers))
59+
}
60+
61+
pub fn dispatch(
62+
bot: &Bot,
63+
deps: DependencyMap,
64+
) -> Dispatcher<Bot, Box<dyn std::error::Error + Send + Sync>, teloxide::dispatching::DefaultKey> {
65+
Dispatcher::builder(bot.clone(), handler())
66+
.dependencies(deps) // dptree::deps![...]
67+
// If no handler succeeded to handle an update, this closure will be called
68+
.default_handler(|upd| async move {
69+
log::warn!("Unhandled update: {:?}", upd);
70+
})
71+
// If the dispatcher fails for some reason, execute this handler
72+
.error_handler(LoggingErrorHandler::with_custom_text(
73+
"An error has occurred in the dispatcher",
74+
))
75+
.enable_ctrlc_handler()
76+
.build()
77+
}

src/config.rs

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
use std::fmt::{Display, Formatter};
2+
use std::path::PathBuf;
3+
use Field::{Domain, GitHub, Token};
4+
5+
pub enum ConfigError {
6+
NonExistent(String),
7+
ReadError(std::io::Error),
8+
}
9+
10+
impl Display for ConfigError {
11+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
12+
match self {
13+
ConfigError::ReadError(e) => write!(f, "Error while reading config: {}", e),
14+
ConfigError::NonExistent(e) => write!(f, "File is probably non existent: {}", e),
15+
}
16+
}
17+
}
18+
19+
pub enum Field {
20+
Token,
21+
Domain,
22+
GitHub,
23+
}
24+
25+
#[derive(Default, Debug)]
26+
pub struct Config {
27+
pub token: String,
28+
pub domain: String,
29+
pub github: String,
30+
}
31+
32+
impl Config {
33+
pub fn new(token: String, domain: String, github: String) -> Self {
34+
Self {
35+
token,
36+
domain,
37+
github,
38+
}
39+
}
40+
41+
pub fn set(&mut self, data: String, field: Field) -> Result<(), ConfigError> {
42+
match field {
43+
Token => self.token = data,
44+
Domain => self.domain = data,
45+
GitHub => self.github = data,
46+
};
47+
48+
Ok(())
49+
}
50+
51+
pub fn read(&mut self, path: PathBuf, field: Field) -> Result<(), ConfigError> {
52+
let data = match self.parse_file(path) {
53+
Ok(d) => d,
54+
Err(e) => return Err(e),
55+
};
56+
57+
match field {
58+
Token => self.token = data,
59+
Domain => self.domain = data,
60+
GitHub => self.github = data,
61+
};
62+
63+
Ok(())
64+
}
65+
66+
fn parse_file(&self, path: PathBuf) -> Result<String, ConfigError> {
67+
if !(path.is_absolute()) {
68+
return Err(ConfigError::NonExistent(
69+
"Given path is not absolute".to_string(),
70+
));
71+
}
72+
73+
if !(path.is_file()) {
74+
return Err(ConfigError::NonExistent(
75+
"This file probably doesn't exist".to_string(),
76+
));
77+
}
78+
79+
let result = match std::fs::read_to_string(path) {
80+
Ok(d) => d,
81+
Err(e) => return Err(ConfigError::ReadError(e)),
82+
};
83+
84+
Ok(result)
85+
}
86+
}

src/functions/groups.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ pub async fn command(bot: &Bot, msg: &Message, groups: &Groups) -> ResponseResul
2424
pub async fn callback_list(
2525
bot: &Bot,
2626
q: &CallbackQuery,
27-
args: &Vec<&str>,
27+
args: &[&str],
2828
groups: &Groups,
2929
) -> ResponseResult<()> {
3030
if !args.is_empty() {
@@ -43,7 +43,7 @@ pub async fn callback_list(
4343
Ok(())
4444
}
4545

46-
pub async fn callback_detail(bot: &Bot, q: &CallbackQuery, args: &Vec<&str>) -> ResponseResult<()> {
46+
pub async fn callback_detail(bot: &Bot, q: &CallbackQuery, args: &[&str]) -> ResponseResult<()> {
4747
let groups: Groups = Groups::new();
4848
let find = groups.find_group(args[1..].join("_").to_string());
4949

src/functions/help.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use super::start::keyboard;
2-
use crate::{utils::message::Rustina, Command};
2+
use crate::{bot::Command, utils::message::Rustina};
33
use teloxide::{payloads::SendMessageSetters, prelude::*, types::ParseMode};
44

55
static TEXT: &[(&str, &str)] = &[

src/functions/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ pub mod version;
1414

1515
pub use inline::inline;
1616

17+
use crate::bot::Command;
1718
use crate::utils::{github::GitHub, groups::Groups, resources::Resources};
18-
use crate::Command;
1919
use std::error::Error;
2020
use teloxide::{prelude::*, types::*};
2121

src/functions/useful.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ pub async fn callback_category_list(
7373
pub async fn callback_material_detail(
7474
bot: &Bot,
7575
q: &CallbackQuery,
76-
args: &Vec<&str>,
76+
args: &[&str],
7777
resources: &Resources,
7878
) -> ResponseResult<()> {
7979
let find = resources
@@ -96,7 +96,7 @@ pub async fn callback_material_detail(
9696
}
9797

9898
pub fn view_category_list(category: &str) -> String {
99-
format!("<b>Siz hozirda {}{} kategoriyasi ichida turibsiz.</b>\nIltimos, keltirilgan materiallardan birini tanlang...",
99+
format!("<b>Siz hozirda {}{} kategoriyasi ichida turibsiz.</b>\nIltimos, keltirilgan materiallardan birini tanlang...",
100100
&category[0..1].to_uppercase(), &category[1..].replace('_', " "))
101101
}
102102

src/functions/version.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub async fn command(bot: &Bot, github: GitHub, msg: &Message) -> ResponseResult
2323
pub async fn callback_list(
2424
bot: &Bot,
2525
q: &CallbackQuery,
26-
args: &Vec<&str>,
26+
args: &[&str],
2727
github: GitHub,
2828
) -> ResponseResult<()> {
2929
let page = args[0].parse::<u32>().unwrap();
@@ -48,7 +48,7 @@ pub async fn callback_list(
4848
pub async fn callback_detail(
4949
bot: &Bot,
5050
q: &CallbackQuery,
51-
args: &Vec<&str>,
51+
args: &[&str],
5252
github: GitHub,
5353
) -> ResponseResult<()> {
5454
let page = args[0].parse::<u32>().unwrap();

0 commit comments

Comments
 (0)