使用instagram-private-api发布内容遭遇400 Bad Request错误求助
我使用instagram-private-api在Node.js项目中通过Discord发布Ins帖子已有半年,近期未修改代码却突然触发400 Bad Request错误,错误信息为:
IgResponseError: POST /rupload_igphoto/1680015944333_0_8212191953 - 400 Bad Request;
已确认登录凭证和图片路径正确,测试代码如下:
const { IgApiClient } = require('instagram-private-api'); const { readFile } = require('fs').promises; const ig = new IgApiClient(); const { IG_Username, IG_Password } = require('./Settings/config.json'); ig.state.generateDevice(IG_Username); (async () => { try { await ig.simulate.preLoginFlow(); await ig.account.login(IG_Username, IG_Password); const photo = await readFile(__dirname + '/Media/Post_Image_Publish.jpg'); const post = await ig.publish.photo({ file: photo, caption: `TESTING POSTING FROM NODE.JS` }); console.log('Photo uploaded successfully'); console.log(`Post URL: https://www.instagram.com/p/${post.media.code}`); } catch (error) { console.error('Error uploading photo to Instagram:', error); } })();
以下是几个可行的排查方向:
检查Instagram账号状态
账号可能触发了Ins的反机制,比如频繁发帖被临时限制,或者需要完成邮箱/手机验证。手动登录Ins网页版或APP,确认账号是否有未处理的验证提示、限制通知,确保账号处于正常可用状态。更新instagram-private-api版本
Ins私有API规则会不定期更新,旧版本的库可能无法兼容新接口。执行npm update instagram-private-api将库更新到最新版后重新测试。完善模拟登录流程
当前代码仅调用了simulate.preLoginFlow(),可以补充登录后的模拟流程,模拟真实用户行为,降低被识别为机器人的概率:await ig.account.login(IG_Username, IG_Password); await ig.simulate.postLoginFlow(); // 新增该行验证图片合规性
Ins对发帖图片有严格要求:建议尺寸为1080x1080正方形(或符合1:1、4:5、16:9等官方支持比例),格式为JPG/PNG,文件大小不宜过大。可以更换一张已知合规的图片测试,或对现有图片进行压缩、调整尺寸后再上传。添加操作延迟
频繁的自动化请求容易被检测,在登录和发帖步骤之间添加适当延迟,模拟真实用户的操作间隔:await ig.account.login(IG_Username, IG_Password); await new Promise(resolve => setTimeout(resolve, 2000)); // 延迟2秒再执行发帖固定设备信息
每次运行代码时ig.state.generateDevice(IG_Username)会重新生成设备信息,频繁更换设备指纹可能被Ins标记为异常。可以将生成的设备信息保存到文件,每次启动时加载,保持设备信息一致:// 保存设备信息(首次运行时执行) const deviceState = ig.state.serialize(); await fs.writeFile('./device.json', JSON.stringify(deviceState)); // 后续启动时加载设备信息 const savedDevice = await fs.readFile('./device.json', 'utf8'); ig.state.deserialize(JSON.parse(savedDevice));
内容的提问来源于stack exchange,提问作者Bobosky

