Twitter Search API (2) - php

My web app requires users to cast votes via twitter and display those votes in a line chart. Id like to accomplish this whole thing using JavaScript.
My Requirements:
Using the twitter API, I need to Collect votes in real time and have those votes displayed in a line chart, in real time!

Using the twitter API, I need to Collect votes in real time and have those votes displayed in a line chart, in real time!
If you're doing real time stuff, you want to use the Streaming API. It's pretty easy to get up and running quickly using existing open-source client implementations like Phirehose. It comes with some great examples too.
Here's their example that tracks a bunch of keywords: you'd probably want to track whatever hashtag people are voting on:
<?php
require_once('../lib/Phirehose.php');
/**
* Example of using Phirehose to display a live filtered stream using track words
*/
class FilterTrackConsumer extends Phirehose
{
/**
* Enqueue each status
*
* #param string $status
*/
public function enqueueStatus($status)
{
/*
* In this simple example, we will just display to STDOUT rather than enqueue.
* NOTE: You should NOT be processing tweets at this point in a real application, instead they should be being
* enqueued and processed asyncronously from the collection process.
*/
$data = json_decode($status, true);
if (is_array($data) && isset($data['user']['screen_name'])) {
print $data['user']['screen_name'] . ': ' . urldecode($data['text']) . "\n";
}
}
}
// Start streaming
$sc = new FilterTrackConsumer('username', 'password', Phirehose::METHOD_FILTER);
$sc->setTrack(array('morning', 'goodnight', 'hello', 'the'));
$sc->consume();
If you're low volume, you could probably just shove the tweet right into the database in enqueueStatus.

Have you checked the Twitter-API itself?
http://dev.twitter.com/doc
The documentation is pretty verbose and contains also some examples on how to use it with JavaScript.
(probably you will have to sing in or sign up to get access to the api, I am not sure).

Related

Where is the documentation for all function/property($word->Documents->Open(), $excel->Visible... ) in COM PHP?

As i checked on https://www.php.net/manual/en/ref.com.php#19688 page, i can see some examples of how to use COM object function but I don't know where to see the full documentation of these COM function? For example:
<?php
/***
* Grouping Rows optically in Excel Using a COM Object
*
* That was not easy, I have spent several hours of trial and error to get
* this thing to work!!!
*
* #author Kulikov Alexey <a.kulikov#gmail.com>
* #since 13.03.2006
*
* #see Open Excel, Hit Alt+F11, thne Hit F2 -- this is your COM bible
***/
//starting excel
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print "Loaded excel, version {$excel->Version}\n";
//bring it to front
#$excel->Visible = 1;//NOT
//dont want alerts ... run silent
$excel->DisplayAlerts = 0;
//create a new workbook
$wkb = $excel->Workbooks->Add();
//select the default sheet
$sheet=$wkb->Worksheets(1);
//make it the active sheet
$sheet->activate;
//fill it with some bogus data
for($row=1;$row<=7;$row++){
for ($col=1;$col<=5;$col++){
$sheet->activate;
$cell=$sheet->Cells($row,$col);
$cell->Activate;
$cell->value = 'pool4tool 4eva ' . $row . ' ' . $col . ' ak';
}//end of colcount for loop
}
///////////
// Select Rows 2 to 5
$r = $sheet->Range("2:5")->Rows;
// group them baby, yeah
$r->Cells->Group;
// save the new file
$strPath = 'tfile.xls';
if (file_exists($strPath)) {unlink($strPath);}
$wkb->SaveAs($strPath);
//close the book
$wkb->Close(false);
$excel->Workbooks->Close();
//free up the RAM
unset($sheet);
//closing excel
$excel->Quit();
//free the object
$excel = null;
?>
In the script above, I can not find documentation for Visible, DisplayAlerts, Worksheets, activate, SaveAs, Workbooks->Add().... property, function in php website
Thank in advance
The Excel object model is described in MSDN.
Be aware that Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
If you deal with open XML documents only you may consider using the Open XML SDK, see Welcome to the Open XML SDK 2.5 for Office for more information.

PHP Live Chat Message insert ( Live streaming Chat, not VideoID Comment )

I'm actually building a PHP bot that reads the youtube live streaming chat, and store in a Database the message that contains a specific keyword wrote by the users during the livestream. All the logic is in place, what is missing is the feedback on chat when the bot is "triggered".
I looked everywhere but seams the PHP documentation is missing, if you look inside the PHP Classes there is the public function insert, but there is no example at all on how to use it?
Someone know how to use it?
Should be something "simple" like: $result = $youtube->liveChatMessages->Insert($args); but I can't figure out on what args looks like.
HERE the only reference about the Insert method
Thanks to all for any suggestion on how to use it!
17/06/2018 edit Working Example
$liveChatMessage = new Google_Service_YouTube_LiveChatMessage();
$liveChatSnippet = new Google_Service_YouTube_LiveChatMessageSnippet();
$liveChatSnippet->setLiveChatId($liveChatID);
$liveChatSnippet->setType("textMessageEvent");
$messageDetails = new Google_Service_YouTube_LiveChatTextMessageDetails();
$messageDetails->setMessageText("Message to type in chat");
$liveChatSnippet->setTextMessageDetails($messageDetails);
$liveChatMessage->setSnippet($liveChatSnippet);
$videoCommentInsertResponse = $youtube->liveChatMessages->insert('snippet', $liveChatMessage);

REST Api Tracking Unique Page Views

I am developing a PHP REST api using Api Platform for my website where users can post 'Reviews' (similar to articles).I want to track unique page views for this articles so I can later sort by most viewed reviews and display them.
I have read a lot of solutions online and I have implemented two of them: Google Analytics tracking and Redis + browser fingerprinting.
First, the Google Analytics tracking works quite well, I am using the 'ga:uniquePageviews' property with a filter for the page path to get using the Google PHP Api the unique page views. The only problem with this method is that some users use ad blockers and they block Google Analytics so no page view will be recorded for those people.
I have also implemented view tracking using Redis + browser fingerprinting (using fingerprintjs2) for anonymous users, and using the user id for logged in users. So for logged in users, if they have not visited the page in the last 30 minutes, a new unique view is added. This seems to work quite well.
The problem is with anonymous users. Currently, on the website side I am using fingerprintjs2 library to generate a browser fingerprint which is then passed to the REST api in a header and if that fingerprint did not visit the page in the last 30 minutes, then a new unique view is added. But because my REST api is going to be public (I plan on maybe also making a mobile app in the future), anyone can just put whatever then want in the fingerprint header and just keep changing it and a new unique view will be recorded and I am not sure how to fix this. Would allowing CORS only from my website domain fix this?But then what about the mobile app?
Right now I am inclined to think that using Google Analytics is the best way despite ad blockers, but the Redis approach just seems pretty cool to me and I would also like to get that working.
Here is a code example of what I am currently using for Redis:
public function addAndGetReviewViews(Request $request, $id)
{
$viewsKey = 'pageviews-review-' . $id;
$setKey = 'uniqueviews-review-' . $id;
$user = $this->getUser();
if ($user) {
$userId = $user->getId();
} else if ($request->headers->has('X-Anonymous-Fingerprint')) {
$userId = base64_encode(
substr($request->headers->get('X-Anonymous-Fingerprint'), 0, 32)
);
} else {
// Only add views if user is logged in or has anonymous fingerprint
return $this->redis->get($viewsKey) ?: 0;
}
$setExists = $this->redis->exists($setKey);
if (!$this->redis->sismember($setKey, $userId)) {
$this->redis->sadd($setKey, $userId);
$this->redis->incr($viewsKey);
}
if (!$setExists) {
$this->redis->expire($setKey, 1800);
}
return $this->redis->get($viewsKey);
}

PHP - Twilio Recording Duration Value Issue

So I'm creating an application that allows users to record a message through Twilio and I'm attempting to store the RecordingSID, the date it was created, and the duration of the recording in a MySQLi database right after the recording has been made. I've managed to get the RecordingSID by taking the last 34 digits off the RecordingURL using the substr() function and am simply getting whatever today's date is for the date created field in my database table. However, seemingly regardless of how long the actual recording is, I'm continually getting a value of 8 when attempting to get the recording duration. Here's what I've got right now (with database inserts omitted since they work):
<?php
$recordingURL = $_REQUEST['RecordingUrl'];
$recordingSID = substr($recordingURL, -34);
date_default_timezone_set('EST');
$dateCreated = date("Y-m-d");
$duration = $_REQUEST['RecordingDuration'];
?>
Any help with this matter would be fantastic! Thanks!
Edit: I've also tried the following solution in place of the last line in my previous code snippet:
<?php
$recordings = $client->account->recordings->getIterator(0, 50, array('Sid' => $recordingSID,));
foreach ($recordings as $recording)
{
$duration = $recording->duration;
}
?>
Based on that code sample you've pasted in, you could be doing a couple of things incorrectly. Correct me if I'm wrong, but I believe you are trying to request a Recording resource back from the Twilio API after you've submitted one with the Twilio js and their TwiML?
If so, twilio actually has a nice little demo of exactly your use case.
You shouldn't see anything in the $_REQUEST['RecordingDuration'], I'm not sure why you are even getting a value of 8 returned. Basically what you want to do is find the users recordings by using the Twilio REST API.
here is an example snippet:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACda6f132a3c49700934481addd5ce1659";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
// Loop over the list of recordings and echo a property for each one
foreach ($client->account->recordings as $recording) {
echo $recording->duration;
}
The response from the API call will return a Recording resource.
Here is some more examples from their docs

Understanding Twitter API's "Cursor" parameter

I don't really get how to use the Curesor parameter in Twitter's API, for an exmaple - here.
Am I supposed to make a new API call for each 100 followers?
I'd love it if someone could provide a PHP example for getting a full list of followers assuming I have more than 100...
Thanks in advance!
You need to pass the cursor value back to the API to get the next "chunk" of followers. Then you take the cursor parameter from that chunk and pass it back to get the next chunk. It is like a "get the next page" mechanism.
Since this question was asked, Twitter API has changed in many ways.
Cursor is used to paginate API responses with many results. For example, a single API call to obtain followers will retrieve a maximum of 5000 ids.
If you want to obtain all the followers of a user you will have to make a new API call, but this time you have to indicate the "next_cursor" number that was in your first response.
If it's useful, the following python code will retrieve followers from a given user.
It will retrieve a maximum of pages indicated by a constant.
Be careful not to be banned (i.e.: don't make more than 150 api calls/hour in anonymous calls)
import requests
import json
import sys
screen_name = sys.argv[1]
max_pages = 5
next_cursor = -1
followers_ids = []
for i in range(0,max_pages):
url = 'https://api.twitter.com/1/followers/ids.json?screen_name=%s&cursor=%s' % (screen_name, next_cursor)
content = requests.get(url).content
data = json.loads(content)
next_cursor = data['next_cursor']
followers_ids.extend(data['ids'])
print "%s have %s followers!" % (screen_name, str(len(followers_ids)))
Despite you asked it some time ago, I hope this will be the more accurated answer.
Twitter does not offer info about what next_cursor means. Only how cursor works.
It is only an easy way for Twitter to manage pagination.
«The function is intended to be used linearly, one cursor set at a time per user.» Source
«It's potentially less efficient for you but much more efficient
for us.» Twitter Staff
BUT...
Someone ask before in a broken link «are cursors persistents? seem that the answer is "yes"»
This means you can save your last cursor before 0 and continue with it next time.
Check out http://code.google.com/p/twitter-boot/source/browse/trunk/twitter-bot.php
foreach ($this->twitter->getFollowers(,0 ) as $follower)//the 0 is the page
{
if ($this->twitter->existsFriendship($this->user, $follower['screen_name'])) //If You Follow this user
continue; //no need to follow now;
try
{
$this->twitter->createFriendship($follower['screen_name'], true); // If you dont Follow Followit now
$this->logger->debug('Following new follower: '.$follower['screen_name']);
}
catch (Exception $e)
{
$this->logger->debug("Skipping:".$follower['screen_name']." ".$e->getMessage());
}
}
}

Categories