-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·99 lines (78 loc) · 2.58 KB
/
index.js
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
const {rules, items, triggers, actions, osgi} = require('openhab');
class Telegram {
constructor(thingUid)
{
this.actions = actions.thingActions("telegram", thingUid);
this.asks = [];
this.commands = {};
rules.JSRule({
name: 'Telegram ask internal handler',
description: "",
triggers: [
triggers.ChannelEventTrigger(thingUid + ":callbackEvent")
],
execute: e => {
const data = JSON.parse(e.receivedTrigger);
let ask_id = parseInt(data.reply_id, 10);
if(typeof this.asks[ask_id][data.text] !== 'undefined') {
let callback = this.asks[ask_id][data.text];
if (typeof callback === 'function') {
const answer = callback(this);
// ack
this.actions.sendTelegramAnswer(ask_id.toString(), (typeof answer === 'string') ? answer : null)
}
}
}
});
rules.JSRule({
name: 'Telegram commands handler',
description: "",
triggers: [
triggers.ChannelEventTrigger(thingUid + ":messageEvent")
],
execute: e => {
const data = JSON.parse(e.receivedTrigger);
if(typeof this.commands[data.text] !== 'undefined') {
let callback = this.commands[data.text];
if (typeof callback === 'function') {
const answer = callback(this);
if (typeof answer === 'string') {
this.message(answer);
}
}
}
}
});
}
onCommand(command, callback)
{
this.commands['/' + command] = callback;
return this;
}
message(message, ...args)
{
this.actions.sendTelegram(message, ...args);
return this;
}
alert(message, ...args)
{
return this.message('❗' + message, ...args);
}
image(url, caption)
{
this.actions.sendTelegramPhoto(url, caption);
return this;
}
ask(message, callback) {
let idx = this.asks.push(callback) - 1;
const buttons = [];
for (const button in callback) {
buttons.push(button);
}
this.actions.sendTelegramQuery('❓' + message, idx.toString(), ...buttons)
return this;
}
}
exports.bot = (thingUid) => {
return new Telegram(thingUid);
}