我想在我的 Discord 机器人(使用 discord.js)中使用来自 reddit (reddit.com/r/SUBREDDIT/random/.json) 的随机 api.获取图像工作正常,直到帖子不包含有效链接,但我希望它在一个单独的文件中的函数中与其他与 api 相关的东西.我的 api.js 中的函数是:
I want to use the random api from reddit (reddit.com/r/SUBREDDIT/random/.json) in my Discord bot (using discord.js). Getting images works fine until the post doens't include a valid link, but I want it in a function in a seperate file with other api-related stuff. The function in my api.js is:
module.exports.randomReddit = async function randomReddit(reddit) {
return new Promise((res, rej) => {
axios.get(`https://www.reddit.com/r/${reddit}/random/.json`)
.then(function (response) {
res(response[0].data.children[0].data);
})
.catch(function (error) {
rej(error);
})
})
}
在我的代码中,我目前有:
In my code, I currently have:
for (let i = 0; i < 10; i++) {
randomReddit('car').then(data => {
let regex = /.(jpg|gif|png)$/;
let test = regex.test(data.url);
if (test) message.channel.send(data.url)
continue;
})
}
随机 reddit 帖子并不总是包含有效链接.我想在帖子没有有效链接之前再次运行该功能(randomReddit).在这种情况下,可以发送图像.我尝试了一些不同的方法,但它们根本不起作用..
The random reddit post doesn't always include a valid link. I would like to run the function (randomReddit) again when a post doesn't have one until a post does have a valid link. In that case, the image may be sent. I tried a few different things but they didn't work at all..
提前谢谢你.
使用像 承诺重试
async function randomReddit(reddit) {
return new Promise((res, rej) => {
axios.get(`https://www.reddit.com/r/${reddit}/random/.json`)
.then(function (response) {
res(response[0].data.children[0].data);
})
.catch(function (error) {
rej(error);
})
})
}
promiseRetry(function (retry) {
return randomReddit('test')
.then(data => {
let regex = /.(jpg|gif|png)$/;
let test = regex.test(data.url);
if (test) return data;
return retry();
})
}).then(function (value) {
// Do smthg
});
这篇关于if 语句失败时重新运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
discord.js v12:我如何等待 DM 频道中的消息?discord.js v12: How do I await for messages in a DM channel?(discord.js v12:我如何等待 DM 频道中的消息?)
如何让我的机器人提及发出该机器人命令的人how to make my bot mention the person who gave that bot command(如何让我的机器人提及发出该机器人命令的人)
如何修复必须使用导入来加载 ES 模块 discord.jsHow to fix Must use import to load ES Module discord.js(如何修复必须使用导入来加载 ES 模块 discord.js)
如何列出来自特定服务器的所有成员?How to list all members from a specific server?(如何列出来自特定服务器的所有成员?)
Discord bot:修复“找不到 FFMPEG"Discord bot: Fix ‘FFMPEG not found’(Discord bot:修复“找不到 FFMPEG)
使用 discord.js 加入 discord 服务器时的欢迎消息Welcome message when joining discord Server using discord.js(使用 discord.js 加入 discord 服务器时的欢迎消息)