forked from spkesDE/com.spkes.telegramNotifications
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
349 lines (321 loc) · 13.2 KB
/
app.ts
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import Homey from 'homey';
import {Telegraf, Markup} from 'telegraf';
class User {
userId: number
chatName: string
constructor(userId: number, chatName: string) {
this.chatName = chatName;
this.userId = userId;
}
}
/*
Todo
- Add "(RE)Start" Button in the Settings Page
- Add State of the Bot in the Settings Page
*/
class TelegramNotifications extends Homey.App {
users: User[] = [];
bot: Telegraf<any> | null = null;
token: string | null = null;
private startSuccess: boolean = true;
private flowsRegistered: boolean = false;
/**
* onInit is called when the app is initialized.
*/
async onInit() {
this.token = await this.homey.settings.get('bot-token');
this.homey.settings.on('set', (dataName) => {
if (dataName === 'bot-token') {
this.token = this.homey.settings.get('bot-token');
if (this.bot === null || !this.startSuccess) {
this.startBot();
this.changeBotState(true);
} else {
this.bot.stop();
this.changeBotState(true);
this.bot = null;
this.startBot();
}
}
if (dataName === 'users') {
this.users = JSON.parse(this.homey.settings.get('users'));
}
});
await this.startBot();
}
private async startBot() {
if (this.token === null || this.token === '' || this.token.length < 43) {
this.log('Telegram Notifications has no token. Please enter a Token in the Settings!');
this.changeBotState(false);
return;
}
this.bot = new Telegraf(this.token);
if (this.homey.settings.get('users') !== null) {
this.users = JSON.parse(this.homey.settings.get('users')) as User[];
}
// Start Command
this.bot.start((ctx) => {
let usePassword = this.homey.settings.get('use-password')
if (usePassword !== null && usePassword) {
let enteredPassword = ctx.message.text.split(' ')[1] ?? '';
let password = this.homey.settings.get('password')
if (password === null || password !== enteredPassword) {
ctx.reply("Wrong password.");
return;
}
}
ctx.replyWithMarkdown(
'Welcome to the Homey Telegram Bot!'
+ '\n\n'
+ 'Press the button below to register yourself!',
Markup.inlineKeyboard([
Markup.callbackButton('Register this Telegram chat!', 'user-add'),
], {columns: 1}).extra(),
).catch(this.error);
this.homey.flow.getTriggerCard('newUser').trigger({
from: ctx.chat.type === 'private' ? ctx.chat.first_name : ctx.chat.title,
username: ctx.chat.type === 'private' ? ctx.chat.username : ctx.chat.title,
chatType: ctx.chat.type,
})
.catch(this.error)
.then();
}).catch(this.error);
this.bot.action('user-add', (ctx) => {
let user: User | null = null;
if (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup') {
user = new User(ctx.chat?.id ?? 0, ctx.chat?.title ?? 'Error');
} else if (ctx.chat.type === 'private') {
user = new User(ctx.chat?.id ?? 0, ctx.chat?.first_name ?? 'Error');
}
if (user !== null && user.userId !== 0) {
if (!this.users.some((u) => u.userId === user?.userId)) {
this.users.push(user);
ctx.reply('👍').catch(this.error);
this.homey.settings.set('users', JSON.stringify(this.users));
} else {
ctx.reply('👎').catch(this.error);
ctx.reply('Already in the user list!').catch(this.error);
}
} else {
ctx.reply('Something went wrong! Can\'t get the User Id').catch(this.error);
}
}).catch(this.error);
// Flows
if (!this.flowsRegistered) {
this.sendNotificationActionFlow();
this.receiveMessageTriggerFlow();
this.sendAImageActionFlow();
this.sendAImageWithTagActionFlow();
this.sendAImageWithMessageActionFlow();
this.sendAImageWithMessageAndTagActionFlow();
this.flowsRegistered = true;
}
this.bot.catch(this.error);
await this.bot.launch().catch(this.error);
// eslint-disable-next-line no-return-assign
await this.bot.telegram.getMe().catch(() => this.changeBotState(false));
if (!this.startSuccess) {
this.log('Failed to start. Token most likely wrong.');
} else {
this.log('Telegram Notifications app is initialized.');
this.homey.log('Debug => Total-Users ' + this.users.length + ', Log-Size: ' + this.getLogSize() + " and start was " + (this.startSuccess ? 'successful' : 'unsuccessful'));
this.changeBotState(true);
}
}
private sendAImageActionFlow() {
const sendNotificationCard = this.homey.flow.getActionCard('send-a-image');
sendNotificationCard.registerRunListener((args) => {
if (this.bot != null) {
if (this.validateURL(args.url)) {
this.bot.telegram.sendPhoto(args.user.id, {filename: "", url: args.url})
.catch(this.error)
.then();
} else {
this.error('ERR_INVALID_PROTOCOL: Protocol "http:" not supported. Expected "https:"')
throw new Error('ERR_INVALID_PROTOCOL: Protocol "http:" not supported. Expected "https:"')
}
} else {
this.error('Failed to start bot. Token most likely wrong.')
throw new Error('Failed to start bot. Token most likely wrong.')
}
});
sendNotificationCard.registerArgumentAutocompleteListener(
'user',
async (query) => {
const results: any = [];
this.users.forEach((user) => {
results.push({
name: user.chatName,
id: user.userId,
});
});
return results.filter((result: any) => {
return result.name.toLowerCase().includes(query.toLowerCase());
});
},
);
}
private sendAImageWithMessageActionFlow() {
const sendNotificationCard = this.homey.flow.getActionCard('send-a-image-with-message');
sendNotificationCard.registerRunListener((args) => {
if (this.bot != null) {
if (this.validateURL(args.url)) {
this.bot.telegram.sendPhoto(args.user.id, {filename: "", url: args.url}, {caption: args.message})
.catch(this.error)
.then();
} else {
this.error('ERR_INVALID_PROTOCOL: Protocol "http:" not supported. Expected "https:"')
throw new Error('ERR_INVALID_PROTOCOL: Protocol "http:" not supported. Expected "https:"')
}
} else {
this.error('Failed to start bot. Token most likely wrong.')
throw new Error('Failed to start bot. Token most likely wrong.')
}
});
sendNotificationCard.registerArgumentAutocompleteListener(
'user',
async (query) => {
const results: any = [];
this.users.forEach((user) => {
results.push({
name: user.chatName,
id: user.userId,
});
});
return results.filter((result: any) => {
return result.name.toLowerCase().includes(query.toLowerCase());
});
},
);
}
private sendAImageWithTagActionFlow() {
const sendAImageWithTagCard = this.homey.flow.getActionCard('send-a-image-with-tag');
sendAImageWithTagCard.registerRunListener((args) => {
if (this.bot != null) {
this.bot.telegram.sendPhoto(args.user.id, {filename: "", url: args.droptoken.cloudUrl})
.catch(this.error)
.then();
}
});
sendAImageWithTagCard.registerArgumentAutocompleteListener(
'user',
async (query) => {
const results: any = [];
this.users.forEach((user) => {
results.push({
name: user.chatName,
id: user.userId,
});
});
return results.filter((result: any) => {
return result.name.toLowerCase().includes(query.toLowerCase());
});
},
);
}
private sendAImageWithMessageAndTagActionFlow() {
const sendAImageWithMessageAndTagCard = this.homey.flow.getActionCard('send-a-image-with-message-and-tag');
sendAImageWithMessageAndTagCard.registerRunListener((args) => {
if (this.bot != null) {
this.bot.telegram.sendPhoto(args.user.id, {
filename: "",
url: args.droptoken.cloudUrl
}, {caption: args.message})
.catch(this.error)
.then();
}
});
sendAImageWithMessageAndTagCard.registerArgumentAutocompleteListener(
'user',
async (query) => {
const results: any = [];
this.users.forEach((user) => {
results.push({
name: user.chatName,
id: user.userId,
});
});
return results.filter((result: any) => {
return result.name.toLowerCase().includes(query.toLowerCase());
});
},
);
}
private sendNotificationActionFlow() {
const sendNotificationCard = this.homey.flow.getActionCard('sendNotification');
sendNotificationCard.registerRunListener((args) => {
if (this.bot != null) {
this.bot.telegram.sendMessage(args.user.id, args.message)
.catch(this.error)
.then();
}
});
sendNotificationCard.registerArgumentAutocompleteListener(
'user',
async (query) => {
const results: any = [];
this.users.forEach((user) => {
results.push({
name: user.chatName,
id: user.userId,
});
});
return results.filter((result: any) => {
return result.name.toLowerCase().includes(query.toLowerCase());
});
},
);
}
private changeBotState(bool: boolean) {
this.startSuccess = bool;
this.homey.settings.set('bot-running', bool);
}
public log(message: any) {
this.writeLog(message).then();
this.homey.log(message);
}
public error(message: any) {
this.writeLog(message).then();
this.homey.error(message);
}
private receiveMessageTriggerFlow() {
const receiveMessageCard = this.homey.flow.getTriggerCard('receiveMessage');
if (this.bot != null) {
this.bot.on('text', (ctx) => {
if (ctx.message.text === undefined) return;
const token = {
message: ctx.message.text,
from: ctx.message.from.first_name !== undefined ? ctx.message.from.first_name : 'undefined',
username: ctx.message.from.username !== undefined ? ctx.message.from.username : 'undefined',
chat: ctx.chat.type === 'private' ? ctx.chat.first_name : ctx.chat.title,
chatType: ctx.chat.type,
};
receiveMessageCard.trigger(token)
.catch(this.error)
.then();
}).catch(this.error);
}
}
private async writeLog(message: any) {
let oldLogs = this.homey.settings.get('logs');
if (oldLogs === null || oldLogs === undefined || oldLogs === '') oldLogs = '[]';
const newMessage: JSON = <JSON><unknown>{date: new Date().toLocaleString(), message};
const savedHistory = JSON.parse(oldLogs);
if (savedHistory.length >= 15) savedHistory.pop();
savedHistory.unshift(newMessage);
this.homey.settings.set('logs', JSON.stringify(savedHistory));
}
private getLogSize() : number {
let oldLogs = this.homey.settings.get('logs');
const savedHistory = JSON.parse(oldLogs);
return savedHistory.length
}
private validateURL(link: string)
{
if (link.indexOf("http://") == 0) {
return false;
}
return link.indexOf("https://") == 0;
}
}
module.exports = TelegramNotifications;