如何解决Giphy API 总是提供相同的 gifs (discord.js)
这可能是不恰当的,但我正在制作一个不和谐的机器人,在这个过程中我想制作一个“gif”命令。我选择了 Giphy api,因为它似乎是最简单的一个。但是每次我让机器人获取热门 gif 时,它都会给我相同的 gif。 (附示例) Here you can see he bot sending the same gif 2 times
这是这个命令所需的代码:
if (message.content.startsWith(`${prefix}gif`)) {
giphy.trending('gifs',{limit:100})
.then((response) => {
var totalResponses = response.data.length;
var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
var responseFinal = response.data[responseIndex];
message.channel.send("Here is a gif for you!\n",{
files: [responseFinal.images.fixed_height.url]
}).catch(() => {
message.channel.send('There was an API error,please try later.')
})
})
}
感谢任何答案。
解决方法
我从未使用过 giphy API,但您只是想从数组中获取随机索引,而这只是通过以下方式完成的:
var totalResponses = response.data.length;
var responseIndex = Math.floor(Math.random() * totalResponses);
var responseFinal = response.data[responseIndex];
message.channel.send("Here is a gif for you!\n",{
files: [responseFinal.images.fixed_height.url]
}).catch(() => {
message.channel.send('There was an API error,please try later.')
})
totalResponses
是数组的长度,我们需要从中获取一个随机数。这是在 responseIndex
中完成的。所以现在在 responseIndex
中存储了一个从 0 到 totalResponses
的随机数(这正是我们想要的,因为数组总是从 0 开始,所以 0 可能是一个可能的索引)。然后在 responseFinal
中,我们将数组的值存储在 responseIndex
的随机索引处。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。