Skip to content

Instantly share code, notes, and snippets.

@spraddles
Last active March 1, 2023 05:46
Show Gist options
  • Save spraddles/eb1ad93b2872191d861bcea5a7e43018 to your computer and use it in GitHub Desktop.
Save spraddles/eb1ad93b2872191d861bcea5a7e43018 to your computer and use it in GitHub Desktop.
Instagram API for posting a video to a business page
import axios from 'axios'
import dotenv from 'dotenv'
dotenv.config()
export const selfPostInstagram = async (description, tags, date, video) => {
const API = 'https://graph.facebook.com/v16.0'
const INSTAGRAM_BUSINESS_ACCOUNT = process.env.INSTAGRAM_BUSINESS_ACCOUNT
const INSTAGRAM_GRAPH_ACCESS_TOKEN = process.env.INSTAGRAM_GRAPH_ACCESS_TOKEN
// @TODO: do token validity check first
const createMediaObjectContainer = async () => {
try {
const response = await axios.post(API + `/${INSTAGRAM_BUSINESS_ACCOUNT}/media`, {
access_token: INSTAGRAM_GRAPH_ACCESS_TOKEN,
media_type: 'REELS',
share_to_feed: false,
video_url: video,
caption: `${description} ${tags}`
})
return response.data.id
}
catch (e) {
console.log(e.response.data)
}
}
const checkContainerStatus = async (mediaObjectContainerId) => {
try {
const response = await axios.get((API + '/' + mediaObjectContainerId), {
params: {
fields: 'status,status_code',
access_token: INSTAGRAM_GRAPH_ACCESS_TOKEN
}
})
// @TODO: add increment count rule
if (await response.data.status_code === 'IN_PROGRESS') {
console.log('file upload in progress')
return setTimeout(async () => await checkContainerStatus(mediaObjectContainerId), 5000)
}
if (await response.data.status_code === 'FINISHED') {
await publishMediaObjectContainer(mediaObjectContainerId)
return Promise.resolve('file uploaded!')
}
if (await response.data.status_code === 'EXPIRED' || response.status_code === 'ERROR') {
return Promise.reject('cant upload file')
}
}
catch(e) {
console.log(e.response.data)
}
}
const publishMediaObjectContainer = async (mediaObjectContainerId) => {
try {
const response = await axios.post((API + '/' + INSTAGRAM_BUSINESS_ACCOUNT + '/media_publish'), {
access_token: INSTAGRAM_GRAPH_ACCESS_TOKEN,
creation_id: mediaObjectContainerId,
})
return console.log('media is uploaded!')
}
catch(e) {
console.log(e.response.data)
}
}
// @TODO: convert to .then() syntax
const mediaObjectContainerId = await createMediaObjectContainer()
await checkContainerStatus(mediaObjectContainerId)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment