繁体   English   中英

我正在尝试用 JavaScript 编写一个 Discord 机器人,但遇到了问题

[英]I am trying to write a Discord bot in JavaScript and have encountered a problem

我正在尝试用 JavaScript 编写一个 Discord 机器人,但遇到了一个问题,当 CMD 窗口到达以下代码时,CMD 窗口崩溃到桌面:“if(styles.includes(cmd2))”语句,有谁知道这个问题可能是什么是?

用户应该输入“!recommend”,然后是“movie”、“game”或“show”。 这目前运行良好。

我现在正在尝试添加一个案例,用户可以输入“!推荐”,然后是“科幻”等流派或风格。 机器人应该在“电影”二维数组中搜索在其流派列表中包含“科幻”的任何电影。 这是行不通的。

我怀疑这个问题是由“if(movies[i].includes(cmd2))”语句引起的,但是,这更像是一种感觉,而不是基于任何真正的逻辑推理。 “genreMovies[i][y].push(movies[i][y]);” 线也可能是问题的根源。 任何帮助将非常感激! 感谢您抽时间阅读!

代码如下所示:

var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');

// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
    colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
   token: auth.token,
   autorun: true
});
bot.on('ready', function (evt) {
    logger.info('Connected');
    logger.info('Logged in as: ');
    logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
    // Our bot needs to know if it will execute a command
    // It will listen for messages that will start with `!`
    if (message.substring(0, 1) == '!') {
        var args = message.substring(1).split(' ');
        var cmd = args[0];
        var cmd2 = args[1];
        var styles = [
        'cyberpunk',
        'dystopia',
        'noir',
        'thriller',
        'sci-fi',
        'post-apocalyptic',
        'action',
        'adventure',
        'romantic',
        'drama',
        'crime',
        'horror',
        'slasher',
        'dark-comedy',
        'mystery',
        'superhero',
        'animated',
        'comedy',
        'historical',
        'fantasy'
        ];
        var gameTypes = [
        'point-and-click',
        'RPG',
        'shooter',
        'stealth',
        'open-world',
        'hack-and-slash'
        ]
        var movies = [
        ['Blade Runner (1982)', 15, '1h 57m', 'cyberpunk, dystopia, noir' , 'film with a brilliant aesthetic and a great cyberpunk noir tale to tell.'],
        ['Blade Runner 2049 (2017)', 15, '2h 44m', 'Cyberpunk, Dystopia, Thriller' , 'visually stunning movie set in a cyberpunk world that explores issues surrounding humanity.'],
        ['Ex Machina (2014)', 15, '1h 48m', 'Sci-Fi, Thriller, Drama, Romance' , 'movie about AI and the issues relating to it with some philisophical questions.']
        ];
        var games = [
        ['Blade Runner (1997)', 16, '8h 30m', 'point-and-click adventure game that captures the films aesthetic brilliantly and has an intruiging plot.'],
        ['Borderlands 2 (2012)', 18, '22h 30m', 'very entertaining comedic first person shooter with a cartoony art style.'],
        ['Deus Ex (2000)', 16, '23h', 'first-person immersive-sim and RPG that delves deep into government conspiracies and capitalistic private agencies.']
        ];
        var tvShows = [
        ['Altered Carbon (2018-2020)', 18, 2, 18, '56m', "thrilling cyberpunk crime drama set in a world where people's personalities are saved in a 'stack' that can be recovered after death."],
        ['Ripper Street (2012-2016)', 15, 5, 37, '1h 7m', 'character focused period drama set in the victorian era following Edmund Reid and his colleagues Sergeant Drake and Homer Jackson.'],
        ['Banshee (2013-2016)', 18, 4, 38, '1h', 'dramatic crime thriller about a criminal who poses as a sheriff in a small southern town with complex characters and emotional payoffs.']
        ];
       
        args = args.splice(1);
        switch(cmd) {
            // !recommend
            case 'recommend':
                switch(cmd2) {
                    // !recommend movie
                    case 'movie':
                        var randInt = getRndInteger(0,3);
                        bot.sendMessage({
                            to: channelID,
                            message: 'You should try ' + movies[randInt][0] + '. The movie is rated BBFC ' + movies[randInt][1] + ' and is ' + movies[randInt][2] + ' long. Genres: ' + movies[randInt][3] + '. It is a ' + movies[randInt][4]
                        });
                    break;
                    // !recommend game
                    case 'game':
                        var randInt = getRndInteger(0,3);
                        bot.sendMessage({
                            to: channelID,
                            message: 'You should try ' + games[randInt][0] + '. The game is rated PEGI ' + games[randInt][1] + ' and is ' + games[randInt][2] + ' long. It is a ' + games[randInt][3]
                        });
                    break;
                    // !recommend TV show
                    case 'show':
                        var randInt = getRndInteger(0,3);
                        bot.sendMessage({
                            to: channelID,
                            message: 'You should try ' + tvShows[randInt][0] + '. The show is rated BBFC ' + tvShows[randInt][1] + ' and has ' + tvShows[randInt][2] + ' seasons with ' + tvShows[randInt][3] + ' episodes. Each episode is around ' + tvShows[randInt][4] + ' long. It is a ' + tvShows[randInt][5]
                        });
                    break;
                }
                if (styles.includes(cmd2)){
                    var i;
                    for (i = 0; i <= movies.length; i++){
                        if (movies[i].includes(cmd2)) {
                            var max = 0;
                            max++;
                            var genreMovies = [];
                            var y;
                            for (y = 0; y <= 4; y++) {
                                genreMovies[i][y].push(movies[i][y]);
                            }
                        }
                    }
                    var randInt = getRndInteger(0,max);
                    bot.sendMessage({
                        to: channelID,
                        message: 'You should try ' + genreMovies[randInt][0] + '. The movie is rated BBFC ' + genreMovies[randInt][1] + ' and is ' + genreMovies[randInt][2] + ' long. Genres: ' + genreMovies[randInt][3] + '. It is a ' + genreMovies[randInt][4]
                    });
                }
            break;
            case 'help':
                bot.sendMessage({
                    to: channelID,
                    message: "__**List of Commands:**__ \n Use *!recommend [mediaType]* e.g. '!recommend movie' and you will get a movie recommendation! \n Use *!recommend [genre] [mediaType]* e.g. '!recommend noir movie' and you will get a movie recommendation from that genre! \n There are also a number of *hidden commands*! \n And as you well know, you can use *!help* to view the command list! \n \n __**List of Media Types:**__ \n movie e.g. '!recommend movie' \n game e.g. '!recommend game' \n show e.g. '!recommend show'"
                });
            break;
        }
     }
});

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min) ) + min;
}

movies[i].includes(cmd2)行为与您期望的不同。 让我们分解一下:

movies[i]有关于一部电影的数据,例如: ['Blade Runner (1982)', 15, '1h 57m', 'cyberpunk, dystopia, noir' , 'film with a brilliant aesthetic and a great cyberpunk noir tale to tell.']

与流派相关的数据第四个数组项 - 'cyberpunk, dystopia, noir'

数组方法array.includes(value)返回 true 如果数组中有一个类似于提供的值,所以如果用户输入!recommend cyberpunk值将是cyberpunk 'cyberpunk' !== 'cyberpunk, dystopia, noir'

我建议将电影数据构建为一个对象,例如:

{
  name: 'Blade Runner',
  year: 1982,
  genres: ['cyberpunk', 'dystopia', 'noir']
  ...
}

然后你可以做movies[i].genres.includes(cmd2)

然后代码将在genreMovies[i][y].push(movies[i][y])出错,因为您已将 GenreMovies 定义为一个空数组,并且您正在尝试访问某些genreMoves[i][y]未定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM