instagram-private-api icon indicating copy to clipboard operation
instagram-private-api copied to clipboard

Direct message | DM script

Open alexrmacleod opened this issue 4 years ago • 2 comments

Has anyone used this instagram-private-api to build a list of usernames from hashtags or location ids and then scheduled/sent direct messages to those usernames?

Would appreciate it if you could share your script or even just a code snippet. Would save me tons of time!

alexrmacleod avatar May 06 '20 03:05 alexrmacleod

I'm working on something similar, but I'm having a bit of an issue sending DMs. My script is basically this:

const user = this.configService.get<string>(ENV_USERNAME);
const pass = this.configService.get<string>(ENV_PASSWORD);

await this.instagramClient.account.login(user, pass);

const userID = await this.instagramClient.user.getIdByUsername('some_username');
const thread = this.instagramClient.entity.directThread(userID.toString());
await thread.broadcastText(messageBody);

But the error I'm getting back is

IgResponseError: POST /api/v1/direct_v2/threads/broadcast/text/ - 400 Bad Request; 
    at Request.handleResponseError (XXX/node_modules/instagram-private-api/dist/core/request.js:125:16)
    at Request.send (XXX/node_modules/instagram-private-api/dist/core/request.js:53:28)
    at async DirectThreadRepository.broadcast (XXX/node_modules/instagram-private-api/dist/repositories/direct-thread.repository.js:176:26)
    at async DirectThreadEntity.broadcast (XXX/node_modules/instagram-private-api/dist/entities/direct-thread.entity.js:192:26)
    at async DirectThreadEntity.broadcastText (XXX/node_modules/instagram-private-api/dist/entities/direct-thread.entity.js:26:16)

sunderee avatar Oct 26 '21 11:10 sunderee

@alexrmacleod @sunderee

I'm late to the discussion, but here's my code that's working for sending DMs:

import { IgApiClient } from 'instagram-private-api'
import { config } from 'dotenv'

const sendMessageToIGUser = async ({ message, recipient }) => {
	// Instantiate the IG client
	const ig = new IgApiClient()

	// Login using your IG username/password
	config()
	const username = process.env.IG_USERNAME
	const password = process.env.IG_PASSWORD

	ig.state.generateDevice(username)
	await ig.account.login(username, password).catch((err) => console.log({ loginErr: err }))

	// Get the recipient user's ID
	const userID = await ig.user
		.getIdByUsername(recipient)
		.catch((err) => console.log({ getIdByUsernameErr: err }))

	// Create a DM thread and send the message
	const thread = ig.entity.directThread([userID.toString()])
	const sendRes = await thread
		.broadcastText(message)
		.catch((err) => console.log({ broadcastTextErr: err }))

	// Handle success/failure
	if (Boolean(sendRes) && typeof sendRes === 'object') {
		console.log(`Message successfully sent to ${recipient}.`)
	} else {
		console.log(`Failed to send message to ${recipient}.`)
	}
}

wjd3 avatar Dec 13 '22 23:12 wjd3