Discord.js技术问询:如何为Reddit随机帖子代码添加描述获取功能
解决方案
要给你的代码添加读取帖子描述的功能其实很简单,我们只需要从Reddit返回的帖子数据里提取selftext字段(这就是帖子的正文/描述内容),再把它整合到Discord的嵌入消息中就行。同时还要考虑到部分帖子可能没有描述内容,得做个空值处理避免显示异常。
下面是修改后的完整代码:
if (msg.content == '-meme') { function loadMemes() { // Fetch JSON return ( fetch('https://www.reddit.com/r/memes.json?limit=800&sort=hot&t=all') .then((res) => res.json()) // Return the actual posts .then((json) => json.data.children) ); } function postRandomMeme(message) { return loadMemes().then((posts) => { // 获取随机帖子的标题、图片链接和描述内容 const { title, url, selftext } = posts[Math.floor(Math.random() * posts.length)].data; // 创建嵌入消息,添加描述字段并处理空描述的情况 const embed = new Discord.RichEmbed({ title, description: selftext.trim() || "该帖子没有描述内容", image: { url }, footer: { text: 'Subreddit : r/memes' }, }); // 发送嵌入消息 return message.channel.send(embed); }); } // 执行函数并捕获错误 postRandomMeme(msg).catch(console.error); }
关键修改点说明:
- 提取描述字段:在解构帖子数据时新增了
selftext字段,这是Reddit帖子自带的正文/描述内容。 - 空值处理:用
selftext.trim() || "该帖子没有描述内容"来兼容无描述的帖子——先去除字符串首尾空白,若为空则显示默认提示文本。 - 错误捕获:把原来注释掉的错误捕获逻辑打开,方便调试时排查问题。
适配新闻类Subreddit的小技巧:
如果要切换到新闻类subreddit(比如r/worldnews),只需要把fetch里的URL换成对应地址就行,比如https://www.reddit.com/r/worldnews.json?limit=800&sort=hot&t=all,其他逻辑完全不用改,因为Reddit的API返回结构是统一的。
另外提一句:如果你的Discord.js版本是v12及以上,RichEmbed已经被废弃,建议换成Discord.MessageEmbed,用法和RichEmbed几乎一致,只需要把new Discord.RichEmbed改成new Discord.MessageEmbed就可以了。
内容的提问来源于stack exchange,提问作者Vas Dávid Valentin




