├── .gitignore ├── LICENSE ├── README.md └── instagram.js /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | node_modules/ 3 | 4 | lastInstagramPost\.txt 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Benedikt Magnus 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Instagram Bot Module 2 | 3 | A module for a bot written with NodeJS to fetch new Instgram posts and forward them to a Discord channel. -------------------------------------------------------------------------------- /instagram.js: -------------------------------------------------------------------------------- 1 | const lastInstagramPostFileName = 'instagramSave.json'; 2 | const instagramUrl = 'https://www.instagram.com/'; 3 | const instagramPostUrl = 'https://www.instagram.com/p/'; 4 | 5 | const fs = require('fs'); 6 | const request = require('request'); 7 | const browser = new (require('zombie'))(); 8 | 9 | var save = { 10 | lastInstagramPost: '', 11 | lastInstagramStory: '' 12 | } 13 | 14 | exports.instagramName = ''; //The name of the user on Instagram. 15 | exports.instagramId = ''; //The ID of the user on Instagram. 16 | exports.channelId = ''; //The Discord channel ID. 17 | exports.client = null; //A client created with 'new Discord.Client()' from the Discord.js library. 18 | exports.instagramSessionCookie = {}; //A session cookie to log into Instagram. 19 | exports.checkInterval = 300000; //The interval for checking Instagram in milliseconds. 20 | exports.formatString = ''; //The format string to display the date and time of a post/story. 21 | exports.locale = 'en'; //The locale to display date and time information. 22 | exports.attachMedia = true; //If true, the media files are attached to the message, otherwise links with preview are posted. 23 | 24 | /** 25 | * Starts checking an Instagram account for new posts and send them to the Discord. 26 | */ 27 | exports.startInstagramChecking = function () 28 | { 29 | fs.readFile(lastInstagramPostFileName, function (err, data) 30 | { 31 | save = JSON.parse(data); 32 | save.save = function () { fs.writeFile(lastInstagramPostFileName, JSON.stringify(this), () => {}); }; 33 | 34 | browser.setCookie({ name: 'sessionid', domain: 'instagram.com', value: exports.instagramSessionCookie }); 35 | 36 | setInterval(checkInstagram, exports.checkInterval); //Check every five minutes. 37 | checkInstagram(); 38 | } 39 | ); 40 | } 41 | 42 | function checkInstagram () 43 | { 44 | getPosts(); 45 | getStories(); 46 | } 47 | 48 | function getPosts () 49 | { 50 | getDataFromUrl(instagramUrl + exports.instagramName, function (data) 51 | { 52 | if ((data == undefined) || (data.length == 0)) 53 | return; 54 | 55 | let container = { 56 | postsToSend: [], //Array to hold prepared posts so we can send them in the correct order after going through all new Instagram posts. 57 | links: [], //Array for all media links. 58 | workers: 1, //Numbers of workers working at the post gathering. 59 | finished: 0, //Number of finished workers. 60 | lastInstagramPost: data[0].node.shortcode 61 | } 62 | 63 | for (i = 0; i < data.length; i++) 64 | { 65 | let node = data[i].node; 66 | 67 | if (node.shortcode == save.lastInstagramPost) 68 | break; 69 | 70 | let link = instagramPostUrl + node.shortcode; 71 | 72 | let comment = ''; 73 | if (node.edge_media_to_caption.edges.length > 0) 74 | { 75 | comment += "\r\n" + node.edge_media_to_caption.edges[0].node.text + "\r\n"; 76 | } 77 | 78 | let text = '@everyone' + "\r\n\r\n" + 79 | getDateTimeFromUnix(node.taken_at_timestamp) + ':' + "\r\n" + 80 | comment + "\r\n"; 81 | 82 | text += '<' + link + '>' + "\r\n"; //Prevent preview of main link in Instagram stories because of the following direct media links. 83 | 84 | container.postsToSend.push(text); 85 | 86 | if (exports.attachMedia) 87 | container.links[i] = []; 88 | 89 | startWorker(link, container, i); 90 | } 91 | 92 | workerFinished(container); 93 | } 94 | ); 95 | } 96 | 97 | function getStories () 98 | { 99 | browser.visit('https://www.instagram.com/graphql/query/?query_hash=45246d3fe16ccc6577e0bd297a5db1ab&variables={"reel_ids":["' + exports.instagramId + '"],"precomposed_overlay":false}', function() 100 | { 101 | let data = browser.text(); 102 | 103 | if (data == '') 104 | return; 105 | 106 | data = JSON.parse(data).data; 107 | 108 | if (data.reels_media.length == 0) 109 | return; 110 | 111 | data = data.reels_media[0].items; 112 | 113 | let postsToSend = []; 114 | let files = []; 115 | 116 | for (i = data.length - 1; i >= 0; i--) 117 | { 118 | if (data[i].id == save.lastInstagramStory) 119 | break; 120 | 121 | let text = getDateTimeFromUnix(data[i].taken_at_timestamp) + ':' + "\r\n"; 122 | 123 | if (data[i].is_video) 124 | { 125 | //Go through all videos listet to find the main one, having the highest/native resolution: 126 | let videos = data[i].video_resources; 127 | for (j = 0; j < videos.length; j++) 128 | if (videos[j].profile == 'MAIN') 129 | { 130 | if (exports.attachMedia) 131 | files.push({ 132 | attachment: videos[j].src, 133 | name: getPathFromUrl(videos[j].src), 134 | }); 135 | else 136 | text += videos[j].src; 137 | 138 | break; 139 | } 140 | } 141 | else 142 | { 143 | if (exports.attachMedia) 144 | files.push({ 145 | attachment: data[i].display_url, 146 | name: getPathFromUrl(data[i].display_url), 147 | }); 148 | else 149 | text += data[i].display_url; 150 | } 151 | 152 | postsToSend.push(text); 153 | } 154 | 155 | //Send all stories 156 | for (i = 0; i < postsToSend.length; i++) 157 | { 158 | let targetChannel = exports.client.channels.get(exports.channelId); 159 | 160 | if (exports.attachMedia) 161 | { 162 | targetChannel.send(postsToSend[i], { files: [files[i]] }).catch( 163 | (error) => 164 | { 165 | console.error(error); 166 | } 167 | ); 168 | } 169 | else 170 | { 171 | targetChannel.send(postsToSend[i]).catch( 172 | (error) => 173 | { 174 | console.error(error); 175 | } 176 | ); 177 | } 178 | } 179 | 180 | if (postsToSend.length > 0) 181 | { 182 | save.lastInstagramStory = data[data.length - 1].id; 183 | save.save(); 184 | } 185 | } 186 | ); 187 | } 188 | 189 | function getDataFromUrl (url, callback) 190 | { 191 | request(url, function (error, response, body) 192 | { 193 | if (error) 194 | console.log(error); 195 | 196 | callback(getDataFromHtml(body)); 197 | } 198 | ); 199 | } 200 | 201 | function getDataFromHtml (body) 202 | { 203 | let startIndex = body.indexOf('window._sharedData = ') + 21; 204 | let endIndex = body.indexOf('window.__initialDataLoaded(window._sharedData);'); //First unique value after the full JSON. 205 | 206 | let data = body.substr(0, endIndex).substr(startIndex); 207 | let lastPositionAfterBracket = data.length - 1; 208 | 209 | //We have to go backwards to find the end of the JSON (a closing bracket) because the first unique value is anywhere near behind the JSON. 210 | while ((data.charAt(lastPositionAfterBracket) != '}') && (lastPositionAfterBracket > 0)) 211 | lastPositionAfterBracket--; 212 | 213 | if (lastPositionAfterBracket <= 0) 214 | { 215 | console.log('No data was given back from Instagram or a parsing error.'); 216 | return; 217 | } 218 | 219 | data = data.substr(0, lastPositionAfterBracket + 1); 220 | data = JSON.parse(data); 221 | data = data.entry_data; 222 | 223 | if (data.ProfilePage != undefined) 224 | data = data.ProfilePage[0].graphql.user.edge_owner_to_timeline_media.edges; //Index page 225 | else 226 | { 227 | data = data.PostPage[0].graphql.shortcode_media; 228 | 229 | if (data.edge_sidecar_to_children != undefined) 230 | data = data.edge_sidecar_to_children.edges; //Galery page 231 | else 232 | data = [{node: data}]; //Single media file page. 233 | } 234 | 235 | return data; 236 | } 237 | 238 | function startWorker (link, container, index) 239 | { 240 | container.workers++; 241 | 242 | getDataFromUrl(link, function (data) 243 | { 244 | for (i = 0; i < data.length; i++) 245 | { 246 | container.postsToSend[index] += "\r\n"; 247 | 248 | let targetUrl = ''; 249 | 250 | if (data[i].node.is_video) 251 | targetUrl = data[i].node.video_url; 252 | else 253 | targetUrl = data[i].node.display_url; 254 | 255 | if (exports.attachMedia) 256 | container.links[index].push(targetUrl); //The direct link will later be attached to the Discord message. 257 | else 258 | container.postsToSend[index] += targetUrl; 259 | } 260 | 261 | workerFinished(container); 262 | } 263 | ); 264 | } 265 | 266 | function workerFinished (container) 267 | { 268 | container.finished++; 269 | 270 | if (container.workers == container.finished) 271 | { 272 | //Send all posts, backwards through postsToSend for the correct order from old to new: 273 | for (i = container.postsToSend.length - 1; i >= 0; i--) 274 | { 275 | let targetChannel = exports.client.channels.get(exports.channelId); 276 | 277 | if (exports.attachMedia) 278 | { 279 | const files = []; 280 | for (link of container.links[i]) 281 | { 282 | files.push({ 283 | attachment: link, 284 | name: getPathFromUrl(link), 285 | }); 286 | } 287 | targetChannel.send(container.postsToSend[i], { files: files }).catch( 288 | (error) => 289 | { 290 | console.error(error); 291 | } 292 | ); 293 | } 294 | else 295 | { 296 | targetChannel.send(container.postsToSend[i]).catch( 297 | (error) => 298 | { 299 | console.error(error); 300 | } 301 | ); 302 | } 303 | } 304 | 305 | //When there was a new post, store the newest post ID on the harddrive: 306 | if (container.postsToSend.length > 0) 307 | { 308 | save.lastInstagramPost = container.lastInstagramPost; 309 | 310 | save.save(); 311 | } 312 | } 313 | } 314 | 315 | function getDateTimeFromUnix (unixTimestamp) 316 | { 317 | let dateTime = require('moment').unix(unixTimestamp); 318 | 319 | dateTime.locale(exports.locale); 320 | 321 | if (exports.formatString == '') 322 | return dateTime.format(); 323 | else 324 | return dateTime.format(exports.formatString); 325 | } 326 | 327 | function getPathFromUrl(url) 328 | { 329 | return url.split(/[?#]/)[0]; 330 | } --------------------------------------------------------------------------------