如何用discord.js制作定时发送谷歌水豚图片的Discord机器人?
实现每小时发送随机水豚图片的Discord机器人
步骤1:准备依赖(可选)
如果你的Node.js版本低于18,需要安装node-fetch来发起网络请求:
npm install node-fetch@2
Node.js 18及以上版本自带fetch,无需额外安装。
步骤2:修改你的代码
替换原有代码为以下内容,关键改动已标注:
// 若Node.js版本<18,取消下一行注释引入fetch // const fetch = require('node-fetch'); client.on('ready', () => { // 按ID直接获取频道,比find更高效 const testChannel = client.channels.cache.get('1034340669197668432'); // 设置1小时(3600000毫秒)的定时任务 setInterval(async () => { try { // 调用免费随机水豚图片接口,无需API密钥 const capybaraImageUrl = 'https://source.unsplash.com/random/?capybara'; // 发送图片到指定频道 await testChannel.send({ files: [capybaraImageUrl] }); } catch (error) { // 捕获错误避免机器人崩溃 console.error('发送图片失败:', error); // 出错时发送备用提示 await testChannel.send('抱歉,没找到水豚图片😥'); } }, 3600000); console.log('机器人已上线,开始定时发送水豚图片!'); });
关键说明
- 频道查找优化:用
client.channels.cache.get(频道ID)替代find,直接通过ID定位频道,性能更优。 - 异步处理:定时任务内用
async/await处理消息发送的异步操作,保证流程顺序执行。 - 错误防护:添加
try/catch捕获网络请求或消息发送时的异常,防止机器人意外崩溃。 - 权限要求:确保机器人在目标频道拥有
Attach Files权限,否则无法发送图片。
内容的提问来源于stack exchange,提问作者Miguel Gomez
相关产品推荐
相关产品推荐

