首页 > 解决方案 > 如何修复nodejs中的“无法读取未定义的属性“包含”?[脚本]

问题描述

我正在设置一个新服务器,并且想运行一个 nodejs 脚本来不和谐。但问题是;它在脚本启动/或运行后发布错误。

我曾尝试在 GitHub 上联系“作者”而没有回答以修复它,并且我确实尝试在我在线的其他服务器上进行测试,但它说同样的错误。(包括 nodejs/npm 版本的降级。)

我找到的代码来自这个 GitHub 页面:https ://github.com/Triniayo/nodejs-discord-csgoupdate

// Requirements
const { Client } = require('discord.js');
const fs = require('fs');
const Parser = require('rss-parser');
const htmlToText = require('html-to-text');
const log = require('npmlog');

// Load Config
const cfg = require('./config.json');

// Create feeder instance
let rssParser = new Parser({
    // Renaming 'content:encoded' to 'contentHtml' because it won't be useable otherwise
    customFields: {
        item: [
            ['content:encoded', 'contentHtml']
        ]
    },
    // Setting User Agent
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
    }
});

// Setting variables for the RSS output
let updateTitle;
let updateURL;
let updateContent;
let updateDate;

// Setting last update variable
let lastUpdate;

function getLastUpdate() {
    // Getting date of last update from check-update.txt file
    let dateFromFile = fs.readFileSync('check-update.txt');
    lastUpdate = dateFromFile.toString();
}

// Getting last date from check-update.txt file every 5 seconds
setInterval(getLastUpdate, 5000);

// Create Discord Bot Instance
const bot = new Client();

// Logging into Bot Account
bot.on('ready', () => {
    log.info('discord', `Logged in as ${bot.user.tag} (User ID: ${bot.user.id}) on ${bot.guilds.size} server(s)`);
    bot.user.setActivity('Fetching Updates');

    // Checking every 10 seconds if there's a new update, and if it's been posted already
    setInterval(getUpdate, 10000);
});

function getUpdate() {
    // Get current date and edit format
    let getDate = new Date();
    let date = [
        getDate.getFullYear(),
        ('0' + (getDate.getMonth() + 1)).slice(-2),
        ('0' + getDate.getDate()).slice(-2)
    ].join('-');

    // Fetching updates from CS:GO Blog
    (async () => {
        // Setting RSS Feed URL
        let feed = await rssParser.parseURL('http://blog.counter-strike.net/index.php/category/updates/feed/');

        // Setting items into variables
        feed.items.forEach(item => {
            if (item.isoDate.includes(`${date}`)) {
                updateTitle = item.title;
                updateURL = item.link;
                updateContent = item.contentHtml;
                updateDate = item.isoDate;
            }
        });

        // Converting from HTML to readable text
        let format = htmlToText.fromString(updateContent, {
            wordwrap: 130
        });

        // Limiting the update to 10 lines
        let updateNotes = format.split('\n', 10);

        if (updateDate.includes(`${date}`)) {
            if (lastUpdate !== date) {
                bot.channels.get(cfg.channelid).send("@everyone A new CS:GO Update has been released!", {
                    embed: {
                      "title": `${updateTitle}`,
                      "description": `${updateNotes.join('\n')}...\n\n[Continue reading on the CS:GO Blog](${updateURL})`,
                      "url": `${updateURL}`,
                      "color": 5478908,
                      "thumbnail": {
                        "url": "https://raw.githubusercontent.com/Triniayo/nodejs-discord-csgoupdate/master/csgo-icon.png"
                      }
                    }
                });

                // Storing date of the latest update in the check-update.txt
                fs.writeFileSync('check-update.txt', `${date}`)
            }
        } else {
            // Do nothing if update has been posted already.
        }
    })();
}

// Logging into the Bot Account
bot.login(cfg.token);

在此下方,是错误,我在将 nodejs 和 npm 更新到最新版本后得到了。

(node:23692) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of undefined
    at /home/mikkel/bots/csgo/app.js:87:24
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
(node:23692) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 13)

我不知道,这个错误意味着什么,因为我对 nodejs 很陌生。

npm/node 的版本:

node: v8.16.1
npm: 6.12.0

我必须改变的是什么。我对javascript或nodejs一无所知。该脚本自由地放在 GitHub 上。

更新:编辑于 2019 年 10 月 10 日 - 15:28:日期格式是什么?- 例子; 在 github 上,它使用以下格式从 check-update.txt 读取:10/23/2018(例如)

似乎它没有在 Discord 上为我发帖。(如果不这样做,它应该这样做)

例子:

    // Checking every 10 seconds if there's a new update, and if it's been posted already
    setInterval(getUpdate, 10000);

这是问题所在:

            // Do nothing if update has been posted already.
        }
    })();
}

也许我应该从不和谐的开发者那里创建一个新的机器人?

标签: javascriptnode.jslinux

解决方案


更改。请求 urlhttphttps,isoDatepubDate. isoDate 不在提要内容中。

// Setting RSS Feed URL
let feed = await rssParser.parseURL('https://blog.counter-strike.net/index.php/category/updates/feed/');

// Setting items into variables
feed.items.forEach(item => {
  if (item.pubDate.includes(`${date}`)) {
    updateTitle = item.title;
    updateURL = item.link;
    updateContent = item.contentHtml;
    updateDate = item.pubDate || '';
  }
});

推荐阅读