1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
use std::env::var;
use crate::__private::{GenericHandler, HandlerError};
use crate::models::{GetUpdates, Update, UpdateType};
use crate::{Bot, BotState};
#[cfg(feature = "commands")]
use {crate::__private::command::CommandHandler, crate::models::MessageEntityType, lazy_static::lazy_static, regex::Regex, std::collections::BTreeMap};
#[cfg(feature = "daemons")]
use {crate::__private::daemon::DaemonStruct, tokio::sync::Mutex};
use log::{error, info, trace};
use std::sync::Arc;
use std::time::Duration;
pub struct BotBuilder<T>
where
T: Sync + Send + 'static,
{
bot: Arc<Bot>,
state: Arc<Option<BotState<T>>>,
#[cfg(feature = "daemons")]
daemons: Vec<DaemonStruct<T>>,
#[cfg(feature = "commands")]
commands: Option<BTreeMap<String, Vec<CommandHandler<T>>>>,
handler: Vec<GenericHandler<T>>,
update_limit: Option<i64>,
allowed_updates: Option<Vec<UpdateType>>,
offset: Option<i64>,
timeout: Option<i64>,
interval: Option<Duration>,
}
impl BotBuilder<()> {
pub fn new() -> BotBuilder<()> {
BotBuilder {
bot: Arc::new(Bot::login(var("BOT_TOKEN").unwrap())),
state: Arc::new(None),
#[cfg(feature = "commands")]
commands: None,
#[cfg(feature = "daemons")]
daemons: vec![],
handler: vec![],
update_limit: None,
allowed_updates: None,
offset: None,
timeout: None,
interval: None,
}
}
pub fn new_with_token(token: String) -> BotBuilder<()> {
BotBuilder {
bot: Arc::new(Bot::login(token)),
state: Arc::new(None),
#[cfg(feature = "commands")]
commands: None,
#[cfg(feature = "daemons")]
daemons: vec![],
handler: vec![],
update_limit: None,
allowed_updates: None,
offset: None,
timeout: None,
interval: None,
}
}
}
impl Default for BotBuilder<()> {
fn default() -> Self {
BotBuilder::new()
}
}
impl<T: Sync + Send + 'static> BotBuilder<T> {
pub fn with_state<S>(self, state: S) -> BotBuilder<S>
where
S: Sync + Send + 'static,
{
if self.state.is_some() {
panic!("State already set")
}
if !self.handler.is_empty() {
panic!("Cannot set state after handler")
}
#[cfg(feature = "daemons")]
if !self.daemons.is_empty() {
panic!("Cannot set state after daemons")
}
#[cfg(feature = "commands")]
if self.commands.is_some() {
panic!("Cannot set state after commands")
}
BotBuilder {
bot: self.bot,
state: Arc::new(Some(BotState { state })),
#[cfg(feature = "commands")]
commands: None,
#[cfg(feature = "daemons")]
daemons: vec![],
handler: vec![],
update_limit: self.update_limit,
allowed_updates: self.allowed_updates,
offset: self.offset,
timeout: self.timeout,
interval: self.interval,
}
}
pub fn handlers(mut self, handlers: Vec<GenericHandler<T>>) -> Self {
if !self.handler.is_empty() {
panic!("Handlers already set")
}
handlers.iter().for_each(|h| info!("Registered handler {} with priority {}", h.name, h.rank));
self.handler = handlers;
self.handler.sort_by_key(|f| f.rank);
self
}
pub fn update_limit(mut self, limit: i64) -> BotBuilder<T> {
if self.update_limit.is_some() {
panic!("Update limit already set")
}
self.update_limit = Some(limit);
self
}
pub fn timeout(mut self, timeout: i64) -> BotBuilder<T> {
if self.timeout.is_some() {
panic!("Timeout already set")
}
self.timeout = Some(timeout);
self
}
pub fn interval(mut self, interval: Duration) -> BotBuilder<T> {
if self.interval.is_some() {
panic!("Interval already set")
}
self.interval = Some(interval);
self
}
#[cfg(feature = "commands")]
pub fn commands(mut self, commands: BTreeMap<String, Vec<CommandHandler<T>>>) -> BotBuilder<T> {
if self.commands.is_some() {
panic!("Commands already set")
}
for cmd in &commands {
info!("Registering handler for command {}: ", cmd.0);
for handler in cmd.1 {
info!(r#" - "{}" with priority {}"#, handler.syntax, handler.rank);
}
}
self.commands = Some(commands);
self
}
#[cfg(feature = "daemons")]
pub fn daemons(mut self, daemons: Vec<DaemonStruct<T>>) -> BotBuilder<T> {
if !self.daemons.is_empty() {
panic!("Daemons already set")
}
daemons.iter().for_each(|d| info!("Registering daemon {}", d.syntax));
self.daemons = daemons;
self
}
pub async fn launch(mut self) {
let allowed_updates = self.allowed_updates.unwrap_or_default();
let timeout = self.timeout.or(Some(5));
info!("Launching bot with parameters: [interval: {:?}, timeout: {:?}]", self.interval, timeout);
#[cfg(feature = "daemons")]
Self::launch_daemons(self.daemons, self.bot.clone(), self.state.clone()).await;
loop {
if let Some(interval) = self.interval {
tokio::time::sleep(interval).await;
}
let mut updates = vec![];
while updates.is_empty() {
updates = self
.bot
.get_updates(GetUpdates {
offset: self.offset,
limit: self.update_limit,
timeout,
allowed_updates: {
#[cfg(feature = "commands")]
if self.commands.is_some() {
[allowed_updates.clone(), vec![UpdateType::NewMessage]].concat()
} else {
allowed_updates.clone()
}
#[cfg(not(feature = "commands"))]
allowed_updates.clone()
},
})
.await
.unwrap()
}
updates.sort_by_key(|u| u.update_id);
self.offset = Some(updates.last().unwrap().update_id + 1);
for update in updates {
if let Ok(update) = Update::try_from(update.clone()) {
trace!("Received update {} ({:?})", update.get_id(), update.get_type());
#[cfg(feature = "commands")]
if Self::try_commands(&self.commands, &self.bot, self.state.as_ref().as_ref(), &update).await {
continue;
}
for h in &self.handler {
if h.updates.is_empty() || h.updates.iter().any(|u| *u == update.get_type()) {
match h.handler.handle(&self.bot, &update, self.state.as_ref().as_ref()).await {
Ok(_) => break,
Err(HandlerError::Parse) => continue,
Err(HandlerError::Runtime) => {
error!("Handler failure for {:?}", update);
break;
}
}
}
}
} else {
error!("Invalid update received: {:?}", update)
}
}
}
}
#[cfg(feature = "commands")]
async fn try_commands(commands: &Option<BTreeMap<String, Vec<CommandHandler<T>>>>, bot: &Bot, state: Option<&BotState<T>>, update: &Update) -> bool {
if let (Update::NewMessage(_, m), Some(commands)) = (&update, commands) {
if let Some(e) = m.entities.iter().find(|e| e.offset == 0 && matches!(e._type, MessageEntityType::BotCommand)) {
trace!("Command \"{}\" issued", m.text.as_ref().unwrap_or(&"".to_string()));
lazy_static! {
static ref PARAMETER_DELIMITER: Regex = Regex::new(r"\s+").unwrap();
}
if let Some(handlers) = commands.get(&m.text.as_ref().unwrap().as_str()[(e.offset + 1) as usize..(e.offset + e.length) as usize]) {
let args: Vec<String> = PARAMETER_DELIMITER
.split(&m.text.as_ref().unwrap().as_str()[(e.offset + e.length) as usize..])
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
for h in handlers {
match h.handler.handle(&args, update, bot, state).await {
Ok(_) => break,
Err(HandlerError::Parse) => continue,
Err(HandlerError::Runtime) => panic!(),
}
}
trace!("Could not delegate to any handler");
return true;
} else {
trace!("No corresponding handler found")
}
}
}
false
}
#[cfg(feature = "daemons")]
async fn launch_daemons(daemons: Vec<DaemonStruct<T>>, bot: Arc<Bot>, state: Arc<Option<BotState<T>>>) -> Vec<Arc<Mutex<()>>> {
daemons
.into_iter()
.map(|d| {
let mutex = Arc::new(Mutex::new(()));
let bot = bot.clone();
let state = state.clone();
let lock = mutex.clone();
tokio::task::spawn(async move { d.daemon.launch(bot, state, lock).await });
mutex
})
.collect()
}
}