首页 > 解决方案 > Javascript irc bot node.js从文本文件错误中连接字符串

问题描述

我正在使用 node.js 和 IRC 库 ( https://github.com/martynsmith/node-irc ) 创建一个 irc 机器人。当我尝试连接文本文件中的字符串时,irc 机器人会关闭并引发错误。我怀疑有一些看不见的换行符会把事情搞砸,但我不知道如何测试它或在这种情况下摆脱它。

代码说明: 当用户在irc频道中输入消息时,调用myFunction。myFunction 读取名为 test.txt 的文本文件,并将行作为元素保存在名为 myArray 的数组中。然后,我尝试使用 bot.say 命令让机器人打印出该数组的一个元素。config.channels[0] 是输入消息的通道,也是机器人应该响应的通道。

机器人可以毫无问题地在不同的行上打印出 myArray[0] 和 myArray[1],但之后它不能连接任何东西。

错误信息: C:\Program Files\nodejs\node_modules\irc\lib\irc.js:849 throw err; ^ 错误 [ERR_UNHANDLED_ERROR]:未处理的错误。([object Object]) 在 Client.emit (events.js:171:17) 在客户端。(C:\Program Files\nodejs\node_modules\irc\lib\irc.js:643:26) 在 Client.emit (events.js:182:13) 在迭代器 (C:\Program Files\nodejs\node_modules\irc \lib\irc.js:846:26) at Array.forEach () at Socket.handleData (C:\Program Files\nodejs\node_modules\irc\lib\irc.js:841:15) at Socket.emit (events .js:182:13) 在 addChunk (_stream_readable.js:283:12) 在 Socket.Readable.push (_stream_readable.js:219:10) 的 readableAddChunk (_stream_readable.js:260:13)

test.txt在不同的行中包含字母 abcd。

var config = {
    channels: ["#channelname"],
    server: "se.quakenet.org",
    botName: "testbot"
};

// Get the lib
var irc = require("irc");

// Create the bot name
var bot = new irc.Client(config.server, config.botName, {
    channels: config.channels
});


// Listen for any message
bot.addListener("message", function(from, to, text, message) {

    myFunction(); //call myFunction when someone types something in the channel

});

function myFunction() {

var myArray = readTextFile('test.txt'); 

bot.say(config.channels[0],myArray[0]); //Print out the first element in myArray (works, this prints out 'a')
bot.say(config.channels[0],myArray[1]); //Print out the second element in myArray(works, this prints out 'b')
bot.say(config.channels[0],'test' + myArray[0]); //Works, prints out 'testa'
bot.say(config.channels[0],myArray[0] + 'test'); //concatenate a string afterwards (prints out 'a' and then throws an error and makes the bot disconnect from server)
bot.say(config.channels[0],myArray[0] + myArray[1]); //prints out 'a' and then throws an error and makes the bot disconnect from server


}

//function to read a text file:   
function readTextFile(file) {
    var fs = require("fs");
    var textFile = fs.readFileSync("./" + file, {"encoding": "utf-8"});
    textFileArray = textFile.split('\n');
return textFileArray;

}

标签: javascriptnode.jsbotsirc

解决方案


问题是文本文件中出现了一些不好的不可见字符(尽管仍然不知道是什么字符)。在另一篇文章中找到了答案,我使用 mystring.replace(/\W/g, '') 从 myArray 中的所有元素中删除了所有非字母数字字符。

从字符串中删除非字母数字字符。[\] 字符有问题


推荐阅读