【问题标题】:Looking for assistance with adding a randomizer to my search results寻求在我的搜索结果中添加随机数的帮助
【发布时间】:2020-09-26 01:12:58
【问题描述】:

此代码的目的是在 Discord 服务器上运行机器人。现在它可以搜索图像,但我想随机化结果。

我有以下变量 - var rnd = Math.floor(Math.random() * search.results.length); 但我不确定它的格式是否正确,或者它的确切放置位置。

这是我的代码:

var cheerio = require("cheerio"); /* Used to extract html content, based on jQuery || install with npm install cheerio */
var request = require("request"); /* Used to make requests to URLs and fetch response  || install with npm install request */

var discord = require("discord.js");
var client = new discord.Client();


// Login into discord using bot token (do not share token with anyone!).
client.login("");

client.on("ready", function() {
    console.log("logged in");
});

client.on("message", function(message) {

    var parts = message.content.split(" "); 

    /* Simple command manager */
    if (parts[0] === "search.") { 

        // call the image function
        image(message, parts); // Pass requester message to image function

    }

});

function image(message, parts) {

    /* extract search query from message */

    var search = parts.slice(1).join(" "); 

    var options = {
        url: "http://results.dogpile.com/serp?qc=images&q=" + search,
        method: "GET",
        headers: {
            "Accept": "text/html",
            "User-Agent": "Chrome"
        }
    };
    request(options, function(error, response, responseBody) {
        if (error) {
            // handle error
            return;
        }

        $ = cheerio.load(responseBody); 
        
        var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href"));
        console.log(urls);
        if (!urls.length) {
            // Handle no results
            return;
        }

        // Send result
        message.channel.send( urls[0] );
    });

client.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('pong');
} else if (msg.content === '') {
  msg.reply('');
} else if (msg.content === '') {
  msg.reply('');
} else if (msg.content === '') {
  msg.reply('');
} else if (msg.content === '') {
  msg.reply('');
}
});

}

谢谢

【问题讨论】:

    标签: javascript discord bots google-image-search


    【解决方案1】:

    我想您正试图从您获取并存储在 var urls 中的结果中获取随机图像。 (如果有什么不同,请扩展您的问题)

    由于您已经生成了变量rnd,该变量的结果长度有一个最大值。

    您可以通过更改以下行来返回随机结果。

    message.channel.send(urls[rnd]);

    【讨论】:

      【解决方案2】:

      我能够让它与以下内容一起工作:

          message.channel.send( urls[Math.floor((Math.random() * 50) + 1)] );
      

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 2011-09-21
        • 1970-01-01
        • 2015-10-10
        • 2010-12-08
        • 1970-01-01
        • 2014-02-24
        • 2017-11-23
        • 2011-08-20
        相关资源
        最近更新 更多