是否可以在 NodeJS 中以编程方式获取和发送 Instagram 直接消息?我找不到有关该主题的任何最新答案,因此决定在这里提问。
现在我知道有:
据我所知,第一和第二没有用于直接消息的 api。 第三个有点可疑。很难说它到底是如何工作的。 Instagram 允许开发者使用这个库吗?
如果您使用
instagram-private-api
,您可以通过以下方式发送直接消息:
const userId = await ig.user.getIdByUsername('username');
const thread = ig.entity.directThread([userId.toString()]);
await thread.broadcastText('Message from node');
(来源:https://github.com/dilame/instagram-private-api/issues/792)
自2021年8月16日起,您可以通过官方API发送IG消息。
这里引自官方“FACEBOOK for developers”网站: “自 2021 年 8 月 16 日起,所有 Instagram 企业帐户都可以连接到 Instagram 的 Messenger API。” (Instagram 消息传递)
带有 NodeJS 和
instagram-private-api
的完整代码:
require("dotenv").config();
const { IgApiClient } = require("instagram-private-api");
const postToInsta = async (orderDetails) => {
try {
//Contect Instagram API Client
const ig = new IgApiClient();
ig.state.generateDevice(process.env.IG_USERNAME);
await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);
//Set user ID
const userId = await ig.user.getIdByUsername("said user");
const thread = ig.entity.directThread([userId.toString()]);
//Send Mesage
await thread.broadcastText("Message from node");
return true;
} catch (err) {
return err;
}
};
const instaPost = postToInsta().then(function (instaPost) {
if (instaPost == true) {
console.log(`Message Sent Succesfully`);
}
});
只需使用
在 .env 文件中设置环境变量IG_USERNAME = "<username>"
IG_PASSWORD = "<password>"
下载
npm i instagram-private-api