iobroker.telegram-menu 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,17 @@ You can create different groups with separate menus, and then assign users to th
33
33
  Placeholder for the next version (at the beginning of the line):
34
34
  ### **WORK IN PROGRESS**
35
35
  -->
36
+ ### 0.7.2 (2023-10-15)
37
+
38
+ - submenu Number fixed
39
+ - text is lost when editing #63
40
+ - convert milliseconds value to a local time specification
41
+ - setstate and get result of another state with text adjusted
42
+
43
+ ### 0.7.1 (2023-10-02)
44
+
45
+ - bugfix, Error read UserListTypeError: Cannot read properties of undefined
46
+
36
47
  ### 0.7.0 (2023-10-01)
37
48
 
38
49
  - #53 feature: sendPicture von server-path
package/admin/js/emit.js CHANGED
@@ -26,6 +26,7 @@ function getUsersFromTelegram(socket, _this, telegramInstance) {
26
26
  */
27
27
  // @ts-ignore
28
28
  function getAllTelegramInstances(socket, _this) {
29
+ console.log("getAllTelegramInstances");
29
30
  const id = [];
30
31
  try {
31
32
  socket.emit(
@@ -36,13 +37,14 @@ function getAllTelegramInstances(socket, _this) {
36
37
  function (err, doc) {
37
38
  if (!err && doc.rows.length) {
38
39
  for (let i = 0; i < doc.rows.length; i++) {
40
+ console.log(doc.rows[i]);
39
41
  if (
40
- doc.rows[i].value &&
41
- doc.rows[i].value.common &&
42
- doc.rows[i].value.common.titleLang &&
43
- doc.rows[i].value.common.titleLang.en &&
44
- doc.rows[i].value.common.titleLang.en == "Telegram"
45
- // doc.rows[i].value.common.title == "Telegram"
42
+ (doc.rows[i].value &&
43
+ doc.rows[i].value.common &&
44
+ doc.rows[i].value.common.titleLang &&
45
+ doc.rows[i].value.common.titleLang.en &&
46
+ doc.rows[i].value.common.titleLang.en == "Telegram") ||
47
+ doc.rows[i].value.common.title == "Telegram"
46
48
  ) {
47
49
  id.push(doc.rows[i].id.replace(/^system\.adapter\./, ""));
48
50
  }
@@ -51,6 +53,7 @@ function getAllTelegramInstances(socket, _this) {
51
53
  // @ts-ignore
52
54
  $("#select_instance").append(newSelectInstanceRow(id));
53
55
  });
56
+ console.log("Instancen: " + id);
54
57
  }
55
58
  }
56
59
  } else if (err) _this.log.debug("Error all Telegram Users: " + JSON.stringify(err));
@@ -1,5 +1,5 @@
1
1
  /*global $, */
2
- /*eslint no-unused-vars: ["error", { "varsIgnorePattern": "isInputFieldEmpty|countOccurrences|deleteDoubleEntrysInArray|"}]*/
2
+ /*eslint no-unused-vars: ["error", { "varsIgnorePattern": "isInputFieldEmpty|countOccurrences|deleteDoubleEntrysInArray|replaceAll|isInputFieldEmty|sortArray"}]*/
3
3
  /**
4
4
  * Counts how often an element is present in the array
5
5
  * @param {[]} arr The array which should be checked
@@ -57,3 +57,7 @@ function sortArray(arr) {
57
57
  });
58
58
  return arr;
59
59
  }
60
+
61
+ function replaceAll(text, searchValue, replaceValue) {
62
+ return text.replace(new RegExp(searchValue, "g"), replaceValue);
63
+ }
package/admin/js/main.js CHANGED
@@ -535,6 +535,7 @@ function insertEditValues(action, $this) {
535
535
  if (action == "get") {
536
536
  newline = valuesToArray($this, "p[data-name='newline_checkbox']");
537
537
  texts = valuesToArray($this, "p[data-name='text']");
538
+ console.log(texts);
538
539
  }
539
540
  if (action == "pic") {
540
541
  picSendDelay = valuesToArray($this, "p[data-name='picSendDelay']");
@@ -605,7 +606,8 @@ function valuesToArray($this, selector) {
605
606
  .siblings()
606
607
  .find(selector)
607
608
  .each(function () {
608
- val.push($(this).html().trim() != "-" ? $(this).html() : "");
609
+ // #63 - Bugfix
610
+ val.push($(this).html().trim() != "-" ? $(this).html().replaceAll('"', "'") : "");
609
611
  });
610
612
  return val;
611
613
  }
package/io-package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "telegram-menu",
4
- "version": "0.7.0",
4
+ "version": "0.7.2",
5
5
  "news": {
6
+ "0.7.2": {
7
+ "en": "submenu Number fixed\ntext is lost when editing #63\nconvert milliseconds value to a local time specification\nsetstate and get result of another state with text adjusted",
8
+ "de": "unterpositionen Anzahl fest\ntext wird beim editieren von #63 verloren\nmillisekunden-wert in eine lokale zeitvorgabe umwandeln\nsetstate und erhalten ergebnis eines anderen staates mit text angepasst",
9
+ "ru": "подменю Номер фиксированный\nтекст теряется при редактировании #63\nконвертировать миллисекундное значение в местную спецификацию времени\nsetstate и получить результат другого государства с текстом скорректирован",
10
+ "pt": "submenu Número fixo\ntexto é perdido ao editar #63\nconverter valor de milissegundos para uma especificação de tempo local\nsetstate e obter resultado de outro estado com texto ajustado",
11
+ "nl": "submenu Nummer gerepareerd\nsms is verloren als editing 63\nverbergt milliseconden waarde voor een plaatselijke tijd specifiek\nvertaling:",
12
+ "fr": "sous-menu Nombre fixe\ntexte est perdu lors de l'édition #63\nconvertir la valeur millisecondes à une spécification locale\nsetstate and get result of another state with text adjusted",
13
+ "it": "sottomenu Numero fisso\ntesto si perde quando si modifica #63\nconvertire il valore di millisecondi in una specifica dell'ora locale\nsetstate e ottenere il risultato di un altro stato con testo regolato",
14
+ "es": "submenú Número fijo\ntexto se pierde cuando se edita #63\nconvertir el valor de milisegundos a una especificación de tiempo local\nsetstate y obtener resultado de otro estado con texto ajustado",
15
+ "pl": "submenu liczba stała\ntekst został utracony podczas edycji #63\nwartość zwrotu milisekund do specyfikacji czasu lokalnego\nzbiór i dostaniemy rezultat innego stanu z tekstem dostosowywanym",
16
+ "uk": "субмену Номер фіксований\nтекст втрачено при редагування #63\nконвертувати значення мілісекундів в локальну специфікацію часу\nsetstate і отримати результат іншої держави з текстом",
17
+ "zh-cn": "分项 固定人数\n编辑第63号\n当地时间的具体化肥价值\na. 一国和另一国由于经调整案文"
18
+ },
19
+ "0.7.1": {
20
+ "en": "bugfix, Error read UserListTypeError: Cannot read properties of undefined",
21
+ "de": "bugfix, Fehler lesen UserListType Fehler: Nicht zu lesen Eigenschaften von undefiniert",
22
+ "ru": "bugfix, Ошибка читать UserListType Ошибка: Не смогите прочитать свойства неопределенного",
23
+ "pt": "bugfix, Erro lido UserListType Erro: Não é possível ler propriedades indefinidas",
24
+ "nl": "error las UserListType Error: Kan niet onbepaalde eigenschappen lezen",
25
+ "fr": "bugfix, Erreur lire UserListType Erreur: Cannot read properties of undefined",
26
+ "it": "bugfix, Error read UserListType Errore: Proprietà di lettura non definite",
27
+ "es": "bugfix, Error leer UserListType Error: No se pueden leer propiedades indefinidas",
28
+ "pl": "error przeczytał UserListType Error: Cannot czytał właściwości nieokreślone",
29
+ "uk": "javaScript licenses API Веб-сайт Go1.13.8 Помилка: Не можна прочитати властивості невизначених",
30
+ "zh-cn": "bugfix, Error读者 rror: 评 注"
31
+ },
6
32
  "0.7.0": {
7
33
  "en": "#53 feature: sendPicture von server-path\n#52 icons are missing, copy data\n#51 by creating a new Menu, the Users are not shown",
8
34
  "de": "#53 Feature: sendPicture von server-path\n#52 symbole fehlen, kopierdaten\n#51 durch Erstellen eines neuen Menüs, die Benutzer werden nicht angezeigt",
@@ -67,32 +93,6 @@
67
93
  "pl": "zastosowano menu z błędem",
68
94
  "uk": "виправлено, відправте меню з помилкою",
69
95
  "zh-cn": "a. 固定状态,向男子发出错误的通知"
70
- },
71
- "0.6.6": {
72
- "en": "add info-big.png",
73
- "de": "info-big.png",
74
- "ru": "добавить info-big.png",
75
- "pt": "adicionar info-big.png",
76
- "nl": "voeg info-big toe",
77
- "fr": "ajouter info-big.png",
78
- "it": "aggiungere info-big.png",
79
- "es": "añadir info-big.png",
80
- "pl": "info-big.png",
81
- "uk": "javascript licenses api веб-сайт go1.13.8",
82
- "zh-cn": "增 编"
83
- },
84
- "0.6.5": {
85
- "en": "get user by chatID and send back to this chatID",
86
- "de": "benutzer per chatID ermitteln und zurück senden an diese chatID",
87
- "ru": "получить пользователя по чатID и отправить обратно в этот чатID",
88
- "pt": "obter usuário por chatID e enviar de volta para este chatID",
89
- "nl": "haal gebruiker van chatID en stuur terug naar dit chatID",
90
- "fr": "obtenir utilisateur par chatID et renvoyer à ce chatID",
91
- "it": "ottenere l'utente da chatID e tornare a questo chatID",
92
- "es": "obtener usuario por chatID y enviar de nuevo a este chatID",
93
- "pl": "użytkowanie przez czat i wysyłane do tego czatID",
94
- "uk": "отримати користувач по chatID і відправити назад в цей чатID",
95
- "zh-cn": "被混乱者利用,然后再送给这一混乱的裁研所。"
96
96
  }
97
97
  },
98
98
  "titleLang": {
package/lib/js/action.js CHANGED
@@ -29,8 +29,9 @@ function calcValue(_this, textToSend, val) {
29
29
  */
30
30
  function exchangeValue(textToSend, stateVal, _this) {
31
31
  const startindex = textToSend.indexOf("change{");
32
- const match = textToSend.substring(startindex + "change".length + 1, textToSend.indexOf("}", startindex));
32
+ let match = textToSend.substring(startindex + "change".length + 1, textToSend.indexOf("}", startindex));
33
33
  let objChangeValue;
34
+ match = match.replaceAll("'", '"');
34
35
  if (Utils.isJSON("{" + match + "}")) objChangeValue = JSON.parse("{" + match + "}");
35
36
  else {
36
37
  _this.log.error(`There is a error in your input: ` + JSON.stringify(Utils.replaceAll(match, '"', "'")));
@@ -100,29 +101,33 @@ const idBySelector = async (
100
101
  enums = result["enum.functions"][`enum.functions.${functions}`].common.members;
101
102
  if (enums) {
102
103
  const promises = enums.map(async (id) => {
103
- const value = await _this.getForeignStateAsync(id);
104
- if (value && value.val) {
105
- _this.log.debug("Value " + JSON.stringify(value.val));
106
- _this.log.debug("text " + JSON.stringify(text));
107
- let newtext = text;
108
- let name;
109
- if (text.includes("{common.name}")) {
110
- _this.log.debug("test ");
111
- name = await _this.getForeignObjectAsync(id);
112
- _this.log.debug("Name " + JSON.stringify(name));
113
- // _this.log.debug("Name " + JSON.stringify(await _this.getForeignObjectAsync(id)));
114
- if (name && name.common.name)
115
- newtext = newtext.replace("{common.name}", name.common.name);
116
- }
117
- if (text.includes("&amp;&amp;")) text2Send += newtext.replace("&amp;&amp;", value.val);
118
- else {
119
- text2Send += newtext;
120
- text2Send += " " + value.val;
104
+ try {
105
+ const value = await _this.getForeignStateAsync(id);
106
+ if (value && value.val) {
107
+ _this.log.debug("Value " + JSON.stringify(value.val));
108
+ _this.log.debug("text " + JSON.stringify(text));
109
+ let newtext = text;
110
+ let name;
111
+ if (text.includes("{common.name}")) {
112
+ _this.log.debug("test ");
113
+ name = await _this.getForeignObjectAsync(id);
114
+ _this.log.debug("Name " + JSON.stringify(name));
115
+ // _this.log.debug("Name " + JSON.stringify(await _this.getForeignObjectAsync(id)));
116
+ if (name && name.common.name)
117
+ newtext = newtext.replace("{common.name}", name.common.name);
118
+ }
119
+ if (text.includes("&amp;&amp;")) text2Send += newtext.replace("&amp;&amp;", value.val);
120
+ else {
121
+ text2Send += newtext;
122
+ text2Send += " " + value.val;
123
+ }
121
124
  }
125
+ if (newline == "true") text2Send += "\n";
126
+ else text2Send += " ";
127
+ _this.log.debug("text2send " + JSON.stringify(text2Send));
128
+ } catch (e) {
129
+ _this.log.error("Error idBySelector: " + JSON.stringify(e));
122
130
  }
123
- if (newline == "true") text2Send += "\n";
124
- else text2Send += " ";
125
- _this.log.debug("text2send " + JSON.stringify(text2Send));
126
131
  });
127
132
  Promise.all(promises)
128
133
  .then(() => {
@@ -14,10 +14,10 @@ const calcValue = require("./action").calcValue;
14
14
  * @param {object} userListWithChatID Userlist with ChatID
15
15
  */
16
16
  function getstate(_this, part, userToSend, telegramInstance, one_time_keyboard, resize_keyboard, userListWithChatID) {
17
- try {
18
- let text = "";
19
- let i = 1;
20
- part.getData.forEach(async (element) => {
17
+ let text = "";
18
+ let i = 1;
19
+ part.getData.forEach(async (element) => {
20
+ try {
21
21
  _this.log.debug("Get Value ID " + JSON.stringify(element.id));
22
22
  const specificatorSelektor = "functions=";
23
23
  const id = element.id;
@@ -49,6 +49,17 @@ function getstate(_this, part, userToSend, telegramInstance, one_time_keyboard,
49
49
  if (element.text) {
50
50
  let result = {};
51
51
  let textToSend = element.text.toString();
52
+ if (textToSend.includes("{time}")) {
53
+ const time = new Date(value.val);
54
+ const timeString = time.toLocaleDateString("de-DE", {
55
+ hour: "2-digit",
56
+ minute: "2-digit",
57
+ second: "2-digit",
58
+ hour12: false,
59
+ });
60
+ textToSend = textToSend.replace("{time}", timeString);
61
+ val = "";
62
+ }
52
63
  if (textToSend.includes("math:")) {
53
64
  const result = calcValue(_this, textToSend, val);
54
65
  textToSend = result.textToSend;
@@ -85,9 +96,9 @@ function getstate(_this, part, userToSend, telegramInstance, one_time_keyboard,
85
96
  i++;
86
97
  });
87
98
  }
88
- });
89
- } catch (error) {
90
- _this.log.error("Error Getdata: " + JSON.stringify(error));
91
- }
99
+ } catch (error) {
100
+ _this.log.error("Error Getdata: " + JSON.stringify(error));
101
+ }
102
+ });
92
103
  }
93
104
  module.exports = { getstate };
@@ -1,3 +1,5 @@
1
+ const sendToTelegram = require("./telegram").sendToTelegram;
2
+
1
3
  /**
2
4
  * Sets the state
3
5
  * @param {*} _this
@@ -7,7 +9,17 @@
7
9
  * @param {boolean} SubmenuValuePriority If true the value from the submenu will be used else the value from the switch
8
10
  * @returns Returns an array with the ids to set
9
11
  */
10
- function setstate(_this, part, userToSend, valueFromSubmenu, SubmenuValuePriority) {
12
+ function setstate(
13
+ _this,
14
+ part,
15
+ userToSend,
16
+ valueFromSubmenu,
17
+ SubmenuValuePriority,
18
+ telegramInstance,
19
+ resize_keyboard,
20
+ one_time_keyboard,
21
+ userListWithChatID,
22
+ ) {
11
23
  try {
12
24
  const setStateIds = [];
13
25
  part.switch.forEach(
@@ -22,12 +34,12 @@ function setstate(_this, part, userToSend, valueFromSubmenu, SubmenuValuePriorit
22
34
  ack = true;
23
35
  returnText = returnText.replace("ack:true", "");
24
36
  } else if (returnText.includes("ack:false")) {
25
- _this.log.debug("Set sck: " + JSON.stringify(false));
37
+ _this.log.debug("Set ack: " + JSON.stringify(false));
26
38
  ack = false;
27
39
  returnText = element.returnText.replace("ack:false", "").trim();
28
40
  }
29
41
 
30
- if (!returnText.includes('{"id":"')) {
42
+ if (!returnText.includes("{'id':'")) {
31
43
  setStateIds.push({
32
44
  id: element.id,
33
45
  confirm: element.confirm,
@@ -37,7 +49,23 @@ function setstate(_this, part, userToSend, valueFromSubmenu, SubmenuValuePriorit
37
49
  _this.log.debug("setStateIds" + JSON.stringify(setStateIds));
38
50
  } else {
39
51
  try {
40
- const returnObj = JSON.parse(returnText);
52
+ _this.log.debug("Returntext " + JSON.stringify(returnText));
53
+ returnText = returnText.replaceAll("'", '"');
54
+ const textToSend = returnText.slice(0, returnText.indexOf("{"));
55
+ const returnObj = JSON.parse(
56
+ returnText.slice(returnText.indexOf("{"), returnText.indexOf("}") + 1),
57
+ );
58
+ sendToTelegram(
59
+ _this,
60
+ userToSend,
61
+ textToSend,
62
+ undefined,
63
+ telegramInstance,
64
+ one_time_keyboard,
65
+ resize_keyboard,
66
+ userListWithChatID,
67
+ );
68
+ _this.log.debug("JSON parse: " + JSON.stringify(returnObj));
41
69
  setStateIds.push({
42
70
  id: returnObj.id,
43
71
  confirm: true,
package/lib/js/subMenu.js CHANGED
@@ -22,9 +22,18 @@ function subMenu(
22
22
  one_time_keyboard,
23
23
  userListWithChatID,
24
24
  ) {
25
- const splittetText = part.split(`"`)[1].split(":");
26
- const callbackData = splittetText[1];
27
- let device2Switch = splittetText[2];
25
+ _this.log.debug("Part: " + JSON.stringify(part));
26
+ let splittetText = [];
27
+ let callbackData = "";
28
+ let device2Switch = "";
29
+ if (part.includes('"')) {
30
+ splittetText = part.split(`"`)[1].split(":");
31
+ } else {
32
+ splittetText = part.split(":");
33
+ }
34
+ device2Switch = splittetText[2];
35
+ callbackData = splittetText[1];
36
+
28
37
  _this.log.debug("callbackData: " + JSON.stringify(callbackData));
29
38
  _this.log.debug("splittet Data of callbackData " + JSON.stringify(splittetText[1]));
30
39
  _this.log.debug("devicetoswitch: " + JSON.stringify(device2Switch));
@@ -59,7 +68,17 @@ function subMenu(
59
68
  } else {
60
69
  val = splittedData[1].split(".")[1];
61
70
  }
62
- const result = setstate(_this, groupData[device2Switch], userToSend, val, true);
71
+ const result = setstate(
72
+ _this,
73
+ groupData[device2Switch],
74
+ userToSend,
75
+ val,
76
+ true,
77
+ undefined,
78
+ undefined,
79
+ undefined,
80
+ undefined,
81
+ );
63
82
  if (Array.isArray(result)) returnIDToListenTo = result;
64
83
  return [null, null, null, returnIDToListenTo];
65
84
  } else if (callbackData.includes("second")) {
@@ -71,7 +90,17 @@ function subMenu(
71
90
  } else {
72
91
  val = splittedData[2].split(".")[1];
73
92
  }
74
- const result = setstate(_this, groupData[device2Switch], userToSend, val, true);
93
+ const result = setstate(
94
+ _this,
95
+ groupData[device2Switch],
96
+ userToSend,
97
+ val,
98
+ true,
99
+ undefined,
100
+ undefined,
101
+ undefined,
102
+ undefined,
103
+ );
75
104
  if (Array.isArray(result)) returnIDToListenTo = result;
76
105
  return [null, null, null, returnIDToListenTo];
77
106
  }
@@ -109,7 +138,17 @@ function subMenu(
109
138
  } else if (part.includes(`submenu:percent${step}`)) {
110
139
  const value = parseInt(part.split(":")[1].split(",")[1]);
111
140
 
112
- const result = setstate(_this, groupData[device2Switch], userToSend, value, true);
141
+ const result = setstate(
142
+ _this,
143
+ groupData[device2Switch],
144
+ userToSend,
145
+ value,
146
+ true,
147
+ undefined,
148
+ undefined,
149
+ undefined,
150
+ undefined,
151
+ );
113
152
  if (Array.isArray(result)) returnIDToListenTo = result;
114
153
  return [null, null, null, returnIDToListenTo];
115
154
 
@@ -140,10 +179,10 @@ function subMenu(
140
179
  if (i === start) index = end - 1;
141
180
  index++;
142
181
  } else index = i;
143
-
182
+ //FIXME - index eine position nach hinten geschoben
144
183
  menu.push({
145
184
  text: `${index}${unit}`,
146
- callback_data: `submenu:${callbackData}:${index}:${device2Switch}`,
185
+ callback_data: `submenu:${callbackData}:${device2Switch}:${index}`,
147
186
  });
148
187
  rowEntrys++;
149
188
  if (rowEntrys == 8) {
@@ -158,12 +197,24 @@ function subMenu(
158
197
  _this.log.debug("keyboard " + JSON.stringify(keyboard.inline_keyboard));
159
198
  return ["Welcher Wert soll gesetzt werden?", JSON.stringify(keyboard), device2Switch];
160
199
  } else if (part.includes(`submenu:${callbackData}`)) {
161
- const value = parseInt(part.split(":")[2]);
162
- device2Switch = part.split(":")[3];
200
+ _this.log.debug("CallbackData" + JSON.stringify(callbackData));
201
+ //FIXME - value und device2Switch vertauscht
202
+ const value = parseInt(part.split(":")[3]);
203
+ device2Switch = part.split(":")[2];
163
204
  _this.log.debug(
164
205
  JSON.stringify({ device2Switch: device2Switch, data: groupData, user: userToSend, value: value }),
165
206
  );
166
- const result = setstate(_this, groupData[device2Switch], userToSend, value, true);
207
+ const result = setstate(
208
+ _this,
209
+ groupData[device2Switch],
210
+ userToSend,
211
+ value,
212
+ true,
213
+ undefined,
214
+ undefined,
215
+ undefined,
216
+ undefined,
217
+ );
167
218
  if (Array.isArray(result)) returnIDToListenTo = result;
168
219
  return [null, null, null, returnIDToListenTo];
169
220
  }
@@ -18,42 +18,46 @@ function sendToTelegram(
18
18
  one_time_keyboard = true,
19
19
  userListWithChatID,
20
20
  ) {
21
- _this.log.debug("Send this Value : " + JSON.stringify(value));
22
- _this.log.debug("Send this to : " + JSON.stringify(user));
23
- _this.log.debug("Instance : " + JSON.stringify(instance));
24
- let chatId = "";
25
- userListWithChatID.forEach((element) => {
26
- if (element.name === user) chatId = element.chatID;
27
- });
28
- if (keyboard.length == 0) {
29
- _this.sendTo(
30
- instance,
31
- "send",
32
- {
33
- text: value,
34
- chatId: chatId,
35
- },
36
- function (res) {
37
- console.log("Sent Value to " + res + " users!");
38
- },
39
- );
40
- } else {
41
- _this.sendTo(
42
- instance,
43
- "send",
44
- {
45
- chatId: chatId,
46
- text: value,
47
- reply_markup: {
48
- keyboard: keyboard,
49
- resize_keyboard: resize_keyboard,
50
- one_time_keyboard: one_time_keyboard,
21
+ try {
22
+ _this.log.debug("Send this Value : " + JSON.stringify(value));
23
+ _this.log.debug("Send this to : " + JSON.stringify(user));
24
+ _this.log.debug("Instance : " + JSON.stringify(instance));
25
+ let chatId = "";
26
+ userListWithChatID.forEach((element) => {
27
+ if (element.name === user) chatId = element.chatID;
28
+ });
29
+ if (keyboard.length == 0) {
30
+ _this.sendTo(
31
+ instance,
32
+ "send",
33
+ {
34
+ text: value,
35
+ chatId: chatId,
51
36
  },
52
- },
53
- function (res) {
54
- console.log("Sent to " + res + " users");
55
- },
56
- );
37
+ function (res) {
38
+ console.log("Sent Value to " + res + " users!");
39
+ },
40
+ );
41
+ } else {
42
+ _this.sendTo(
43
+ instance,
44
+ "send",
45
+ {
46
+ chatId: chatId,
47
+ text: value,
48
+ reply_markup: {
49
+ keyboard: keyboard,
50
+ resize_keyboard: resize_keyboard,
51
+ one_time_keyboard: one_time_keyboard,
52
+ },
53
+ },
54
+ function (res) {
55
+ console.log("Sent to " + res + " users");
56
+ },
57
+ );
58
+ }
59
+ } catch (e) {
60
+ _this.log.error("Error sendToTelegram: " + JSON.stringify(e));
57
61
  }
58
62
  }
59
63
  /**
package/main.js CHANGED
@@ -46,7 +46,7 @@ class TelegramMenu extends utils.Adapter {
46
46
  async onReady() {
47
47
  this.setState("info.connection", false, true);
48
48
  let instanceTelegram = this.config.instance;
49
- if (instanceTelegram.length == 0) instanceTelegram = "telegram.0";
49
+ if (!instanceTelegram || instanceTelegram.length == 0) instanceTelegram = "telegram.0";
50
50
  const telegramID = `${instanceTelegram}.communicate.request`;
51
51
  const datapoint = `${instanceTelegram}.info.connection`;
52
52
  this.log.debug("Datapoint: " + JSON.stringify(datapoint));
@@ -67,7 +67,7 @@ class TelegramMenu extends utils.Adapter {
67
67
  const groupsWithUsers = this.config.usersInGroup;
68
68
  const textNoEntryFound = this.config.textNoEntry;
69
69
  const userListWithChatID = this.config.userListWithChatID;
70
- const menu = {
70
+ const menuData = {
71
71
  data: {},
72
72
  };
73
73
  const _this = this;
@@ -99,10 +99,10 @@ class TelegramMenu extends utils.Adapter {
99
99
  try {
100
100
  for (const name in nav) {
101
101
  const value = await editArrayButtons(nav[name], this);
102
- if (value) menu.data[name] = await generateNewObjectStructure(_this, value);
103
- this.log.debug("New Structure: " + JSON.stringify(menu.data[name]));
104
- const returnValue = generateActions(_this, action[name], menu.data[name]);
105
- menu.data[name] = returnValue?.obj;
102
+ if (value) menuData.data[name] = await generateNewObjectStructure(_this, value);
103
+ this.log.debug("New Structure: " + JSON.stringify(menuData.data[name]));
104
+ const returnValue = generateActions(_this, action[name], menuData.data[name]);
105
+ menuData.data[name] = returnValue?.obj;
106
106
  subscribeForeignStateIds = returnValue?.ids;
107
107
  this.log.debug("SubscribeForeignStates: " + JSON.stringify(subscribeForeignStateIds));
108
108
  if (subscribeForeignStateIds && subscribeForeignStateIds?.length > 0) {
@@ -110,7 +110,7 @@ class TelegramMenu extends utils.Adapter {
110
110
  } else this.log.debug("Nothing to Subscribe!");
111
111
  this.log.debug("Menu: " + JSON.stringify(name));
112
112
  this.log.debug("Array Buttons: " + JSON.stringify(value));
113
- this.log.debug("Gen. Actions: " + JSON.stringify(menu.data[name]));
113
+ this.log.debug("Gen. Actions: " + JSON.stringify(menuData.data[name]));
114
114
  }
115
115
  } catch (err) {
116
116
  this.log.error("Error generateNav: " + JSON.stringify(err));
@@ -127,11 +127,12 @@ class TelegramMenu extends utils.Adapter {
127
127
  groupsWithUsers[menu].forEach((user) => {
128
128
  backMenuFuc(this, startside, null, user);
129
129
  this.log.debug("User List " + JSON.stringify(userListWithChatID));
130
+
130
131
  sendToTelegram(
131
132
  _this,
132
133
  user,
133
- menu.data[menu][startside].text,
134
- menu.data[menu][startside].nav,
134
+ menuData.data[menu][startside].text,
135
+ menuData.data[menu][startside].nav,
135
136
  instanceTelegram,
136
137
  resize_keyboard,
137
138
  one_time_keyboard,
@@ -188,12 +189,24 @@ class TelegramMenu extends utils.Adapter {
188
189
  this.log.debug("Groups with searched User " + JSON.stringify(groups));
189
190
  let dataFound = false;
190
191
  for (const group of groups) {
191
- const groupData = menu.data[group];
192
+ const groupData = menuData.data[group];
192
193
  this.log.debug("Nav: " + JSON.stringify(groupData));
193
- this.log.debug("Menu: " + JSON.stringify(menu.data));
194
+ this.log.debug("Menu: " + JSON.stringify(menuData.data));
194
195
  this.log.debug("Group: " + JSON.stringify(group));
195
196
 
196
- if (processData(this, groupData, calledValue, userToSend, group)) {
197
+ if (
198
+ processData(
199
+ this,
200
+ groupData,
201
+ calledValue,
202
+ userToSend,
203
+ group,
204
+ instanceTelegram,
205
+ resize_keyboard,
206
+ one_time_keyboard,
207
+ userListWithChatID,
208
+ )
209
+ ) {
197
210
  dataFound = true;
198
211
  break;
199
212
  } else continue;
@@ -290,7 +303,17 @@ class TelegramMenu extends utils.Adapter {
290
303
  * @param {string} groupWithUser Group with the User
291
304
  * @returns true, if data was found, else false
292
305
  */
293
- function processData(_this, groupData, calledValue, userToSend = "", groupWithUser) {
306
+ function processData(
307
+ _this,
308
+ groupData,
309
+ calledValue,
310
+ userToSend = "",
311
+ groupWithUser,
312
+ instanceTelegram,
313
+ resize_keyboard,
314
+ one_time_keyboard,
315
+ userListWithChatID,
316
+ ) {
294
317
  if (groupData[calledValue] && userToSend && groupWithUser && userActiveCheckbox[groupWithUser]) {
295
318
  const part = groupData[calledValue];
296
319
  // Navigation
@@ -298,7 +321,16 @@ class TelegramMenu extends utils.Adapter {
298
321
  _this.log.debug("Menu to Send: " + JSON.stringify(part.nav));
299
322
  backMenuFuc(_this, calledValue, part.nav, userToSend);
300
323
  if (JSON.stringify(part.nav).includes("menu")) {
301
- callSubMenu(_this, JSON.stringify(part.nav), groupData, userToSend);
324
+ callSubMenu(
325
+ _this,
326
+ JSON.stringify(part.nav),
327
+ groupData,
328
+ userToSend,
329
+ instanceTelegram,
330
+ resize_keyboard,
331
+ one_time_keyboard,
332
+ userListWithChatID,
333
+ );
302
334
  return true;
303
335
  } else {
304
336
  if (userToSend) {
@@ -319,7 +351,17 @@ class TelegramMenu extends utils.Adapter {
319
351
  }
320
352
  // Schalten
321
353
  else if (part.switch) {
322
- setStateIdsToListenTo = setstate(_this, part, userToSend, 0, false);
354
+ setStateIdsToListenTo = setstate(
355
+ _this,
356
+ part,
357
+ userToSend,
358
+ 0,
359
+ false,
360
+ instanceTelegram,
361
+ resize_keyboard,
362
+ one_time_keyboard,
363
+ userListWithChatID,
364
+ );
323
365
 
324
366
  _this.log.debug("SubmenuData3" + JSON.stringify(setStateIdsToListenTo));
325
367
  if (Array.isArray(setStateIdsToListenTo))
@@ -372,22 +414,26 @@ class TelegramMenu extends utils.Adapter {
372
414
  } else path = element.fileName;
373
415
  try {
374
416
  const timeout = _this.setTimeout(async () => {
375
- _this.log.debug("Send Pic to Telegram");
376
- sendToTelegram(
377
- _this,
378
- userToSend,
379
- path,
380
- undefined,
381
- instanceTelegram,
382
- resize_keyboard,
383
- one_time_keyboard,
384
- userListWithChatID,
385
- );
417
+ try {
418
+ _this.log.debug("Send Pic to Telegram");
419
+ sendToTelegram(
420
+ _this,
421
+ userToSend,
422
+ path,
423
+ undefined,
424
+ instanceTelegram,
425
+ resize_keyboard,
426
+ one_time_keyboard,
427
+ userListWithChatID,
428
+ );
386
429
 
387
- let timeoutToClear = {};
388
- timeoutToClear = timeouts.filter((item) => item.key == timeoutKey);
389
- clearTimeout(timeoutToClear.timeout);
390
- timeouts = timeouts.filter((item) => item.key !== timeoutKey);
430
+ let timeoutToClear = {};
431
+ timeoutToClear = timeouts.filter((item) => item.key == timeoutKey);
432
+ clearTimeout(timeoutToClear.timeout);
433
+ timeouts = timeouts.filter((item) => item.key !== timeoutKey);
434
+ } catch (e) {
435
+ _this.log.error("Error: " + JSON.stringify(e));
436
+ }
391
437
  }, parseInt(element.delay));
392
438
  _this.log.debug("Timeout add");
393
439
  timeouts.push({ key: timeoutKey, timeout: timeout });
@@ -401,7 +447,17 @@ class TelegramMenu extends utils.Adapter {
401
447
  return true;
402
448
  }
403
449
  } else if (calledValue.startsWith("menu") || calledValue.startsWith("submenu")) {
404
- callSubMenu(_this, calledValue, groupData, userToSend);
450
+ _this.log.debug("Call Submenu");
451
+ callSubMenu(
452
+ _this,
453
+ calledValue,
454
+ groupData,
455
+ userToSend,
456
+ instanceTelegram,
457
+ resize_keyboard,
458
+ one_time_keyboard,
459
+ userListWithChatID,
460
+ );
405
461
  return true;
406
462
  } else {
407
463
  return false;
@@ -414,7 +470,16 @@ class TelegramMenu extends utils.Adapter {
414
470
  * @param {{}} groupData
415
471
  * @param {string} userToSend
416
472
  */
417
- function callSubMenu(_this, part, groupData, userToSend) {
473
+ function callSubMenu(
474
+ _this,
475
+ part,
476
+ groupData,
477
+ userToSend,
478
+ instanceTelegram,
479
+ resize_keyboard,
480
+ one_time_keyboard,
481
+ userListWithChatID,
482
+ ) {
418
483
  const subMenuData = subMenu(
419
484
  _this,
420
485
  part,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.telegram-menu",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Easily create Telegram Menus",
5
5
  "author": {
6
6
  "name": "MiRo1310",
@@ -72,7 +72,8 @@
72
72
  "lint": "eslint .",
73
73
  "translate": "translate-adapter",
74
74
  "release": "release-script",
75
- "lint:fix": "eslint . --fix"
75
+ "lint:fix": "eslint . --fix",
76
+ "checker": "node skript.mjs"
76
77
  },
77
78
  "bugs": {
78
79
  "url": "https://github.com/MiRo1310/ioBroker.telegram-menu/issues"