danieldevine / bird-elephant Goto Github PK
View Code? Open in Web Editor NEWPHP library for Twitter API v2
License: MIT License
PHP library for Twitter API v2
License: MIT License
Describe the bug
I have upload an image, but there are not media_id_string value
To Reproduce
`
$twitter = new \Coderjerk\BirdElephant\BirdElephant($credentials);
$image = $twitter->tweets()->upload('img/habilitada.gif');
$media = (new \Coderjerk\BirdElephant\Compose\Media)->mediaIds([$image->media_id_string]);
$tweet = (new \Coderjerk\BirdElephant\Compose\Tweet)->text('Mensaje con imagen: @johnarleycano')
->media($media);`
Screenshots
If applicable, add screenshots to help explain your problem.
Environment (please complete the following information):
Additional context
Notice: Undefined property: GuzzleHttp\Exception\ClientException::$media_id_string in
I couldn't find this anywhere in the documentation and/or find the corresponding endpoint, but I would like to grab the users list(s) and output tweets.
Endpoint: https://developer.twitter.com/en/docs/twitter-api/lists/list-tweets/introduction
Is there a way to grab the tweets from a list?
FYI The example code has an error in the credential array, it's missing a comma. Unless it's implied to remove it if you aren't using auth 2.0, which I did.
I can't get a basic tweet creation example to work:
<?php
require_once 'vendor/autoload.php';
use Coderjerk\BirdElephant\BirdElephant;
//your credentials, should be passed in via $_ENV or similar, don't hardcode.
$credentials = array(
'consumer_key' => '', //valid confirmed through CURL
'consumer_secret' => '', //valid confirmed through CURL
'bearer_token' => '', //valid confirmed through CURL
'token_identifier' => '', //valid confirmed through CURL
'token_secret' => '' //valid confirmed through CURL
);
//instantiate the object
$twitter = new BirdElephant($credentials);
$tweet = (new \Coderjerk\BirdElephant\Compose\Tweet)->text("test tweet");
$twitter->tweets()->tweet($tweet);
?>
Results in the error:
PHP Parse error: syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST) in /var/www/vendor/coderjerk/bird-elephant/src/BirdElephant.php on line 21
Any ideas? Thank you.
Hello,
Thank you for providing this SDK :)
I'm using your authenticate.php
and index.php
example.
I get the access token successfully,
but then, for some reason, I'm not able to see my own tweets.
My account is protected, but I should be able to see my own tweets! :)
(it works for public users)
->me()->myself()
returns my own user, so the access token is definitely being set.
But when I do $user->tweets()
, I get this:
Sorry, you are not authorized to see the user with id: [MY_USER_ID]
MY_USER_ID
being the correct user ID - I double checked that.
Do you have any idea what could be the problem?
My scopes:
'scope' => [
'tweet.read',
'users.read',
'follows.read',
'like.read',
'list.read'
]
And the Authorization page also mentions that my app will be able to see protected tweets too.
Thanks!
Hi,
Please help me with the below errors :
if($fromdate){
$fromdate= new \DateTime($fromdate);
$starttime=$fromdate->format(\DateTimeInterface::ATOM); // Updated ISO8601
array_push($params,['start_time'=>$starttime]);
}
if($todate){
$todate= new \DateTime($todate);
$todate=$todate->sub(new \DateInterval("PT30S"));
$endtime=$todate->format(\DateTimeInterface::ATOM); // Updated ISO8601
array_push($params,['end_time'=>$endtime]);
}
The below is one error when I use start time and end time parameters:
GuzzleHttp\Exception\ClientException
Client error: GET https://api.twitter.com/2/tweets/search/recent?query=%23nomore&tweet.fields=created_at%2Clang&max_results=100&expansions=author_id&user.fields=name%2Cusername&0%5Bstart_time%5D=2022-01-18T00:00:00%2B00:00&1%5Bend_time%5D=2022-01-23T23:59:30%2B00:00
resulted in a 400 Bad Request
response: {"errors":[{"parameters":{"1[end_time]":["2022-01-23T23:59:30+00:00"]},"message":"The query parameter [1[end_time]] is n (truncated...)
=================
The below is working but it is giving me error in the next_token pagination, but working only for 100 tweets.
GuzzleHttp\Exception\ClientException
Client error: GET https://api.twitter.com/2/tweets/search/recent?query=%23nomore&tweet.fields=created_at%2Clang&max_results=100&expansions=author_id&user.fields=name%2Cusername&0%5Bnext_token%5D=b26v89c19zqg8o3fpe4782uwnhbxdndndwsfb7cq81ev1
resulted in a 400 Bad Request
response: {"errors":[{"parameters":{"0[next_token]":["b26v89c19zqg8o3fpe4782uwnhbxdndndwsfb7cq81ev1"]},"message":"The query parame (truncated...)
Please help me on how to fix it.
Thanks and I am waiting for reply.
Mussa
At this moment the sleep()
methods on the uploadMedia()
function gets a null
argument, so it keeps refreshing. This is because the check_after_secs
parameter has to be in the processing_info
object.
Line 245 in cff000f
I think it should work if you change this line to:
sleep($status->processing_info->check_after_secs);
I try to upload image got this error!
Return value of Coderjerk\BirdElephant\Request::uploadMedia() must be an instance of Coderjerk\BirdElephant\mixed, instance of GuzzleHttp\Exception\ClientException returned
how to handle this error?
Hi there! Andy here, from Twitter Developer Relations.
Thanks for building on the v2 API, it's exciting to see new libraries emerging.
A couple of notes that may help:
Thanks again.
Sir i am trying to fetch all trending topic, and also trending topic by country, by country state so i read all your document. But i didn't found any function to get data like that. so please guide me to achieve my goal to use this package.
Hi !
I'm trying to implement the lib with my php app.
IT's a very basic one, using cron to automatically share my posts.
I have my credentials and my API, but I can't make the link between the credentials needed.
What I have :
What is needed by elephant is :
Thanks :) And sorry for the dumb quesiton ...
Describe the bug
I am using OAuth 2.0 Authentication, I need to send the tweet using the access_token authorized by the user. Because it is 2.0 oauth, I did not pass the parameters token_identifier and token_secret. In this case, I can upload the text version of the tweet normally. However, adding media with pictures or videos will prompt undefined token_identifier, but my tweet needs media, what should I do? thinks very.
Environment (please complete the following information):
linux
php version: 7.4
Bird Elephant version: 0.6.1
Additional context
My demand is that the user who passes auth2.0 authentication gets the access_token and uses the access_token to send tweets for the user. The tweets need to contain pictures or videos. What should I do? thanks
Describe the bug
when use user lookup with invalid username return
Undefined property: stdClass::$data from function getUserIdFromUsername
To Reproduce
$look = $users->lookup(['waelmahmoude111'], [ 'user.fields' => 'public_metrics', ]);
Expected behavior
return user or (null || exception )
Screenshots
Environment (please complete the following information):
Describe the bug
When calling $client->lists()->tweets()->lookup()
method with the max_results
param, it returns an inaccurate amount of tweets, it seems that the max_results
parameter doesn't account for the correct amount of tweets. When calling the $user->tweets($params);
call with max_results
, it works just fine.
To Reproduce
Use the following call:
$params = [
'expansions' => 'author_id,attachments.media_keys',
'max_results' => 7,
'tweet.fields' => 'attachments,author_id,context_annotations,created_at,entities,reply_settings,source,text,withheld,referenced_tweets',
'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,url,username,verified,withheld'
];
$tweets = $client->lists()->tweets()->lookup($list_id, $params);
Expected behavior
When inputting the max_results param to 7, I'd expect to see 7 tweets, but for some odd reason, it keeps returning less, when max_results isn't passed in, it returns all 100 by default.
Screenshots
https://i.ibb.co/BKgP7xH/Screen-Shot-2022-02-09-at-9-18-25-AM.png
Environment (please complete the following information):
I have a 'this used to work' problem π¬ (sorry!) I am using Laravel to automate a tweet.
$credentials = array(
'consumer_key' => env('TWITTER_CONSUMER_KEY'),
'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
'bearer_token' => env('TWITTER_BEARER_TOKEN'),
'auth_token' => $token,
);
$twitter = new BirdElephant($credentials);
$tweet = (new Tweet)->text($tweetText);
$tweetResult = $twitter->tweets()->tweet($tweet);
First, I started receiving 'Class "Coderjerk\BirdElephant\InvalidArgumentException" not found' when I tried to tweet. So to debug, I changed the following and then got the correct error message.
Coderjerk\BirdElephant\Request
throw new \InvalidArgumentException('A 1.0a token is required for this endpoint.');
But I feel like I should actually be doing a bearerTokenRequest
as I have successfully created an oAuth 2.0 auth_token. To test this I added $signed = false
to Coderjerk\BirdElephant\Request and it all worked correctly - tweet was tweeted πΎ
Coderjerk\BirdElephant\Request
$signed = false;
if ($signed === true && (empty($this->credentials['token_identifier']) || empty($this->credentials['token_secret']))) {
throw new \InvalidArgumentException('A 1.0a token is required for this endpoint.');
}
if ($signed === false && (isset($this->credentials['auth_token']) || isset($this->credentials['bearer_token'])) ) {
return $this->bearerTokenRequest(
$args,
$this->credentials['auth_token'] ?? $this->credentials['bearer_token']
);
}
If the problem is that I genuinely am supposed to only use oAuth 1.0a then I can't understand why this worked before and why it works fine if I hack it to force $signed to be false. Am I missing an argument or something that tells it I want to use oAuth 2.0?
Thank you π€ΈββοΈ
getSingleUserByID didn't work, user lookup just for username to find id.. nothing for id to find username?
Hi there, found a bug in Spaces when using getByUser()
method
Steps to reproduce the behavior:
./src/Spaces/SpacesLookup.php
$params['user_ids'] = [$id]
- should be a string, not an arrayDescribe the bug
In Coderjerk\BirdElephant\Request::authorisedRequest()
the code decides whether to use 2.0 or 1.0a-basd authentication by the $signed
property, which is passed along with each specific endpoint call. The problem this introduces is that it will try to use 2.0 token-based authentication even when you pass a 1.0a token/secret.
To Reproduce
$be = new BirdElephant([
'consumer_key' => [...],
'consumer_secret' => [...],
'token_identifier' => [...],
'token_secret' => [...],
]);
$be->user('shaneiseminger')->tweets();
This produces a 401 Unauthorized error. In debugging, I can see that an empty Authorization
header is passed instead of the OAuth1 headers.
Authorization: Bearer
Expected behavior
I would expect the library to decide the authorization style based on the tokens passed in the constructor, as tokens and authentication methods are not interchangeable.
Most 2.0 endpoints support 1.0a tokens, so it's not necessary to force a certain authentication style for certain endpoints. It would be totally fair to throw an exception if 1.0a tokens are used for an endpoint that does not support it.
Happy to provide a PR if you like.
Environment (please complete the following information):
Describe the bug
Calling the Tweets() constructor throws an error 8192: Creation of dynamic property Coderjerk\BirdElephant\Tweets::$lookup is deprecated.
File: vendor/coderjerk/bird-elephant/src/Tweets.php, line 26.
Environment (please complete the following information):
PHP 8.2.7
Bird Elephant version 0.7.0
Probably also applies to the other properties in the constructor (except for $credentials).
Describe the bug
Parse error: syntax error, unexpected '/', expecting ';' or ',
To Reproduce
Steps to reproduce the behavior:
I install the tool using the
composer require coderjerk/bird-elephant
I wanted to try the exemple
`use Coderjerk/BirdElephant/BirdElephant;
//your credentials, should be passed in via $_ENV or similar, don't hardcode.
$credentials = array(
'bearer_token' => xxxxxx,
'consumer_key' => xxxxxx,
'consumer_secret' => xxxxxx,
'token_identifier' => xxxxxx,
'token_secret' => xxxxxx,
);
//instantiate the object
$twitter = new BirdElephant($credentials);
//get a user's followers using the handy helper methods
$followers = $twitter->user('coderjerk')->followers();
//pass your query params to the methods directly
$following = $twitter->user('coderjerk')->following([
'max_results' => 20,
'user.fields' => 'profile_image_url'
]);
// You can also use the sub classes / methods directly if you like:
$user = new UserLookup($credentials);
$user = $user->getSingleUserByID('2244994945', null);I changed what should be change with my own bearer_token, secret keys .... But when I try the script I have this error message
Parse error: syntax error, unexpected '/', expecting ';' or ', it's in the first ligne meaning that it at the level of the
use `keyword.
Expected behavior
That the script show me the followrs in json
Environment (please complete the following information):
Additional context
I am noobs, I am prety sure I did somthing wrong and I am sorry to bother you but really need some help
Describe the bug
Tried everything on this one (and possibly ive missed something) but keep getting a member function error on recents, tried using oath 1 and 2 (although i know this is an auth 2 call). Poked around the src functions but couldnt find anything, other functions that i can use seem to work ok in that function.
Fatal error: Uncaught Error: Call to a member function recent() on null
function array is set as expected
To Reproduce
Steps to reproduce the behavior:
$twitter = new BirdElephant($credentials);
$params = array('query' => 'a', 'max_results' => 5);
$tweets->search->recent($params);
Expected behavior
returns a list of tweets
Environment (please complete the following information):
Additional context
validated all generated keys with other function contexts (and seems to be working ok elsewhere)
Right now there is no option to send direct messages via Twitter API using bird-elephant. If you could add this option to send direct messages that would be helpful for the users.
Describe the bug
While sending a dm to a particular user without attachments I am getting the below error.
stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[parameters] => stdClass Object
(
[$.attachments] => Array
(
[0] => null
)
)
[message] => $.attachments: null found, array expected
)
)
[title] => Invalid Request
[detail] => One or more parameters to your request was invalid.
[type] => https://api.twitter.com/2/problems/invalid-request
)
this is because attachments are sent to Twitter by default even if we send just DM.
coderjerk\bird-elephant\src\Compose\DirectMessage.php
in this above class attachments variable from line 8 is declared as a string. Declaring this as an array worked for me.
I think that is the issue. Please debug and fix the issue.
To Reproduce
$twitter = new BirdElephant(['bearer_token' => $res['bearer_token'],
'consumer_key' => $res['consumer_key'],'consumer_secret' => $res['consumer_secret'],'token_identifier' => $res['access_key'],'token_secret' => $res['access_secret']]);
$dms = $twitter->directMessages();
$dm = (new \Coderjerk\BirdElephant\Compose\DirectMessage)->text('Hello Buddy');
// echo "<pre>";print_r($dm);exit;
$res = $dms->message($dm)->sendTo('madforcryptos_');
echo "<pre>";print_r($res);exit;
Environment (please complete the following information):
Can a video be uploaded and attached to tweets? Via
$twitter->tweets()->upload ('./img/video.mp4');
Or any other ways to achieve this?
Is your feature request related to a problem? Please describe.
The library automatically fetches the user ID for a given username, which slows things down and burns an extra request. And when I do things like this:
$be->user('shaneiseminger')->tweets();
it actually fires two successive requests for the user ID:
Coderjerk\BirdElephant\User
instantiates several classes in the constructor.Coderjerk\BirdElephant\Users\Bookmarks
fetches the user ID in the constructor.Coderjerk\BirdElephant\Tweets
fetches it again for the tweets()
method.Describe the solution you'd like
I think it's common to store user metadata with an access token. We certainly do. So it would be helpful to avoid those extra requests and by passing the user ID like so:
$be->user('shaneiseminger', 12345)->tweets();
You would need to solve the duplicate-request bug, because it stems from the fact that individual classes do not share user IDs, therefore each has to retrieve it separately. For the above solution to work, there would need to be some kind of common storage.
Describe alternatives you've considered
The simplest would be to pass the user ID as a third argument to the constructor of each class that requires a username, though that doesn't allow us to fetch it on-demand and still share it with all other classes. So I suggest:
class UserIdLookup extends ApiBase {
private static array $userIdCache = [];
public function __invoke(string $username)
{
if (empty(self::$userIdCache[$username]) {
self::$userIdCache[$username] = $this->getUserId($username);
}
return self::$userIdCache[$username];
}
}
Usage:
$userIdLookup = new UserIdLookup('screenname');
$userId = $userIdLookup();
Happy to submit a PR.
Hey!
When making requests to the Twitter API, they return headers as described here:
https://developer.twitter.com/en/docs/twitter-api/rate-limits
Note that the HTTP headers are contextual. When using application-only authentication, they indicate the rate limit for the application context. When using user-based authentication, they indicate the rate limit for that user context.
x-rate-limit-limit:
the rate limit ceiling for that given endpoint
x-rate-limit-remaining:
the number of requests left for the 15-minute window
x-rate-limit-reset:
the remaining window before the rate limit resets, in UTC epoch seconds
From what I understand, it's not possible to get these headers using BirdElephant, is that correct?
Thank you very much π
Please help ... Soon i ll be sponsoring this project
print_r($tweets->get('1554443467065118725'));
above request is returning me truncated tweet ?
Sharing as Text works, but I couldn't send a tweet with Media. I also did the validation for v1.1. Even when uploading the chris.png file in the file, I get an error like image formats. I don't quite understand. Is there a sample tweet code blog with an example image?
Iget Uncaught GuzzleHttp\Exception\ClientException error.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.