iobroker.telegram-menu 0.6.10 → 0.7.1

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,16 @@ 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.1 (2023-10-02)
37
+
38
+ - bugfix, Error read UserListTypeError: Cannot read properties of undefined
39
+
40
+ ### 0.7.0 (2023-10-01)
41
+
42
+ - #53 feature: sendPicture von server-path
43
+ - #52 icons are missing, copy data
44
+ - #51 by creating a new Menu, the Users are not shown
45
+
36
46
  ### 0.6.10 (2023-09-23)
37
47
 
38
48
  - bug fix
@@ -168,9 +168,10 @@
168
168
  addNewGroup(menus, newMenu, _onChange)
169
169
  activeMenu = newMenu
170
170
  showUser(newMenu, showHideUserCheckbox)
171
- userListWithChatID = buildUserSelection(valUserFromTelegram, newMenu, usersInMenus)
171
+ userListWithChatID = buildUserSelection(valUserFromTelegram, [newMenu], usersInMenus)
172
172
  translateAll()
173
173
  }
174
+
174
175
  })
175
176
  // Delete Btn, open popup
176
177
  $("#group_menu").on("click", "#deleteUser", function () {
@@ -590,9 +591,13 @@
590
591
  rowToCopy.find("a").parent().remove()
591
592
  const buttonsNav = `<td><a class="deleteRow btn-floating btn-small waves-effect waves-light red"><i class="material-icons">delete</i></a></td>
592
593
  <td><a class="btn-floating btn-small waves-effect waves-light blue btn_down"><i class="material-icons" name="down">arrow_downward</i></a></td>
593
- <td><a class="btn-floating btn-small waves-effect waves-light blue btn_up"><i class="material-icons" name="up">arrow_upward</i></a></td>`
594
+ <td><a class="btn-floating btn-small waves-effect waves-light blue btn_up"><i class="material-icons" name="up">arrow_upward</i></a></td>
595
+ <td><a class="btn-floating btn-small waves-effect waves-light green btn_add_row"><i class="material-icons">add</i></a></td>`
594
596
  const buttonsAction = `<td><a class="deleteEveryRow btn-floating btn-small waves-effect waves-light red"><i class="material-icons">delete</i></a></td>
595
- <td><a data-target="tab_action" class="editEntry modal-trigger btn-floating btn-small waves-effect waves-light green"><i class="material-icons">edit</i></a></td>`;
597
+ <td><a data-target="tab_action" class="editEntry modal-trigger btn-floating btn-small waves-effect waves-light green"><i class="material-icons">edit</i></a></td>
598
+ <td><a class="btn-floating btn-small waves-effect waves-light blue btn_down"><i class="material-icons" name="down">arrow_downward</i></a></td>
599
+ <td><a class="btn-floating btn-small waves-effect waves-light blue btn_up"><i class="material-icons" name="up">arrow_upward</i></a></td> `;
600
+
596
601
  if (action == "nav") {
597
602
  rowToCopy.append(buttonsNav)
598
603
  $(`#${activeMenu}`).append(rowToCopy)
package/io-package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "telegram-menu",
4
- "version": "0.6.10",
4
+ "version": "0.7.1",
5
5
  "news": {
6
+ "0.7.1": {
7
+ "en": "bugfix, Error read UserListTypeError: Cannot read properties of undefined",
8
+ "de": "bugfix, Fehler lesen UserListType Fehler: Nicht zu lesen Eigenschaften von undefiniert",
9
+ "ru": "bugfix, Ошибка читать UserListType Ошибка: Не смогите прочитать свойства неопределенного",
10
+ "pt": "bugfix, Erro lido UserListType Erro: Não é possível ler propriedades indefinidas",
11
+ "nl": "error las UserListType Error: Kan niet onbepaalde eigenschappen lezen",
12
+ "fr": "bugfix, Erreur lire UserListType Erreur: Cannot read properties of undefined",
13
+ "it": "bugfix, Error read UserListType Errore: Proprietà di lettura non definite",
14
+ "es": "bugfix, Error leer UserListType Error: No se pueden leer propiedades indefinidas",
15
+ "pl": "error przeczytał UserListType Error: Cannot czytał właściwości nieokreślone",
16
+ "uk": "javaScript licenses API Веб-сайт Go1.13.8 Помилка: Не можна прочитати властивості невизначених",
17
+ "zh-cn": "bugfix, Error读者 rror: 评 注"
18
+ },
19
+ "0.7.0": {
20
+ "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",
21
+ "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",
22
+ "ru": "#53 функция: sendPicture von server-path\n#52 иконки отсутствуют, копирование данных\n#51, создавая новое меню, Пользователи не отображаются",
23
+ "pt": "Característica #53: sendPicture von server-path\n#52 ícones estão faltando, copiar dados\n#51 criando um novo Menu, os Usuários não são mostrados",
24
+ "nl": "Vertaling:\n52 iconen ontbreken\nQuality over Quantity (QoQ) Releases Vertaling:",
25
+ "fr": "#53 fonction: sendPicture von server-path\n#52 icônes sont manquantes, données de copie\n#51 en créant un nouveau menu, les Utilisateurs ne sont pas affichés",
26
+ "it": "#53 caratteristica: sendPicture von server-path\n#52 icone mancanti, copia dati\n#51 creando un nuovo menu, gli utenti non vengono mostrati",
27
+ "es": "función #53: sendPicture von server-path\n#52 iconos faltan, copiar datos\n#51 mediante la creación de un nuevo Menú, los Usuarios no se muestran",
28
+ "pl": "#53: Wysyłanie serwera\nzaginęło 52 ikony\n#51 poprzez stworzenie nowego Menu, Użytkownicy nie zostali przedstawieni",
29
+ "uk": "#53 Функція: sendPicture фон сервер-path\n#52 іконки відсутні, копіювання даних\n#51 шляхом створення нового меню Користувачі не показані",
30
+ "zh-cn": "#53 特色:寄电器\n第52条 遗漏,复印数据\n第51号活动是创建一个新的男子,用户没有证明。"
31
+ },
6
32
  "0.6.10": {
7
33
  "en": "bug fix",
8
34
  "de": "fehlerbehebung",
@@ -67,32 +93,6 @@
67
93
  "pl": "info-big.png",
68
94
  "uk": "javascript licenses api веб-сайт go1.13.8",
69
95
  "zh-cn": "增 编"
70
- },
71
- "0.6.5": {
72
- "en": "get user by chatID and send back to this chatID",
73
- "de": "benutzer per chatID ermitteln und zurück senden an diese chatID",
74
- "ru": "получить пользователя по чатID и отправить обратно в этот чатID",
75
- "pt": "obter usuário por chatID e enviar de volta para este chatID",
76
- "nl": "haal gebruiker van chatID en stuur terug naar dit chatID",
77
- "fr": "obtenir utilisateur par chatID et renvoyer à ce chatID",
78
- "it": "ottenere l'utente da chatID e tornare a questo chatID",
79
- "es": "obtener usuario por chatID y enviar de nuevo a este chatID",
80
- "pl": "użytkowanie przez czat i wysyłane do tego czatID",
81
- "uk": "отримати користувач по chatID і відправити назад в цей чатID",
82
- "zh-cn": "被混乱者利用,然后再送给这一混乱的裁研所。"
83
- },
84
- "0.6.4": {
85
- "en": "Trigger check, used triggers are no longer available in action, in nav it is visualized that the trigger is already in use",
86
- "de": "Trigger-Check, verwendete Trigger sind nicht mehr in Aktion, in nav wird visualisiert, dass der Trigger bereits im Einsatz ist",
87
- "ru": "Проверка Trigger, используемые триггеры больше не доступны в действии, в nav визуализируется, что триггер уже используется",
88
- "pt": "Verificação de gatilho, gatilhos usados não estão mais disponíveis em ação, nav é visualizado que o gatilho já está em uso",
89
- "nl": "Trigger controle, gebruikte triggers zijn niet meer beschikbaar in actie, in Nav is het gevisualiseerd dat de trekker al gebruikt is",
90
- "fr": "Trigger check, triggers utilisés ne sont plus disponibles en action, dans nav il est visualisé que le trigger est déjà en service",
91
- "it": "Controllo del trigger, i trigger utilizzati non sono più disponibili in azione, in nav è visualizzato che il trigger è già in uso",
92
- "es": "Comprobación del desencadenante, los disparadores usados ya no están disponibles en acción, en nav se visualiza que el gatillo ya está en uso",
93
- "pl": "Kontrola Triggera nie jest już dostępna w akcji, w nav jest wizualizowana, że wyzwalanie jest już w użyciu",
94
- "uk": "Перевірка тригера, використовувані тригери більше не доступні в дії, в нав він візуалізований, що тригер вже в використанні",
95
- "zh-cn": "突然的检查不再可供采取行动,在无知的情况下,触发者已经使用。"
96
96
  }
97
97
  },
98
98
  "titleLang": {
package/lib/js/action.js CHANGED
@@ -1,8 +1,10 @@
1
1
  const sendToTelegram = require("./telegram").sendToTelegram;
2
+ const Utils = require("./global");
2
3
  /**
3
- *
4
- * @param {string} textToSend
5
- * @param {string} val
4
+ * Calculates Value with the Value in {math:} from textToSend
5
+ * @param {string} textToSend Text to send to user
6
+ * @param {string} val Value to calculate with
7
+ * @returns {object} textToSend and val
6
8
  */
7
9
  function calcValue(_this, textToSend, val) {
8
10
  const startindex = textToSend.indexOf("{math");
@@ -19,33 +21,29 @@ function calcValue(_this, textToSend, val) {
19
21
  }
20
22
 
21
23
  /**
22
- *
24
+ * Exchange Value with other Value
23
25
  * @param {String} textToSend Text which should be send to user
26
+ * @param {String} stateVal Value to exchange
27
+ * @param {*} _this
28
+ * @returns {object} valueChange and textToSend
24
29
  */
25
30
  function exchangeValue(textToSend, stateVal, _this) {
26
31
  const startindex = textToSend.indexOf("change{");
27
32
  const match = textToSend.substring(startindex + "change".length + 1, textToSend.indexOf("}", startindex));
28
33
  let objChangeValue;
29
- if (isJSON("{" + match + "}")) objChangeValue = JSON.parse("{" + match + "}");
34
+ if (Utils.isJSON("{" + match + "}")) objChangeValue = JSON.parse("{" + match + "}");
30
35
  else {
31
- _this.log.error(`There is a error in your input: ` + JSON.stringify(match.replace(/"/g, "'")));
36
+ _this.log.error(`There is a error in your input: ` + JSON.stringify(Utils.replaceAll(match, '"', "'")));
32
37
  return false;
33
38
  }
34
39
  return { valueChange: objChangeValue[String(stateVal)], textToSend: textToSend.substring(0, startindex) };
35
40
  }
36
- function isJSON(str) {
37
- try {
38
- JSON.parse(str);
39
- return true;
40
- } catch (error) {
41
- return false;
42
- }
43
- }
41
+
44
42
  /**
45
43
  * Generate Array
46
- * @param {*} val
44
+ * @param {object[]} val
47
45
  * @param {*} _this
48
- * @returns
46
+ * @returns Arrays with Buttons
49
47
  */
50
48
  async function editArrayButtons(val, _this) {
51
49
  try {
@@ -76,10 +74,10 @@ async function editArrayButtons(val, _this) {
76
74
  /**
77
75
  *
78
76
  * @param {*} _this
79
- * @param {string} selector
80
- * @param {*} text
81
- * @param {*} userToSend
82
- * @param {*} newline
77
+ * @param {string} selector Selector
78
+ * @param {string} text Text to send
79
+ * @param {string} userToSend User to send
80
+ * @param {string} newline Newline
83
81
  */
84
82
  const idBySelector = async (
85
83
  _this,
@@ -122,7 +120,7 @@ const idBySelector = async (
122
120
  text2Send += " " + value.val;
123
121
  }
124
122
  }
125
- if (newline == "true" || newline == true) text2Send += "\n";
123
+ if (newline == "true") text2Send += "\n";
126
124
  else text2Send += " ";
127
125
  _this.log.debug("text2send " + JSON.stringify(text2Send));
128
126
  });
@@ -156,7 +154,8 @@ const idBySelector = async (
156
154
  /**
157
155
  *
158
156
  * @param {*} _this
159
- * @param {array} val
157
+ * @param {array} val Array with Objects
158
+ * @returns Object with new Structure
160
159
  */
161
160
  async function generateNewObjectStructure(_this, val) {
162
161
  try {
@@ -176,9 +175,10 @@ async function generateNewObjectStructure(_this, val) {
176
175
  }
177
176
 
178
177
  /**
179
- *
178
+ * Generate Actions
180
179
  * @param {object} action Object with Actions
181
- * @param {*} userObject Object from User with generated Navigation
180
+ * @param {object} userObject Object from User with generated Navigation
181
+ * @returns {object} Object with Actions and IDs
182
182
  */
183
183
  function generateActions(_this, action, userObject) {
184
184
  try {
@@ -223,7 +223,6 @@ function generateActions(_this, action, userObject) {
223
223
  });
224
224
  });
225
225
  action.pic.forEach(function (element, key) {
226
- _this.log.debug("Pic ");
227
226
  userObject[element.trigger] = { sendPic: [] };
228
227
  if (key == 0) userObject[element.trigger] = { sendPic: [] };
229
228
  element.IDs.forEach(function (id, key) {
@@ -3,6 +3,16 @@ const idBySelector = require("./action").idBySelector;
3
3
  const exchangeValue = require("./action").exchangeValue;
4
4
  const calcValue = require("./action").calcValue;
5
5
 
6
+ /**
7
+ * Get the state of the id and send it to the user
8
+ * @param {*} _this
9
+ * @param {object} part Part of the Menu
10
+ * @param {string} userToSend User to send the message to
11
+ * @param {string} telegramInstance Instance to send the message to
12
+ * @param {boolean} one_time_keyboard
13
+ * @param {boolean} resize_keyboard
14
+ * @param {object} userListWithChatID Userlist with ChatID
15
+ */
6
16
  function getstate(_this, part, userToSend, telegramInstance, one_time_keyboard, resize_keyboard, userListWithChatID) {
7
17
  try {
8
18
  let text = "";
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Removes duplicate entries and saves the result
3
+ * @param {string[]} arr Array
4
+ * @returns Array with unique entrys
5
+ */
6
+ function deleteDoubleEntrysInArray(arr, _this) {
7
+ return arr.filter((item, index) => arr.indexOf(item) === index);
8
+ }
9
+
10
+ /**
11
+ * Replaces all searchValue with replaceValue in text
12
+ * @param {string} text Text to replace the searchValue with replaceValue
13
+ * @param {string} searchValue Value to search for
14
+ * @param {string} replaceValue Value to replace the searchValue with
15
+ * @returns
16
+ */
17
+ function replaceAll(text, searchValue, replaceValue) {
18
+ return text.replace(new RegExp(searchValue, "g"), replaceValue);
19
+ }
20
+ /**
21
+ * Checks if _string is JSON
22
+ * @param {string} _string
23
+ * @returns {boolean} Returns True if _string is JSON else False
24
+ */
25
+ function isJSON(_string) {
26
+ try {
27
+ JSON.parse(_string);
28
+ return true;
29
+ } catch (error) {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ module.exports = { deleteDoubleEntrysInArray, replaceAll, isJSON };
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Sets the state
3
+ * @param {*} _this
4
+ * @param {object} part Part of the menu
5
+ * @param {string} userToSend User to send the message to
6
+ * @param {number} valueFromSubmenu Value from the submenu
7
+ * @param {boolean} SubmenuValuePriority If true the value from the submenu will be used else the value from the switch
8
+ * @returns Returns an array with the ids to set
9
+ */
1
10
  function setstate(_this, part, userToSend, valueFromSubmenu, SubmenuValuePriority) {
2
11
  try {
3
12
  const setStateIds = [];
package/lib/js/subMenu.js CHANGED
@@ -7,14 +7,14 @@ const backMenu = {};
7
7
  /**
8
8
  *
9
9
  * @param {*} _this
10
- * @param {string} text
11
- * @param {*} groupData
12
- * @param {string} userToSend
13
- * @returns
10
+ * @param {string} part
11
+ * @param {{}} groupData - Data of the group
12
+ * @param {string} userToSend - user to send the message to
13
+ * @returns []
14
14
  */
15
15
  function subMenu(
16
16
  _this,
17
- text,
17
+ part,
18
18
  groupData,
19
19
  userToSend,
20
20
  instanceTelegram,
@@ -22,13 +22,13 @@ function subMenu(
22
22
  one_time_keyboard,
23
23
  userListWithChatID,
24
24
  ) {
25
- const splittetText = JSON.stringify(text).split(`"`)[1].split(":");
25
+ const splittetText = part.split(`"`)[1].split(":");
26
26
  const callbackData = splittetText[1];
27
27
  let device2Switch = splittetText[2];
28
28
  _this.log.debug("callbackData: " + JSON.stringify(callbackData));
29
29
  _this.log.debug("splittet Data of callbackData " + JSON.stringify(splittetText[1]));
30
30
  _this.log.debug("devicetoswitch: " + JSON.stringify(device2Switch));
31
- _this.log.debug("text: " + JSON.stringify(text));
31
+ _this.log.debug("text: " + JSON.stringify(part));
32
32
 
33
33
  //ANCHOR - Switch
34
34
 
@@ -77,7 +77,7 @@ function subMenu(
77
77
  }
78
78
 
79
79
  //ANCHOR - Percent
80
- else if (!text.includes("submenu") && callbackData.includes("percent")) {
80
+ else if (!part.includes("submenu") && callbackData.includes("percent")) {
81
81
  step = parseInt(callbackData.replace("percent", ""));
82
82
  let rowEntrys = 0;
83
83
  let menu = [];
@@ -106,15 +106,15 @@ function subMenu(
106
106
  if (rowEntrys != 0) keyboard.inline_keyboard.push(menu);
107
107
 
108
108
  return ["Welcher Wert soll gesetzt werden?", JSON.stringify(keyboard), device2Switch];
109
- } else if (text.includes(`submenu:percent${step}`)) {
110
- const value = parseInt(text.split(":")[1].split(",")[1]);
109
+ } else if (part.includes(`submenu:percent${step}`)) {
110
+ const value = parseInt(part.split(":")[1].split(",")[1]);
111
111
 
112
112
  const result = setstate(_this, groupData[device2Switch], userToSend, value, true);
113
113
  if (Array.isArray(result)) returnIDToListenTo = result;
114
114
  return [null, null, null, returnIDToListenTo];
115
115
 
116
116
  //ANCHOR - Number
117
- } else if (!text.includes("submenu") && callbackData.includes("number")) {
117
+ } else if (!part.includes("submenu") && callbackData.includes("number")) {
118
118
  const splittedData = callbackData.replace("number", "").split("-");
119
119
  let rowEntrys = 0;
120
120
  let menu = [];
@@ -157,9 +157,9 @@ function subMenu(
157
157
  if (rowEntrys != 0) keyboard.inline_keyboard.push(menu);
158
158
  _this.log.debug("keyboard " + JSON.stringify(keyboard.inline_keyboard));
159
159
  return ["Welcher Wert soll gesetzt werden?", JSON.stringify(keyboard), device2Switch];
160
- } else if (text.includes(`submenu:${callbackData}`)) {
161
- const value = parseInt(text.split(":")[2]);
162
- device2Switch = text.split(":")[3];
160
+ } else if (part.includes(`submenu:${callbackData}`)) {
161
+ const value = parseInt(part.split(":")[2]);
162
+ device2Switch = part.split(":")[3];
163
163
  _this.log.debug(
164
164
  JSON.stringify({ device2Switch: device2Switch, data: groupData, user: userToSend, value: value }),
165
165
  );
@@ -18,44 +18,57 @@ 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,
36
+ },
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
+ },
51
53
  },
52
- },
53
- function (res) {
54
- console.log("Sent to " + res + " users");
55
- },
56
- );
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
  }
63
+ /**
64
+ *
65
+ * @param {*} _this
66
+ * @param {string} user Username
67
+ * @param {string} text Text to send
68
+ * @param {*} keyboard
69
+ * @param {*} instance
70
+ * @param {*} userListWithChatID
71
+ */
59
72
  function sendToTelegramSubmenu(_this, user, text, keyboard, instance = "telegram.0", userListWithChatID) {
60
73
  try {
61
74
  let chatId = "";
package/main.js CHANGED
@@ -19,6 +19,7 @@ const getstate = require("./lib/js/getstate").getstate;
19
19
  const subMenu = require("./lib/js/subMenu").subMenu;
20
20
  const backMenuFuc = require("./lib/js/subMenu").backMenuFuc;
21
21
  const sendToTelegramSubmenu = require("./lib/js/telegram").sendToTelegramSubmenu;
22
+ const Utils = require("./lib/js/global");
22
23
 
23
24
  let timeouts = [];
24
25
  let timeoutKey = 0;
@@ -58,21 +59,20 @@ class TelegramMenu extends utils.Adapter {
58
59
  const one_time_keyboard = checkbox["oneTiKey"];
59
60
  const resize_keyboard = checkbox["resKey"];
60
61
  const checkboxNoEntryFound = checkbox["checkboxNoValueFound"];
61
- const listofGroups = this.config.users;
62
+ const listofMenus = this.config.users;
62
63
  const startsides = this.config.startsides;
63
- let token = this.config.tokenGrafana;
64
+ const token = this.config.tokenGrafana;
64
65
  const directoryPicture = this.config.directory;
65
66
  const userActiveCheckbox = this.config.userActiveCheckbox;
66
67
  const groupsWithUsers = this.config.usersInGroup;
67
68
  const textNoEntryFound = this.config.textNoEntry;
68
69
  const userListWithChatID = this.config.userListWithChatID;
69
- const menu = {
70
+ const menuData = {
70
71
  data: {},
71
72
  };
72
73
  const _this = this;
73
74
  this.getForeignObject(datapoint, async (err, obj) => {
74
75
  if (err || obj == null) {
75
- // Error
76
76
  this.log.error(JSON.stringify(err));
77
77
  this.log.error(`The State ${datapoint} was not found!`);
78
78
  } else {
@@ -80,7 +80,7 @@ class TelegramMenu extends utils.Adapter {
80
80
  try {
81
81
  telegramState = await this.getForeignStateAsync(datapoint);
82
82
  } catch (e) {
83
- this.log.debug("Error " + JSON.stringify(e));
83
+ this.log.error("Error getForeignState: " + JSON.stringify(e));
84
84
  }
85
85
  telegramAktiv = telegramState?.val;
86
86
  if (!telegramAktiv) {
@@ -99,17 +99,18 @@ 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
- 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
- if (subscribeForeignStateIds && subscribeForeignStateIds?.length > 0)
108
- _subscribeForeignStatesAsync(subscribeForeignStateIds, _this);
109
107
  this.log.debug("SubscribeForeignStates: " + JSON.stringify(subscribeForeignStateIds));
108
+ if (subscribeForeignStateIds && subscribeForeignStateIds?.length > 0) {
109
+ _subscribeForeignStatesAsync(subscribeForeignStateIds, _this);
110
+ } else this.log.debug("Nothing to Subscribe!");
110
111
  this.log.debug("Menu: " + JSON.stringify(name));
111
112
  this.log.debug("Array Buttons: " + JSON.stringify(value));
112
- this.log.debug("Gen. Actions: " + JSON.stringify(menu.data[name]));
113
+ this.log.debug("Gen. Actions: " + JSON.stringify(menuData.data[name]));
113
114
  }
114
115
  } catch (err) {
115
116
  this.log.error("Error generateNav: " + JSON.stringify(err));
@@ -117,27 +118,32 @@ class TelegramMenu extends utils.Adapter {
117
118
  this.log.debug("Checkbox " + JSON.stringify(checkbox));
118
119
 
119
120
  try {
120
- this.log.debug("MenuList: " + JSON.stringify(listofGroups));
121
- listofGroups.forEach((group) => {
122
- this.log.debug("Menu: " + JSON.stringify(group));
123
- const startside = [startsides[group]].toString();
124
- if (userActiveCheckbox[group] && startside != "-") {
121
+ this.log.debug("MenuList: " + JSON.stringify(listofMenus));
122
+ listofMenus.forEach((menu) => {
123
+ this.log.debug("Menu: " + JSON.stringify(menu));
124
+ const startside = [startsides[menu]].toString();
125
+ if (userActiveCheckbox[menu] && startside != "-") {
125
126
  this.log.debug("Startseite: " + JSON.stringify(startside));
126
- groupsWithUsers[group].forEach((user) => {
127
+ groupsWithUsers[menu].forEach((user) => {
127
128
  backMenuFuc(this, startside, null, user);
128
129
  this.log.debug("User List " + JSON.stringify(userListWithChatID));
130
+
129
131
  sendToTelegram(
130
132
  _this,
131
133
  user,
132
- menu.data[group][startside].text,
133
- menu.data[group][startside].nav,
134
+ menuData.data[menu][startside].text,
135
+ menuData.data[menu][startside].nav,
134
136
  instanceTelegram,
135
137
  resize_keyboard,
136
138
  one_time_keyboard,
137
139
  userListWithChatID,
138
140
  );
139
141
  });
140
- }
142
+ } else
143
+ this.log.debug(
144
+ "Menu inactive or is Submenu. " +
145
+ JSON.stringify({ active: userActiveCheckbox[menu], startside: startside }),
146
+ );
141
147
  });
142
148
  } catch (error) {
143
149
  this.log.error("Error read UserList" + error);
@@ -183,9 +189,9 @@ class TelegramMenu extends utils.Adapter {
183
189
  this.log.debug("Groups with searched User " + JSON.stringify(groups));
184
190
  let dataFound = false;
185
191
  for (const group of groups) {
186
- const groupData = menu.data[group];
192
+ const groupData = menuData.data[group];
187
193
  this.log.debug("Nav: " + JSON.stringify(groupData));
188
- this.log.debug("Menu: " + JSON.stringify(menu.data));
194
+ this.log.debug("Menu: " + JSON.stringify(menuData.data));
189
195
  this.log.debug("Group: " + JSON.stringify(group));
190
196
 
191
197
  if (processData(this, groupData, calledValue, userToSend, group)) {
@@ -293,7 +299,7 @@ class TelegramMenu extends utils.Adapter {
293
299
  _this.log.debug("Menu to Send: " + JSON.stringify(part.nav));
294
300
  backMenuFuc(_this, calledValue, part.nav, userToSend);
295
301
  if (JSON.stringify(part.nav).includes("menu")) {
296
- callSubMenu(_this, part.nav, groupData, userToSend);
302
+ callSubMenu(_this, JSON.stringify(part.nav), groupData, userToSend);
297
303
  return true;
298
304
  } else {
299
305
  if (userToSend) {
@@ -314,7 +320,7 @@ class TelegramMenu extends utils.Adapter {
314
320
  }
315
321
  // Schalten
316
322
  else if (part.switch) {
317
- setStateIdsToListenTo = setstate(_this, part, userToSend);
323
+ setStateIdsToListenTo = setstate(_this, part, userToSend, 0, false);
318
324
 
319
325
  _this.log.debug("SubmenuData3" + JSON.stringify(setStateIdsToListenTo));
320
326
  if (Array.isArray(setStateIdsToListenTo))
@@ -332,36 +338,40 @@ class TelegramMenu extends utils.Adapter {
332
338
  );
333
339
  return true;
334
340
  } else if (part.sendPic) {
335
- try {
336
- _this.log.debug("Send Picture");
341
+ _this.log.debug("Send Picture");
337
342
 
338
- part.sendPic.forEach((element) => {
339
- // this.log.debug("Element " + JSON.stringify(element));
340
- token = token.trim();
343
+ part.sendPic.forEach((element) => {
344
+ let path = "";
345
+ if (element.id != "-") {
341
346
  const url = element.id;
342
- const newUrl = url.replace(/&amp;/g, "&");
343
- exec(
344
- `curl -H "Authorisation: Bearer ${token}" "${newUrl}" > ${directoryPicture}${element.fileName}`,
345
- (error, stdout, stderr) => {
346
- if (stdout) {
347
- _this.log.debug("Stdout: " + JSON.stringify(stdout));
348
- }
349
- if (stderr) {
350
- _this.log.debug("Stderr: " + JSON.stringify(stderr));
351
- }
352
- if (error) {
353
- _this.log.error("Ein Fehler ist aufgetreten: " + JSON.stringify(error));
354
- return;
355
- }
356
- },
357
- );
347
+ const newUrl = Utils.replaceAll(url, "&amp;", "&");
348
+ try {
349
+ exec(
350
+ `curl -H "Authorisation: Bearer ${token.trim()}" "${newUrl}" > ${directoryPicture}${
351
+ element.fileName
352
+ }`,
353
+ (error, stdout, stderr) => {
354
+ if (stdout) {
355
+ _this.log.debug("Stdout: " + JSON.stringify(stdout));
356
+ }
357
+ if (stderr) {
358
+ _this.log.debug("Stderr: " + JSON.stringify(stderr));
359
+ }
360
+ if (error) {
361
+ _this.log.error("Ein Fehler ist aufgetreten: " + JSON.stringify(error));
362
+ return;
363
+ }
364
+ },
365
+ );
366
+ } catch (e) {
367
+ _this.log.error("Error :" + JSON.stringify(e));
368
+ }
358
369
 
359
- _this.log.debug(
360
- "url " +
361
- `curl -H "Authorisation: Bearer ${token}" "${newUrl}" > ${directoryPicture}${element.fileName}`,
362
- );
370
+ _this.log.debug("Delay Time " + JSON.stringify(element.delay));
363
371
  timeoutKey += 1;
364
- const path = `${directoryPicture}${element.fileName}`;
372
+ path = `${directoryPicture}${element.fileName}`;
373
+ } else path = element.fileName;
374
+ try {
365
375
  const timeout = _this.setTimeout(async () => {
366
376
  _this.log.debug("Send Pic to Telegram");
367
377
  sendToTelegram(
@@ -379,13 +389,17 @@ class TelegramMenu extends utils.Adapter {
379
389
  timeoutToClear = timeouts.filter((item) => item.key == timeoutKey);
380
390
  clearTimeout(timeoutToClear.timeout);
381
391
  timeouts = timeouts.filter((item) => item.key !== timeoutKey);
382
- }, element.delay);
392
+ }, parseInt(element.delay));
393
+ _this.log.debug("Timeout add");
383
394
  timeouts.push({ key: timeoutKey, timeout: timeout });
384
- });
385
- return true;
386
- } catch (e) {
387
- _this.log.error("Error :" + JSON.stringify(e));
388
- }
395
+ } catch (e) {
396
+ _this.log.error("Error: " + JSON.stringify(e));
397
+ }
398
+ });
399
+
400
+ _this.log.debug("Picture sended");
401
+
402
+ return true;
389
403
  }
390
404
  } else if (calledValue.startsWith("menu") || calledValue.startsWith("submenu")) {
391
405
  callSubMenu(_this, calledValue, groupData, userToSend);
@@ -397,8 +411,8 @@ class TelegramMenu extends utils.Adapter {
397
411
  /**
398
412
  *
399
413
  * @param {*} _this
400
- * @param {*} part
401
- * @param {*} groupData
414
+ * @param {string} part
415
+ * @param {{}} groupData
402
416
  * @param {string} userToSend
403
417
  */
404
418
  function callSubMenu(_this, part, groupData, userToSend) {
@@ -419,7 +433,7 @@ class TelegramMenu extends utils.Adapter {
419
433
  if (subMenuData[3]) setStateIdsToListenTo = subMenuData[3];
420
434
  _subscribeAndUnSubscribeForeignStatesAsync(setStateIdsToListenTo, _this, true);
421
435
  }
422
- if (subMenuData && subMenuData[0]) {
436
+ if (subMenuData && typeof subMenuData[0] == "string") {
423
437
  sendToTelegramSubmenu(
424
438
  _this,
425
439
  userToSend,
@@ -433,25 +447,17 @@ class TelegramMenu extends utils.Adapter {
433
447
 
434
448
  /**
435
449
  *
436
- * @param {*} array
450
+ * @param {string[]} array
437
451
  * @param {*} _this
438
452
  */
439
453
  function _subscribeForeignStatesAsync(array, _this) {
440
- array = deleteDoubleEntrysInArray(array);
441
- _this.log.debug("array " + JSON.stringify(array));
454
+ array = Utils.deleteDoubleEntrysInArray(array, _this);
455
+ _this.log.debug("Subscribe all States of: " + JSON.stringify(array));
442
456
  array.forEach((element) => {
443
- _this.log.debug("Subscribe State: " + JSON.stringify(element));
444
457
  _this.subscribeForeignStatesAsync(element);
445
458
  });
446
459
  }
447
- /**
448
- * Removes duplicate entries and saves the result
449
- * @param {[]} arr Array
450
- * @returns Array with unique entrys
451
- */
452
- function deleteDoubleEntrysInArray(arr) {
453
- return arr.filter((item, index) => arr.indexOf(item) === index);
454
- }
460
+
455
461
  /**
456
462
  *
457
463
  * @param {any[]} array
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.telegram-menu",
3
- "version": "0.6.10",
3
+ "version": "0.7.1",
4
4
  "description": "Easily create Telegram Menus",
5
5
  "author": {
6
6
  "name": "MiRo1310",
@@ -34,22 +34,24 @@
34
34
  "@types/chai": "^4.3.5",
35
35
  "@types/chai-as-promised": "^7.1.5",
36
36
  "@types/jquery": "^3.5.16",
37
- "@types/mocha": "^10.0.1",
37
+ "@types/mocha": "^10.0.2",
38
38
  "@types/node": "^20.3.3",
39
- "@types/proxyquire": "^1.3.28",
39
+ "@types/proxyquire": "^1.3.29",
40
40
  "@types/sinon": "^10.0.15",
41
- "@types/sinon-chai": "^3.2.9",
41
+ "@types/sinon-chai": "^3.2.10",
42
42
  "chai": "^4.3.7",
43
43
  "chai-as-promised": "^7.1.1",
44
- "eslint": "^8.48.0",
44
+ "eslint": "^8.50.0",
45
45
  "eslint-config-prettier": "^9.0.0",
46
- "eslint-plugin-prettier": "^4.2.1",
46
+ "eslint-plugin-prettier": "^5.0.0",
47
47
  "mocha": "^10.2.0",
48
48
  "prettier": "^3.0.3",
49
49
  "proxyquire": "^2.1.3",
50
50
  "sinon": "^15.2.0",
51
51
  "sinon-chai": "^3.7.0",
52
- "typescript": "~5.2.2"
52
+ "typescript": "~5.2.2",
53
+ "chalk": "^5.3.0",
54
+ "inquirer": "^9.2.11"
53
55
  },
54
56
  "main": "main.js",
55
57
  "files": [
@@ -70,7 +72,8 @@
70
72
  "lint": "eslint .",
71
73
  "translate": "translate-adapter",
72
74
  "release": "release-script",
73
- "lint:fix": "eslint . --fix"
75
+ "lint:fix": "eslint . --fix",
76
+ "checker": "node skript.mjs"
74
77
  },
75
78
  "bugs": {
76
79
  "url": "https://github.com/MiRo1310/ioBroker.telegram-menu/issues"