Skip to content

Added Comment Fetcher #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
vendor/
composer.lock
config.php
/nbproject/private/
/nbproject
/extensions/CommentFetcher/log.log
/comments.html
/extensions/CommentFetcher/error.log
104 changes: 104 additions & 0 deletions extensions/CommentFetcher/CommentFetcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
<?php
use InstagramAPI\Instagram;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* Description of CommentFetcher
*
* @author Arriba-PC
*/
class CommentFetcher implements Extension {

public $savedComments = [];
private $broadcastId;
private Instagram $ig;
private $lastTimestamp = 0;
private $process = null;

private $templateFilePath = './extensions/CommentFetcher/Template.html';

public function __construct($broadcastId, $ig){
$this->broadcastId = $broadcastId;
$this->ig = $ig;
}

public function getComments(){
$this->broadcastId;
$live = $this->ig->live;
$comments = $live->getComments($this->broadcastId, $this->lastTimestamp);
foreach ($comments->getComments() as &$comment) {
array_push($this->savedComments, $comment);
$this->lastTimestamp = $comment->getCreatedAt();
}

print("Last timestamp for messages : ".$this->lastTimestamp);
}

public function printComments($toHtml = false){
$this->getComments();
$comments = array_slice($this->savedComments, -5);
if(!$toHtml){
foreach ($comments as &$comment){
$username = $comment->getUser()->getUsername();
$message = $comment->getText();
logM("$username : \n $message");
}
} else {
$this->generateCommentsHTML($comments);
}
}

private function generateCommentsHTML($comments){
$commentDivs = '';
print("\n\nGenerating comments HTML...\n\n");
foreach ($comments as &$comment) {
$commentDivs .= $this->generateCommentDiv($comment);
}

$myfile = fopen($this->templateFilePath, "r") or die("Unable to open file!");
$template = fread($myfile,filesize($this->templateFilePath));
fclose($myfile);

$templateFilled = str_replace('!COMMENTS_PLACEHOLDER!', $commentDivs, $template);
$myfile = fopen("comments.html", "w") or die("Unable to open comments file!");
fwrite($myfile, $templateFilled);
fclose($myfile);
print("\n\Comments Printed to HTML...\n\n");


}

private function generateCommentDiv(\InstagramAPI\Response\Model\Comment $comment){
$username = $comment->getUser()->getUsername();
$message = $comment->getText();

$div = "<div class='comment'><div class='commentWrapper'>";
$div .= "<p class='commentUser'>$username : </p> <p class='commentMessage'>$message </p> ";
$div .= "</div></div>";
return $div;
}

public function run() {
$broadcastId = $this->broadcastId;
$cmd = "php extensions/CommentFetcher/RunCommentFetcher.php -id=$broadcastId";
$spec = array (
0 => array('pipe', 'r'),
1 => array('file', 'extensions/CommentFetcher/log.log', 'w'), // or 'a' to append
2 => array('file', 'extensions/CommentFetcher/error.log', 'w'),
);
$this->process = proc_open( $cmd, $spec, $pipes);
}

public function stop(){
$status = proc_get_status($this->process);
return exec('taskkill /F /T /PID '.$status['pid']);
}


}

43 changes: 43 additions & 0 deletions extensions/CommentFetcher/RunCommentFetcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

require './vendor/autoload.php';
require_once './extensions/Extension.php';
require_once './extensions/CommentFetcher/CommentFetcher.php';
require_once './config.php';

use InstagramAPI\Instagram;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

$ig = new Instagram(false, false);

$broadcastId = null;
foreach ($argv as $arg){
if($idPos = strpos($arg, '-id=') !== false){
$broadcastId = substr($arg, $idPos + 3);
$broadcastId = explode(" ", $broadcastId)[0];
}
}

if(!$broadcastId || empty($broadcastId)){
die("No broadcast id sent!");
}

try {
$ig->login(IG_USERNAME, IG_PASS);
} catch (\Exception $e) {
echo 'Error While Logging in to Instagram: '.$e->getMessage()."\n";
exit(0);
}

print($broadcastId);

$commentFetcher = new CommentFetcher($broadcastId, $ig);
while(true){
sleep(10);
$commentFetcher->printComments(true);
}
58 changes: 58 additions & 0 deletions extensions/CommentFetcher/Template.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Comment Section IG Live</title>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="5">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div> !COMMENTS_PLACEHOLDER! </div>
</body>

<style>
body{
margin: auto;
width: 90vw;
max-width: 400px;
height: 1000px;
}

.comment{
background-color: #585858;
box-shadow: 0px 0px 2px 1px #999;
border-radius: 10px;
width: 100%;
max-height: 200px;
line-break: anywhere;
margin-top: 10px;
font-family: sans-serif;
}
.commentWrapper{
padding: 10px;
}

p.commentUser {
color: white;
font-weight: bold;
letter-spacing: 0.05rem;
font-family: sans-serif;
}

p.commentMessage {
color: white;
}
</style>

<script>

window.scrollTo(0,document.body.scrollHeight);


</script>
</html>
18 changes: 18 additions & 0 deletions extensions/Extension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* Description of Extension
*
* @author Arriba-PC
*/
interface Extension {
public function run();
public function stop();

}
21 changes: 21 additions & 0 deletions extensions/ExtensionsList.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* Description of ExtensionsList
*
* @author Arriba-PC
*/
class ExtensionsList extends \ArrayObject {
public function offsetSet($key, $val) {
if ($val instanceof Extension) {
return parent::offsetSet($key, $val);
}
throw new \InvalidArgumentException('Value must be a Extension');
}
}
61 changes: 56 additions & 5 deletions goLive.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
require __DIR__.'/vendor/autoload.php';
use InstagramAPI\Instagram;
use InstagramAPI\Request\Live;
use InstagramAPI\Response\BroadcastCommentsResponse;

require_once './extensions/Extension.php';
require './extensions/ExtensionsList.php';
require './extensions/CommentFetcher/CommentFetcher.php';

require_once 'config.php';
/////// (Sorta) Config (Still Don't Touch It) ///////
Expand All @@ -26,6 +31,13 @@
//Login to Instagram
logM("Logging into Instagram...");
$ig = new Instagram($debug, $truncatedDebug);

$extensions = new ExtensionsList();

$commentFetcherExtensionName = "CommentFetcher";

$broadcastId = null;

try {
$ig->login(IG_USERNAME, IG_PASS);
} catch (\Exception $e) {
Expand All @@ -49,20 +61,24 @@
'rtmp://\1:80/',
$stream->getUploadUrl()
);

print($stream->getUploadUrl());
//Grab the stream url as well as the stream key.
$split = preg_split("[".$broadcastId."]", $streamUploadUrl);

$streamUrl = $split[0];
$streamKey = $broadcastId.$split[1];

logM("================================ Stream URL ================================\n".$streamUrl."\n================================ Stream URL ================================");

logM("======================== Current Stream Key ========================\n".$streamKey."\n======================== Current Stream Key ========================");

logM("^^ Please Start Streaming in OBS/Streaming Program with the URL and Key Above ^^");

logM("Live Stream is Ready for Commands:");

loadExtensions();
runExtensions();

newCommand($ig->live, $broadcastId, $streamUrl, $streamKey);
logM("Something Went Super Wrong! Attempting to At-Least Clean Up!");
$ig->live->getFinalViewerList($broadcastId);
Expand All @@ -78,14 +94,26 @@ function newCommand(Live $live, $broadcastId, $streamUrl, $streamKey) {
print "\n> ";
$handle = fopen ("php://stdin","r");
$line = trim(fgets($handle));
handleCommand($line, $handle);
fclose($handle);
newCommand($live, $broadcastId, $streamUrl, $streamKey);
}


function handleCommand($line, $handle = null){
global $ig, $broadcastId, $extensions, $commentFetcherExtensionName;
$live = $ig->live;
if($line == 'ecomments') {
$live->enableComments($broadcastId);
logM("Enabled Comments!");
} elseif ($line == 'dcomments') {
$live->disableComments($broadcastId);
logM("Disabled Comments!");
} elseif ($line == 'getcomments'){
$extensions[$commentFetcherExtensionName]->printComments();
} elseif ($line == 'stop' || $line == 'end') {
fclose($handle);
stopExtensions();
//Needs this to retain, I guess?
$live->getFinalViewerList($broadcastId);
$live->end($broadcastId);
Expand Down Expand Up @@ -119,15 +147,38 @@ function newCommand(Live $live, $broadcastId, $streamUrl, $streamKey) {
} elseif ($line == 'help') {
logM("Commands:\nhelp - Prints this message\nurl - Prints Stream URL\nkey - Prints Stream Key\ninfo - Grabs Stream Info\nviewers - Grabs Stream Viewers\necomments - Enables Comments\ndcomments - Disables Comments\nstop - Stops the Live Stream");
} else {
logM("Invalid Command. Type \"help\" for help!");
logM("Invalid Command. Type \"help\" for help!");
}
fclose($handle);
newCommand($live, $broadcastId, $streamUrl, $streamKey);
}




/**
* Logs a message in console but it actually uses new lines.
*/
function logM($message) {
print $message."\n";
}



function runExtensions(){
global $extensions;
foreach($extensions as $extension){
$extension->run();
}
}

function stopExtensions(){
global $extensions;
foreach($extensions as $extension){
$extension->stop();
}
}

function loadExtensions(){
global $extensions, $broadcastId, $commentFetcherExtensionName, $ig;
$extensions[$commentFetcherExtensionName] = new CommentFetcher($broadcastId, $ig);

}