3 Commits

Author SHA1 Message Date
s3rius 1dd6c21ce4 Updated converted again.
/ docker_build (push) Successful in 3m52s
/ deploy_helm (push) Successful in 14s
Signed-off-by: Pavel Kirilin <s3riussan@gmail.com>
2026-07-17 15:08:51 +02:00
s3rius 8d86ca5fae Fixed currency converter.
/ docker_build (push) Successful in 3m36s
/ deploy_helm (push) Successful in 15s
Signed-off-by: Pavel Kirilin <s3riussan@gmail.com>
2026-07-16 15:30:41 +02:00
s3rius 2ca20c837c Fixed some dangerous methods.
/ deploy_helm (push) Successful in 15s
/ docker_build (push) Successful in 9m17s
2025-10-24 14:55:27 +02:00
5 changed files with 136 additions and 34 deletions
+2 -2
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
@@ -38,7 +38,7 @@ jobs:
needs: docker_build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Setup helm
uses: azure/setup-helm@v4.3.0
- name: Deploy
+1 -1
View File
@@ -25,7 +25,7 @@ lazy_static = "1.4.0"
log = "0.4.17"
rand = "0.8.5"
rayon = "1.6.1"
regex = "1.7.1"
regex = { version = "1.7.1", features = ["unicode"] }
reqwest = { version = "0.11.14", features = ["gzip", "json", "tokio-rustls"] }
serde = { version = "1.0.152", features = ["derive"] }
serde_json = "1.0.93"
+3
View File
@@ -92,6 +92,9 @@ pub struct BotConfig {
value_delimiter = ','
)]
pub currency_excluded_chats: Vec<i64>,
#[arg(name = "dev-mode", long, default_value_t = false, env = "BOT_DEV_MODE")]
pub dev_mode: bool,
}
#[derive(Clone, Parser, Debug)]
+119 -30
View File
@@ -1,8 +1,17 @@
use std::{
collections::{HashMap, HashSet},
time::Duration,
sync::LazyLock,
time::{Duration, Instant},
};
use tokio::sync::Mutex;
use serde_json::Value;
static RATE_CACHE: LazyLock<Mutex<(Value, Instant)>> =
LazyLock::new(|| Mutex::new((Value::Null, Instant::now())));
static CACHE_TTL: Duration = Duration::from_secs(3600);
use grammers_client::{Client, InputMessage, Update};
use regex::Regex;
@@ -29,7 +38,8 @@ lazy_static::lazy_static! {
"TRY",
"AMD",
"RSD",
"THB"
"THB",
"GEL",
];
static ref CONVERTION_ALIASES: HashMap<&'static str, &'static str> = HashMap::from(
@@ -39,6 +49,7 @@ lazy_static::lazy_static! {
// USD
("бакс", "USD"),
("доллар", "USD"),
("$", "USD"),
// EUR
("евро", "EUR"),
// JPY
@@ -53,8 +64,7 @@ lazy_static::lazy_static! {
// CNY
("юан", "CNY"),
// UAH
("гривна", "UAH"),
("гривны", "UAH"),
("гривн", "UAH"),
("гривен", "UAH"),
("грiвен", "UAH"),
// KZT
@@ -70,6 +80,8 @@ lazy_static::lazy_static! {
("динар", "RSD"),
// THB
("бат", "THB"),
// GEL
("лари", "GEL"),
]
);
@@ -80,7 +92,7 @@ lazy_static::lazy_static! {
.chain(SUPPORTED_CURS.iter().copied())
.collect::<Vec<_>>()
.join("|");
Regex::new(format!(r"\s*(?P<cur_value>\d+([\.,]\d+)?)\s+(?P<cur_name>{a})").as_str()).unwrap()
Regex::new(format!(r"(?i)\s*(?P<cur_value>\d+([\.,]\d+)?)\s+((?P<cur_name>{a})[\p{{L}}]*)(\s+(в|to|in)\s+(?P<target>{a})[\p{{L}}]*)?").as_str()).unwrap()
};
}
@@ -100,6 +112,31 @@ impl CurrencyConverter {
.build()?;
Ok(Self { client })
}
async fn fetch_rates(&self) -> anyhow::Result<Value> {
let cached = {
let lock = RATE_CACHE.lock().await;
if lock.1.elapsed() < CACHE_TTL && lock.0 != Value::Null {
Some(lock.0.clone())
} else {
None
}
};
if let Some(resp) = cached {
return Ok(resp);
}
let resp = self
.client
.get("https://www.cbr-xml-daily.ru/daily_json.js")
.send()
.await?
.error_for_status()?
.json::<serde_json::Value>()
.await?;
let mut lock = RATE_CACHE.lock().await;
*lock = (resp.clone(), Instant::now());
Ok(resp)
}
}
/// This filter check if the message matches regex for currencies.
@@ -118,14 +155,14 @@ impl Handler for CurrencyConverter {
let Some(message) = get_message(update) else {
return Ok(());
};
let response = self
.client
.get("https://www.cbr-xml-daily.ru/daily_json.js")
.send()
.await?
.error_for_status()?
.json::<serde_json::Value>()
.await?;
let response = match self.fetch_rates().await {
Ok(r) => r,
Err(e) => {
log::warn!("Failed to fetch rates: {e}");
return Ok(());
}
};
let Some(valutes) = response
.get("Valute")
@@ -149,26 +186,24 @@ impl Handler for CurrencyConverter {
else {
continue;
};
let cur_name = capture.name("cur_name").map(|mtch| mtch.as_str());
let Some(cur_name) = cur_name
// We check if the value is an alias.
.and_then(|val| CONVERTION_ALIASES.get(val).copied())
// get previous value if not.
.or(cur_name)
else {
continue;
let cur_name_raw = capture.name("cur_name").map(|mtch| mtch.as_str());
let cur_name: String = if let Some(val) = cur_name_raw {
let lower = val.to_lowercase();
if let Some(alias) = CONVERTION_ALIASES.get(lower.as_str()) {
alias.to_string()
} else {
val.to_uppercase().to_string()
}
} else {
String::new()
};
let fingerprint = format!("{num_value:.5} {cur_name}");
// Check if we already processed this value.
if mapped.contains(&fingerprint) {
if cur_name.is_empty() {
continue;
}
// Add a value to not calculate it again.
mapped.insert(fingerprint);
// Now we want to know current nominal for this value.
let Some(nominal) = valutes
// We search for it using cur_name.
.get(cur_name)
.get(cur_name.as_str())
.and_then(|info| info.get("Nominal"))
.map(ToString::to_string)
.and_then(|value| value.as_str().parse::<f64>().ok())
@@ -176,9 +211,10 @@ impl Handler for CurrencyConverter {
else {
continue;
};
// Now we want to know multiplier.
let Some(multiplier) = valutes
.get(cur_name)
.get(cur_name.as_str())
.and_then(|info| info.get("Value"))
.map(ToString::to_string)
.and_then(|value| value.as_str().parse::<f64>().ok())
@@ -186,9 +222,62 @@ impl Handler for CurrencyConverter {
continue;
};
let mut converted_value = multiplier * num_value / nominal;
let mut target_name = String::from("RUB");
let target_cur_name = capture.name("target").map(|mtch| mtch.as_str());
let target_cur_name: String = if let Some(val) = target_cur_name {
let lower = val.to_lowercase();
if let Some(alias) = CONVERTION_ALIASES.get(lower.as_str()) {
alias.to_string()
} else {
val.to_uppercase().to_string()
}
} else {
String::new()
};
if !target_cur_name.is_empty() {
if target_cur_name == cur_name {
continue;
}
if let Some(info) = valutes.get(target_cur_name.as_str()) {
let Some(target_nominal) = info
.get("Nominal")
.map(ToString::to_string)
.and_then(|v| v.as_str().parse::<f64>().ok())
else {
continue;
};
let Some(target_multiplier) = info
.get("Value")
.map(ToString::to_string)
.and_then(|v| v.as_str().parse::<f64>().ok())
else {
continue;
};
let Some(target_code) = info
.get("CharCode")
.and_then(|v| v.as_str())
.map(ToString::to_string)
else {
continue;
};
target_name = target_code;
converted_value = converted_value * target_nominal / target_multiplier;
}
}
let fingerprint = format!("{num_value:.5} {cur_name} {target_name}");
// Check if we already processed this value.
if mapped.contains(&fingerprint) {
continue;
}
// Add a value to not calculate it again.
mapped.insert(fingerprint);
calucates.push(format!(
"<pre>{num_value} {cur_name} = {value:.2} RUB</pre><br>",
value = multiplier * num_value / nominal,
"<pre>{num_value} {cur_name} = {converted_value:.2} {target_name}</pre><br>",
));
}
+11 -1
View File
@@ -100,7 +100,7 @@ async fn handle_with_log(handler: Box<dyn Handler>, client: Client, update_data:
#[allow(clippy::too_many_lines)]
async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> {
let me = client.get_me().await?;
let handlers: Vec<FilteredHandler> = vec![
let mut handlers: Vec<FilteredHandler> = vec![
// Printing help.
FilteredHandler::new(Help)
.add_filter(ExcludedChatsFilter(args.excluded_chats.clone()))
@@ -132,6 +132,7 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> {
.add_filter(ExcludedChatsFilter(args.excluded_chats.clone()))
.add_filter(UpdateTypeFilter(&[UpdateType::New]))
.add_filter(SilentFilter)
.add_filter(OnlyFromId(me.id()))
.add_filter(TextFilter(&[".bl"], TextMatchMethod::StartsWith)),
// Handler for converting currecies.
FilteredHandler::new(CurrencyConverter::new()?)
@@ -145,6 +146,7 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> {
.add_filter(ExcludedChatsFilter(args.excluded_chats.clone()))
.add_filter(UpdateTypeFilter(&[UpdateType::New]))
.add_filter(SilentFilter)
.add_filter(OnlyFromId(me.id()))
.add_filter(TextFilter(&[".rl"], TextMatchMethod::StartsWith)),
// Weather forecast.
FilteredHandler::new(WeatherForecaster::new()?)
@@ -172,6 +174,7 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> {
.add_filter(ExcludedChatsFilter(args.excluded_chats.clone()))
.add_filter(UpdateTypeFilter(&[UpdateType::New]))
.add_filter(SilentFilter)
.add_filter(OnlyFromId(me.id()))
.add_filter(TextFilter(&[".c"], TextMatchMethod::StartsWith))
.add_filter(NotFilter(TextFilter(
&[".cid"],
@@ -191,6 +194,13 @@ async fn run(args: BotConfig, client: Client) -> anyhow::Result<()> {
.add_filter(TextFilter(&[".t"], TextMatchMethod::StartsWith)),
];
// If dev mode is enabled only respond to messages from user himself.
if args.dev_mode {
for hander in handlers.iter_mut() {
*hander = hander.clone().add_filter(OnlyFromId(me.id()));
}
}
let mut errors_count = 0;
loop {