【发布时间】: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