2016-12-01 86 views
3

首先,我不是一個技術的傢伙,所以我需要爲假人的幫助=)包含在返回false

我做了一個項目,我從GIT克隆的,與一個機器人的工作。

事實是,在某些時候,這個機器人使用包含功能,但這是行不通的。使用谷歌我能夠把日誌,並看到實際上該列表包含字符串,但它總是返回false。

這是函數:

var isFromUser = contains(cm.config.users, username, 'exists') 

這是 「日誌」

username: 230592242 
cm.config.bot.owner: 9587763 
isFromOwner: false 
cm.config.users: 230592242 
isFromUser: false 

正如你可以看到,用戶在registersd用戶,但它返回false。

這些都是我使用NPE的庫:

drwxr-xr-x 4 root root 110 Nov 29 16:58 chokidar 
drwxr-xr-x 4 root root 135 Nov 29 16:58 easylogger 
drwxr-xr-x 6 root root 164 Nov 29 16:58 easywizard 
drwxr-xr-x 3 root root 105 Nov 29 16:58 jsonfile-config-manager 
drwxr-xr-x 2 root root 107 Nov 29 16:58 multiple-contains 
drwxr-xr-x 5 root root 121 Nov 29 16:58 winston 

蘊含功能:

// Compare item with filter or another item 
var checkItem = function(item, itemOrFilter) { 

    // Defining array of filters 
    var filters = [] 
    if (!Array.isArray(itemOrFilter)) { 
    if (itemOrFilter.key != undefined) 
     filters.push(itemOrFilter) 
    } else { 
    filters = itemOrFilter 
    } 

    // Filtering 
    if (filters.length > 0) { 
    var i = 0 
    var match = true 
    while (match && i < filters.length) { 
     match = (item[filters[i].key] === filters[i].value) 
     i++ 
    } 
    return match 
    } 

    // Matching 
    else { 
    return (JSON.stringify(item) === JSON.stringify(itemOrFilter)) 
    } 
} 

// Search item in array. 
var searchInArray = function(array, itemOrFilter, mode) { 
    var found = { "index": -1, "filtered": []} 
    var i = 0 
    var end = false 
    while (i < array.length && !end) { 
    end = (mode != 'filter' && mode != 'repetitions' && found.index != -1) 
    if (checkItem(array[i], itemOrFilter)) { 
     found.index = i 
     found.filtered.push(array[i]) 
    } 
    i++ 
    } 
    return found 
} 

// Search substring or char in string. 
var searchInString = function(string, item, mode) { 
    var filtered = string.match(new RegExp(item, 'g')) 
    var index = (filtered) ? string.indexOf(filtered[0]) : -1 
    var found = { "index": index 
       , "filtered": filtered || [] 
       } 
    return found 
} 

// Search digit or subnumber in number. 
var searchInNumber = function(number, item, mode) { 
    var strnumber = number.toString() 
    return searchInString(strnumber, item) 
} 


// Main function 
module.exports = function contains (container, item, mode) { 

    mode = (mode || 'index') 
    var found = { "index": -1, "filtered": []} 

    // Searching in number 
    if (typeof container == "number") 
    found = searchInNumber(container, item, mode) 

    // Searching in string 
    else if (typeof container == "string" || container instanceof String) 
    found = searchInString(container, item, mode) 

    // Searching in array 
    else if (Array.isArray(container)) 
    found = searchInArray(container, item, mode) 
    else console.log("Container type not allowed") 

    // TODO: Search into object's properties 
    //else if (container instanceof Object) found = searchInObject(container, item) 

    if (mode == 'exists') return found.filtered.length > 0 
    if (mode == 'index') return found.index 
    if (mode == 'filter') return found.filtered 
    if (mode == 'repetitions') return found.filtered.length 
    console.log("Mode not allowed") 
    return null 
} 

這些都是我沒有實現的日誌:

// Filtering Messages 
  var filterMessages = function(message) { 
    // Formating message and preparing variables 
    var username = (!message.from.username) ? message.from.id : message.from.username 
    var messageToLog = logger.prepareMessage(message) 
    // Checking message 
    console.log('username: ' + username) 
    console.log('cm.config.bot.owner: ' + cm.config.bot.owner) 
    var isFromOwner = (username == cm.config.bot.owner) 
    console.log('isFromOwner: ' + isFromOwner) 
    console.log('cm.config.users: ' + cm.config.users) 
    var isFromUser = contains(cm.config.users, username, 'exists') 
    console.log('isFromUser: ' + isFromUser) 
    var isCommand = (message.text && message.text.charAt(0) == '/' && message.text.length > 1) 
    var activeUser = cmm.getActiveUserIdx(username) 

這是輸出日誌:

username: 230592242 
cm.config.bot.owner: 9587763 
isFromOwner: false 
cm.config.users: 230592242 
isFromUser: false 

控制檯出的消息,其中所述用戶名,檢索例如:

完整的日誌輸出,具有用戶信息:

username: 230592242 
cm.config.bot.owner: 9587763 
isFromOwner: false 
cm.config.users: 230592242 
isFromUser: false 
into the condition !isFromOwner && !isFromUser 
[info] - [msg_1566] @230592242 : /ventas 2016-11-30 
returning... 
[info] - [msg_1567] @IBM_monitor_bot : Sorry, this is a private bot. 
     [msg_1567] @IBM_monitor_bot : You need an authorization to use it 

屬性用戶文件:用戶的

// Loading config 
  cm.addFile(cfgPath + 'literals.json', null, true) 
  cm.addFile(cfgPath + 'users.json', null, true) 
  cm.addFile(cfgPath + 'bot.json', null, true, buildBot) 
} 

內容。 json文件:

[ 
     "230592242" 
] 

樣品的消息:

[信息] - [msg_1566] @ 230592242:/塔斯二○一六年十一月三十○日

消息製備:

// Filtering Messages 
var filterMessages = function(message) { 
// Formating message and preparing variables 
var username = (!message.from.username) ? message.from.id : message.from.username 
var messageToLog = logger.prepareMessage(message) 

新的日誌與控制檯和配置請求:

{ files: 
    { easylogger: 
     { name: '/root/node_modules/private-telegram-bot/config/logger.json', 
     watch: true }, 
    literals: 
     { name: '/root/node_modules/private-telegram-bot/config/literals.json', 
     watch: true }, 
    users: 
     { name: '/root/node_modules/private-telegram-bot/config/users.json', 
     watch: true }, 
    bot: 
     { name: '/root/node_modules/private-telegram-bot/config/bot.json', 
     watch: true }, 
    help: 
     { name: '/root/node_modules/private-telegram-bot/config/help.json', 
     watch: true }, 
    commands: 
     { name: '/root/node_modules/private-telegram-bot/config/commands.json', 
     watch: true } }, 
    easylogger: { enabled: true, transports: [ [Object], [Object], [Object] ] }, 
    literals: 
    { en: 
     { notAuthorizedUserError: 'Sorry, this is a private bot.\nYou need an authorization to use it', 
     notCommandError: '', 
     unknownCommandError: 'I don\'t know this command.\nWhat do you want from me?', 
     operationCancelledError: 'Operation has been cancelled', 
     nothingToCancelError: 'Sorry, nothing to cancel', 
     commandTimeoutError: 'command has been cancelled by timeout', 
     commandOnlyForOwnerError: 'Sorry, this command is only for bot owner', 
     noHelpError: 'Sorry, I can\'t help you.\nI haven\'t any info about this command', 
     wellcomeMessage: 'Hi @%username%.\nWellcome to %botname%.', 
     emptyUsernameError: 'Your friend does not have a name?', 
     userAuthorizedError: 'Needless to add to your friend.\nHe was among the elect!', 
     addUserSuccessMessage: 'Done! Currently, your friend can run all your public commands', 
     addUserWellcomeMessage: 'Do you want to allow to a friend use your bot?\nI need his Telegram username for this', 
     removeUserSuccessMessage: 'Done! User has been removed', 
     removeUserWellcomeMessage: 'Do you want remove a user?', 
     userNotFoundError: 'This user doesn\'t exist', 
     wrongTokenError: 'Something is worng with this bot token. Check it in bot.json file', 
     tokenNotFoundError: 'Token not found. Add your bot token in \'token\' property in bot.json file', 
     ownerNotFoundError: 'Bot owner not found. Add your Telegram alias (without \'@\') in \'owner\' property in bot.json file', 
     unknownLanguageError: 'Which language do you speak? I don\'t understand you\nI speak english(en) and spanish(es)\nCheck your default language in your bot config file (bot.json)' }, 
    es: 
     { notAuthorizedUserError: 'Lo siento, este es un bot privado.\nNecesitas autorizacion para usarlo', 
     notCommandError: 'Solo se permite usar comandos.\nTodos los comandos empiezan por /', 
     unknownCommandError: 'No conozco ese comando.\nQue quieres de mi?', 
     operationCancelledError: 'La operacion ha sido cancelada', 
     nothingToCancelError: 'Lo siento, no hay nada que cancelar', 
     commandTimeoutError: 'comando ha sido cancelado por timeout', 
     commandOnlyForOwnerError: 'Lo siento, ese comando es solo para el dueño del bot', 
     noHelpError: 'Lo, siento, no puedo ayudarte.\nNo tengo ninguna informacion sobre ese comando', 
     wellcomeMessage: 'Hola @%username%.\nBienvenido a %botname%.', 
     emptyUsernameError: 'Tu amigo no tiene nombre?', 
     userAuthorizedError: 'No hace falta añadir a tu amigo.\nYa estaba entre los elegidos!', 
     addUserSuccessMessage: 'Hecho! Tu amigo ya puede ejecutar todos los comandos publicos', 
     addUserWellcomeMessage: 'Quieres que un amigo pueda usar tu bot?\nPara eso necesito su usuario de Telegram', 
     removeUserSuccessMessage: 'Hecho! Usuario eliminado', 
     removeUserWellcomeMessage: 'Quieres eliminar un usuario?', 
     userNotFoundError: 'Ese usuario no existe', 
     wrongTokenError: 'Algo va mal con ese token. Compruebalo en el fichero bot.json', 
     tokenNotFoundError: 'Token no encontrado. Añade tu token en la propiedad \'token\' de bot.json', 
     ownerNotFoundError: 'Propietario del bot no encontrado. Añade tu alias de Telegram (sin \'@\') en la propiedad \'owner\' de bot.json', 
     unknownLanguageError: 'Que lengua hablas? No te entiendo\nSolo hablo ingles(en) y español(es)\nComprueba tu lenguaje por defecto en el fichero de configuracion del bot (bot.json)' } }, 
    users: [ '9587763' ], 
    bot: 
    { token: 'XXXXXXXXXXXXXXXXX', 
    owner: 'XXX9587763XXX', 
    updates: { enabled: true }, 
    responseNoAuthorizedMessages: true, 
    defaultLanguage: 'en' }, 
    help: { commands: [ [Object], [Object], [Object], [Object], [Object] ] }, 
    commands: 
    { publicScriptsPath: '../publicScripts/', 
    adminScriptsPath: '../adminScripts/', 
    commandTimeout: 60000, 
    adminCommands: [ 'adduser', 'removeuser' ], 
    publicCommands: [ 'ventas' ] } } 
[ '9587763' ] 
username: 9587763 
username length: 7 
number 
cm.config.bot.owner: XXX9587763XXX 
false 
isFromOwner: false 
cm.config.users: 9587763 
cm.config.users length: 7 
object 
isFromUser: false 
into the condition !isFromOwner && !isFromUser 
[info] - [msg_1620] @9587763 : /ventas 
+6

「遏制」 是不是內置的功能。請將該函數的主體添加到您的問題中。 –

+0

對不起,我提到你,我不是技術人員。你能否提供關於如何獲取你想要的信息的愚蠢信息(比如我)? – bazilio

+0

'1' - 您是否使用任何IDE進行代碼編輯(例如webstorm等)? '1.1:YES - >'然後打開代碼文件你抓住了「這是功能」部分。將鼠標光標移動到「contains」字上,然後按「ctrl或cmd」並單擊該字。 '1.1.1 - >'你看到'function contains'這樣的東西嗎? '1.1.1.1:YES - >'複製該塊並粘貼到這裏。 '1.1.1.2:NO - >'然後右鍵點擊並找到名爲「轉到定義」的菜單按鈕。你找到了嗎? '1.1.1.2.1:YES - >'then'goto 1.1.1.1'。 '1.1.1.2.2:沒有 - >'抱歉不能做任何事。 '1.2:NO - >'然後下載一個編輯器和'goto 1.1' –

回答

1

更新:由於在評論中討論的那樣,你必須使用for循環如下自cm.config.users是一個數組。

var isFromUser = false; 
for(var i = 0; i < cm.config.users.length; i++) { 
    isFromUser = contains(cm.config.users[i], username, 'exists'); 
    if(isFromUser) break; 
} 

函數按預期工作,沒有問題。當我運行的函數的值與cm.config.users: 230592242中提到的230592242相同時,其預期返回true。當使用除此以外的值運行時,它將返回false

我已在下面給出了一個示例片段來確認您可以通過點擊底部的Run code snippet來運行。

你要檢查什麼是contains(cm.config.users, username, 'exists')

使用,因爲使用的配置值的username值由這似乎是一個「用戶名」,而不是「用戶名」您試圖線cm.config.users: 230592242230592242去檢查。

這就是爲什麼你得到false

// Compare item with filter or another item 
 
var checkItem = function(item, itemOrFilter) { 
 

 
    // Defining array of filters 
 
    var filters = [] 
 
    if (!Array.isArray(itemOrFilter)) { 
 
    if (itemOrFilter.key != undefined) 
 
     filters.push(itemOrFilter) 
 
    } else { 
 
    filters = itemOrFilter 
 
    } 
 

 
    // Filtering 
 
    if (filters.length > 0) { 
 
    var i = 0 
 
    var match = true 
 
    while (match && i < filters.length) { 
 
     match = (item[filters[i].key] === filters[i].value) 
 
     i++ 
 
    } 
 
    return match 
 
    } 
 

 
    // Matching 
 
    else { 
 
    return (JSON.stringify(item) === JSON.stringify(itemOrFilter)) 
 
    } 
 
} 
 

 
// Search item in array. 
 
var searchInArray = function(array, itemOrFilter, mode) { 
 
    var found = { "index": -1, "filtered": []} 
 
    var i = 0 
 
    var end = false 
 
    while (i < array.length && !end) { 
 
    end = (mode != 'filter' && mode != 'repetitions' && found.index != -1) 
 
    if (checkItem(array[i], itemOrFilter)) { 
 
     found.index = i 
 
     found.filtered.push(array[i]) 
 
    } 
 
    i++ 
 
    } 
 
    return found 
 
} 
 

 
// Search substring or char in string. 
 
var searchInString = function(string, item, mode) { 
 
    var filtered = string.match(new RegExp(item, 'g')) 
 
    var index = (filtered) ? string.indexOf(filtered[0]) : -1 
 
    var found = { "index": index 
 
       , "filtered": filtered || [] 
 
       } 
 
    return found 
 
} 
 

 
// Search digit or subnumber in number. 
 
var searchInNumber = function(number, item, mode) { 
 
    var strnumber = number.toString() 
 
    return searchInString(strnumber, item) 
 
} 
 

 

 
// Main function 
 
function contains (container, item, mode) { 
 

 
    mode = (mode || 'index') 
 
    var found = { "index": -1, "filtered": []} 
 

 
    // Searching in number 
 
    if (typeof container == "number") 
 
    found = searchInNumber(container, item, mode) 
 

 
    // Searching in string 
 
    else if (typeof container == "string" || container instanceof String) 
 
    found = searchInString(container, item, mode) 
 

 
    // Searching in array 
 
    else if (Array.isArray(container)) 
 
    found = searchInArray(container, item, mode) 
 
    else console.log("Container type not allowed") 
 

 
    // TODO: Search into object's properties 
 
    //else if (container instanceof Object) found = searchInObject(container, item) 
 

 
    if (mode == 'exists') return found.filtered.length > 0 
 
    if (mode == 'index') return found.index 
 
    if (mode == 'filter') return found.filtered 
 
    if (mode == 'repetitions') return found.filtered.length 
 
    console.log("Mode not allowed") 
 
    return null 
 
} 
 

 
var cm = { 
 
    config: { 
 
    users: [ 
 
     230592242 
 
     ] 
 
    } 
 
}; 
 

 
var userId = 230592242; 
 
console.log('Checking the value user id "' + userId + '"..'); 
 
var isFromUser = false; 
 
for(var i = 0; i < cm.config.users.length; i++) { 
 
    isFromUser = contains(cm.config.users[i], userId, 'exists'); 
 
    if(isFromUser) break; 
 
} 
 
console.log(isFromUser); 
 

 
var username = 'test' 
 
console.log('Checking the value user name "' + username + '"..'); 
 
isFromUser = false; 
 
for(var i = 0; i < cm.config.users.length; i++) { 
 
    isFromUser = contains(cm.config.users[i], username, 'exists'); 
 
    if(isFromUser) break; 
 
} 
 
console.log(isFromUser);

+0

評論不適用於擴展討論;這個對話已經[在聊天中存檔](http://chat.stackoverflow.com/rooms/129690/discussion-on-answer-by-aruna-contains-is-returning-false)。請不要在評論中進行長時間的對話。 –