Code Monkey home page Code Monkey logo

codebird-js's Introduction

codebird-js

A Twitter library in JavaScript.

Copyright (C) 2010-2018 Jublo Limited [email protected]

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

Travis Status

Including Codebird

To include Codebird in your code, add its scripts to your markup:

<script type="text/javascript" src="codebird.js"></script>

<script type="text/javascript">
var cb = new Codebird;
cb.setConsumerKey("YOURKEY", "YOURSECRET");
</script>

You may also use a JavaScript module loader of your choice (such as RequireJS or the one bundled in Node.js) to load Codebird unobtrusively. In Node.js, loading Codebird looks like this:

var Codebird = require("codebird");
// or with leading "./", if the codebird.js file is in your main folder:
// var Codebird = require("./codebird");

var cb = new Codebird();
cb.setConsumerKey("YOURKEY", "YOURSECRET");

Authentication

To authenticate your API requests on behalf of a certain Twitter user (following OAuth 1.0a), take a look at these steps:

<script type="text/javascript" src="codebird.js"></script>

<script type="text/javascript">
var cb = new Codebird;
cb.setConsumerKey("YOURKEY", "YOURSECRET");
</script>

You may either set the OAuth token and secret, if you already have them:

cb.setToken("YOURTOKEN", "YOURTOKENSECRET");

Or you authenticate, like this:

// gets a request token
cb.__call("oauth_requestToken", { oauth_callback: "oob" }, function(
  reply,
  rate,
  err
) {
  if (err) {
    console.log("error response or timeout exceeded" + err.error);
  }
  if (reply) {
    if (reply.errors && reply.errors["415"]) {
      // check your callback URL
      console.log(reply.errors["415"]);
      return;
    }

    // stores the token
    cb.setToken(reply.oauth_token, reply.oauth_token_secret);

    // gets the authorize screen URL
    cb.__call("oauth_authorize", {}, function(auth_url) {
      window.codebird_auth = window.open(auth_url);
    });
  }
});

⚠️ Codebird server calls do not always go through when being processed in a hyperlink onclick handler. Be sure to cancel the default procedure before calling Codebird, like this (jQuery):

$(function() {

    $('#auth').click(function(e) {
        e.preventDefault();

        var cb = new Codebird;
// ...

Now you need to add a PIN box to your website. After the user enters the PIN, complete the authentication:

cb.__call(
  "oauth_accessToken",
  { oauth_verifier: document.getElementById("PINFIELD").value },
  function(reply, rate, err) {
    if (err) {
      console.log("error response or timeout exceeded" + err.error);
    }
    if (reply) {
      // store the authenticated token, which may be different from the request token (!)
      cb.setToken(reply.oauth_token, reply.oauth_token_secret);
    }

    // if you need to persist the login after page reload,
    // consider storing the token in a cookie or HTML5 local storage
  }
);

Logging out

In case you want to log out the current user (to log in a different user without creating a new Codebird object), just call the logout() method.

cb.logout().then(() => {
  // user is now logged out
});

Codebird also supports calling the oauth/invalidate_token method directly:

cb.__call("oauth_invalidateToken", {
  access_key:        "1234",
  access_key_secret: "5678"
}).then(() => {
  // tokens are now reset
});

Application-only auth

Some API methods also support authenticating on a per-application level. This is useful for getting data that are not directly related to a specific Twitter user, but generic to the Twitter ecosystem (such as search/tweets).

To obtain an app-only bearer token, call the appropriate API:

cb.__call("oauth2_token", {}, function(reply, err) {
  var bearer_token;
  if (err) {
    console.log("error response or timeout exceeded" + err.error);
  }
  if (reply) {
    bearer_token = reply.access_token;
  }
});

I strongly recommend that you store the obtained bearer token in your database. There is no need to re-obtain the token with each page load, as it becomes invalid only when you call the oauth2/invalidate_token method.

If you already have your token, tell Codebird to use it:

cb.setBearerToken("YOURBEARERTOKEN");

In this case, you don't need to set the consumer key and secret. For sending an API request with app-only auth, see the ‘Usage examples’ section.

Authenticating using a callback URL, without PIN

  1. Before sending your user off to Twitter, you have to store the request token and its secret, for example in a cookie.
  2. In the callback URL, extract those values and assign them to the Codebird object.
  3. Extract the oauth_verifier field from the request URI.

In Javascript, try extracting the URL parameter like this:

var cb = new Codebird();
var current_url = location.toString();
var query = current_url.match(/\?(.+)$/).split("&amp;");
var parameters = {};
var parameter;

cb.setConsumerKey("STUFF", "HERE");

for (var i = 0; i < query.length; i++) {
  parameter = query[i].split("=");
  if (parameter.length === 1) {
    parameter[1] = "";
  }
  parameters[decodeURIComponent(parameter[0])] = decodeURIComponent(
    parameter[1]
  );
}

// check if oauth_verifier is set
if (typeof parameters.oauth_verifier !== "undefined") {
  // assign stored request token parameters to codebird here
  // ...
  cb.setToken(
    stored_somewhere.oauth_token,
    stored_somewhere.oauth_token_secret
  );

  cb.__call(
    "oauth_accessToken",
    {
      oauth_verifier: parameters.oauth_verifier
    },
    function(reply, rate, err) {
      if (err) {
        console.log("error response or timeout exceeded" + err.error);
      }
      if (reply) {
        cb.setToken(reply.oauth_token, reply.oauth_token_secret);
      }

      // if you need to persist the login after page reload,
      // consider storing the token in a cookie or HTML5 local storage
    }
  );
}

Usage examples

⚠️ Because the Consumer Key and Token Secret are available in the code, it is important that you configure your app as read-only at Twitter, unless you are sure to know what you are doing.

When you have an access token, calling the API is simple:

cb.setToken("YOURTOKEN", "YOURTOKENSECRET"); // see above

cb.__call("statuses_homeTimeline", {}, function(reply, rate, err) {
  console.log(reply);
  console.log(err);
});

Tweeting is as easy as this:

cb.__call("statuses_update", { status: "Whohoo, I just tweeted!" }, function(
  reply,
  rate,
  err
) {
  // ...
});

⚠️ Make sure to urlencode any parameter values that contain query-reserved characters, like tweeting the & sign:

var params = "status=" + encodeURIComponent("Fish & chips");
cb.__call("statuses_update", params, function(reply, rate, err) {
  // ...
});

In most cases, giving all parameters in an array is easier, because no encoding is needed:

var params = {
  status: "Fish & chips"
};
cb.__call("statuses_update", params, function(reply, rate, err) {
  // ...
});
var params = {
  screen_name: "jublonet"
};
cb.__call("users_show", params, function(reply, rate, err) {
  // ...
});
var params = {
  q: "NYC"
};
cb.__call("search_tweets", params, function(reply) {
  // ...
});

Uploading media to Twitter

Tweet media can be uploaded in a 2-step process, and the media have to be base64-encoded. First you send each image to Twitter, like this:

var params = {
    "media_data": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAB+0lEQVR42mP8//8/Ay0BEwONwagFoxZQDljI0PP8x7/Z93/e+PxXmpMpXp5dh4+ZgYHh0bd/clxYnMuINaMtfvRLgp3RVZwVU+rkuz+eRz+//wXVxcrEkKnEceXTX0dRlhoNTmKDaOvzXwHHv6x9+gtN/M9/hpjTX+GmMzAw/P7HMOnOj+ff//35x/Ds+z9iLfjPwPDt7//QE1/Sz319/RNh3PkPf+58+Yup/t7Xf9p8zFKcTMRa4CLGCrFm1v2fSjs+pJ/7uuvl7w+//yO7HRkUq3GEyrCREMk+kqy2IiyH3/xhYGD48uf/rPs/Z93/yczIwM3CiFU9Hw5xnD4ouvTt4Tf0AP37n+HTb+w+UOBmIs2CICm2R9/+EZlqGRkYzIVYSLMgRIYtUYGdSAsMBFgUuJhIy2iMDAwt2pysjAwLHv78RcgnOcrs5BQVHEyMG579Imi6Nh9zrBxZFgixMW624pXnwldYcTAzLjDhZmUit7AzE2K54c7fp8eF1QhWRobFptwmgiwkF3b//jMwMjJ8+P3/zPs/yx/9Wvr412+MgBJlZ1xsyuOOrbAibMHH3/87b32fce/nR2ypnpuFMVGevU6TQ5SdqKKeEVez5cuf/7te/j727s+9L/++/v3PzcyowM1kIcTiLs7Kz8pIfNnOONouGrVg1AIGAJ6gvN4J6V9GAAAAAElFTkSuQmCC"
);
cb.__call(
    "media_upload",
    params,
    function (reply, rate, err) {
        // you get a media id back:
        console.log(reply.media_id_string);

        // continue upload of 2nd image here, if any (just 1 image works, too!)
    }
);

Second, you attach the collected media ids for all images to your call to statuses/update, like this:

cb.__call(
    "statuses_update",
    {
        "media_ids": "12345678901234567890,9876543210987654321"
        "status": "Whohoo, I just tweeted two images!"
    },
    function (reply, rate, err) {
        // ...
    }
);

More documentation for uploading media is available on the Twitter Developer site.

Requests with app-only auth

To send API requests without an access token for a user (app-only auth), add another parameter to your method call, like this:

cb.__call(
  "search_tweets",
  "q=Twitter",
  function(reply) {
    // ...
  },
  true // this parameter required
);

Bear in mind that not all API methods support application-only auth.

Mapping API methods to Codebird function calls

As you can see from the last example, there is a general way how Twitter’s API methods map to Codebird function calls. The general rules are:

  1. For each slash in a Twitter API method, use an underscore in the Codebird function.

    Example: statuses/update maps to cb.__call("statuses_update", ...).

  2. For each underscore in a Twitter API method, use camelCase in the Codebird function.

    Example: statuses/home_timeline maps to cb.__call("statuses_homeTimeline", ...).

  3. For each parameter template in method, use UPPERCASE in the Codebird function. Also don’t forget to include the parameter in your parameter list.

    Examples:

    • statuses/show/:id maps to cb.__call("statuses_show_ID", 'id=12345', ...).
    • users/profile_image/:screen_name maps to cb.__call("users_profileImage_SCREEN_NAME", "screen_name=jublonet", ...).

HTTP methods (GET, POST, DELETE etc.)

Never care about which HTTP method (verb) to use when calling a Twitter API. Codebird is intelligent enough to find out on its own.

Response codes

The HTTP response code that the API gave is included in any return values. You can find it within the return object’s httpstatus property.

Dealing with rate-limits

Basically, Codebird leaves it up to you to handle Twitter’s rate limit. The library returns the response HTTP status code, so you can detect rate limits.

I suggest you to check if the reply.httpstatus property is 400 and check with the Twitter API to find out if you are currently being rate-limited. See the Rate Limiting FAQ for more information.

If you allow your callback function to accept a second parameter, you will receive rate-limiting details in this parameter, if the Twitter API responds with rate-limiting HTTP headers.

cb.__call("search_tweets", "q=Twitter", function(reply, rate_limit_status) {
  console.log(rate_limit_status);
  // ...
});

API calls and the same-origin policy

Normally, browsers only allow requests being sent to addresses that are on the same base domain. This is a security feature called the “same-origin policy.” However, this policy is in your way when you try to access the (remote) Twitter API domain and its methods.

Cross-domain requests

With Codebird, don’t worry about this. We automatically send cross-domain requests using a secured proxy that sends back the required headers to the user’s browser.

This CORS proxy is using an encrypted SSL connection. We do not record data sent to or from the Twitter API. Using Codebird’s CORS proxy is subject to the Acceptable use policy.

If your JavaScript environment is not restricted under the same-origin policy (for example in node.js), direct connections to the Twitter API are established automatically, instead of contacting the CORS proxy.

You may also turn off the CORS compatibility manually like this:

cb.setUseProxy(false);

Support for Internet Explorer 7 to 9

Cross-domain requests work well in any browser except for Internet Explorer 7-9. Codebird cannot send POST requests in these browsers. For IE7-9, Codebird works in limited operation mode:

  • Calls to GET methods work fine,
  • calling POST methods is impossible,
  • Application-only auth does not work.

Using your own proxy server

The source code of the CORS proxy is publicly available. If you want to, set up your own instance on your server. Afterwards, tell Codebird the address:

cb.setProxy("https://example.com/codebird-cors-proxy/");

Heads up! Follow the notes in the codebird-cors-proxy README for details.

Using multiple Codebird instances

By default, each Codebird instance works on its own.

If you need to run requests to the Twitter API for multiple users at once, Codebird supports this automatically. Just create a new object:

var cb1 = new Codebird();
var cb2 = new Codebird();

Please note that your OAuth consumer key and secret is shared within multiple Codebird instances, while the OAuth request and access tokens with their secrets are not shared.

How Do I…?

…get user ID, screen name and more details about the current user?

When the user returns from the authentication screen, you need to trade the obtained request token for an access token, using the OAuth verifier. As discussed in the section ‘Usage example,’ you use a call to oauth/access_token to do that.

The API reply to this method call tells you details about the user that just logged in. These details contain the user ID and the screen name.

Take a look at the returned data as follows:

{
    oauth_token: "14648265-rPn8EJwfB**********************",
    oauth_token_secret: "agvf3L3**************************",
    user_id: 14648265,
    screen_name: "jublonet",
    httpstatus: 200
}

If you need to get more details, such as the user’s latest tweet, you should fetch the complete User Entity. The simplest way to get the user entity of the currently authenticated user is to use the account/verify_credentials API method. In Codebird, it works like this:

cb.__call("account_verifyCredentials", {}, function(reply) {
  console.log(reply);
});

I suggest to cache the User Entity after obtaining it, as the account/verify_credentials method is rate-limited by 15 calls per 15 minutes.

…walk through cursored results?

The Twitter REST API utilizes a technique called ‘cursoring’ to paginate large result sets. Cursoring separates results into pages of no more than 5000 results at a time, and provides a means to move backwards and forwards through these pages.

Here is how you can walk through cursored results with Codebird.

  1. Get the first result set of a cursored method:
cb.__call("followers_list", {}, function(result1) {
  // ...
});
  1. To navigate forth, take the next_cursor_str:
var nextCursor = result1.next_cursor_str;
  1. If nextCursor is not 0, use this cursor to request the next result page:
if (nextCursor > 0) {
  cb.__call("followers_list", { cursor: nextCursor }, function(result2) {
    // ...
  });
}

To navigate back instead of forth, use the field resultX.previous_cursor_str instead of next_cursor_str.

It might make sense to use the cursors in a loop. Watch out, though, not to send more than the allowed number of requests to followers/list per rate-limit timeframe, or else you will hit your rate-limit.

…use xAuth with Codebird?

Codebird supports xAuth just like every other authentication used at Twitter. Remember that your application needs to be whitelisted to be able to use xAuth.

Here’s an example:

cb.__call(
  "oauth_accessToken",
  {
    x_auth_username: "username",
    x_auth_password: "4h3_p4$$w0rd",
    x_auth_mode: "client_auth"
  },
  function(reply) {
    console.log(reply);
    // ...
  }
);

If everything went fine, you will get an object like this:

{
    "oauth_token": "14648265-ABLfBFlE*********************************",
    "oauth_token_secret": "9yTBY3pEfj*********************************",
    "user_id": "14648265",
    "screen_name": "jublonet",
    "x_auth_expires": "0",
    "httpstatus": 200
}

Are you getting a strange error message, an empty error, or status "0"? If the user is enrolled in login verification, the server will return a HTTP 401 error with a custom body (that may be filtered by your browser).

You may check the browser web console for an error message.

When this error occurs, advise the user to generate a temporary password on twitter.com and use that to complete signing in to the application.

…access the Collections API?

Collections are a type of timeline that you control and can be hand curated and/or programmed using an API.

Pay close attention to the differences in how collections are presented — often they will be decomposed, efficient objects with information about users, Tweets, and timelines grouped, simplified, and stripped of unnecessary repetition.

Never care about the OAuth signing specialities and the JSON POST body for POST and PUT calls to these special APIs. Codebird takes off the work for you and will always send the correct Content-Type automatically.

Find out more about the Collections API in the Twitter API docs. More information on the Direct Messages API and the Account Activity API is available there as well.

Here’s a sample for adding a Tweet using the Collections API:

cb.__call(
  "collections_entries_curate",
  {
    id: "custom-672852634622144512",
    changes: [{ op: "add", tweet_id: "672727928262828032" }]
  },
  function(reply, rate) {
    document.body.innerText = JSON.stringify(reply);
  }
);

…use promises instead of callback functions?

Have you ever heard of the Pyramid of Doom? It’s when code progresses more to the right because of excessive nesting than it progresses from top to bottom.

Because of the asynchronous requests, Codebird will use callbacks that you provide. They are called when the result from the Twitter API has arrived. However, to streamline code, there is a sleeker concept for this: Promises.

There are several popular libraries that support promises. Codebird will auto-detect and use any of the following:

  • jQuery Deferred
  • Q
  • RSVP
  • when

Here’s a usage sample for promises:

cb.__call("statuses_update", { status: "Whohoo, I just tweeted!" }).then(
  function(data) {
    var reply = data.reply,
      rate = data.rate;
    // ...
  },
  function(err) {
    // ...
  }
);

Since the app-only flag is the fourth parameter for __call, you’ll have to provide a callback stub nonetheless even with promises:

cb.__call(
  "search_tweets",
  { q: "#PHP7" },
  null, // no callback needed, we have the promise
  true // app-only auth
).then(
  function(data) {
    var reply = data.reply,
      rate = data.rate;
    // ...
  },
  function(err) {
    // ...
  }
);

Tips:

  • If you provide both (callback and promise.then), Codebird will first call the callback, then resolve the promise.

  • If the request fails due to any errors, Codebird will reject the promise.

codebird-js's People

Contributors

aguardientico avatar benfoxall avatar davei234 avatar digital11 avatar hamzaezzi avatar kiss avatar mynetx avatar niklasberglund avatar osnr avatar shabin-slr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codebird-js's Issues

Popup Blocked for Pin window

Hi Everyone,

This is not a bug as the code and codebird script are working fine, but I've noticed that the popup when requesting Twitter's pin is blocked by Chrome and IE, as this is a callback call from the login button clicked and not a direct call from the login button. Is there a way to avoid this popup to be blocked?

Here's basically my code:

In HTML:
A button calling Tlog() onclick.

In JS:
Tlog = function () {

// gets a request token
cb.__call("oauth_requestToken", {
    oauth_callback: "oob"
}, function (reply) {

    cb.setToken(reply.oauth_token, reply.oauth_token_secret);

    // gets the authorize screen URL
    cb.__call("oauth_authorize", {}, function (auth_url) {
        //HERE'S THE POPUP BLOCKED
        window.codebird_auth = window.open(auth_url);
        $('#TLogin').hide();
        $('#TPinField').prepend('<p>Enter the PIN received from Twitter and click on "Validate PIN"</p>');
        $('#TPinField').show();
        $('#TPinButton').show();
    });
});

}

I would appreciate any advice.
Thanks and a great day.

Walter

Not all Rest Commands implemented?

Hello and thank you for your work.

Trying to favorite a post does NOT work:

cb.__call("favorites_create", {
"id": "362614359207329800"
}, function (reply) {
console.log('Favorite response')
console.log(reply);
});

Returns error message:
https://api.jublo.net/codebird/1.1/favorites/create.json
Object {errors: Array[1], httpstatus: 404}
errors: Array[1]
0: Object
code: 34
message: "Sorry, that page does not exist"
proto: Object
length: 1
proto: Array[0]
httpstatus: 404

Am I missing something? or you will implement this later?
Thanks and regards,

Walter

Jublo.net Proxy down?

Unable to connect to the proxy this morning.
Someone else meets this problem?

Thanks,
Walter

Don’t use proxy for non-browser environments

The CORS proxy should only be used for browsers that have the same-origin policy. Node.js and other non-browser environments (any that do not define the navigator object) should use direct connection to the API.

detectMultipart is broken

Due to the "rudimentary" comparison mechanism, detectMultipart returns true for status/update for example. I would suggest simply creating an object with the method calls as keys, and checking later if a given key exists.

JSHint validation

Codebird.js should pass JSHint validation, as prove for high-quality code.

status_userTimeline doesnt work? Is this a bug ?

This code should work:

var params = {
screen_name: "twitter"
};

cb.__call(
"statuses_userTimeline",params,
{},
function (data) {
console.log(data);

}

But i dont get any error messages and the request is empty.

update media

Hey guys,

what could be the problem when trying "statuses_updateWithMedia". I get

The requested URL /codebird/1.1/statuses/update_with_media.json was not found on this server. "httpstatus":404}

Typo in _clone function

When defining the function _clone(obj) , line 806 has (what I believe is) a recursive call to the same function in the event that the data member of the object being clone is itself an object.
I believe that that there is a typo bug on line 806, instead of having a _clone(obj) function call, line 806 has a call to clone(obj). PLEASE NOTE the absence of the underscore( _ ) .
clone() function is NOT DEFINED anywhere in codebird.js .

At present code.js works fine but I believe this typo bug will cause future problems in the event that a recursive call is ever made by the code in line 806

Add unit testing suite

Codebird should contain a test suite for finding regressions and hidden bugs. The test suite should run in the browser, for example via Jasmine.

Support internal API methods

In addition to the API methods publicly documented, the Twitter API also supports undocumented API methods, often for use by internal or official apps. Codebird may support them (or part of them).

Allow to assign custom proxy address

"Error 405 - Method not allowed" allow to specify method customly

When I use cb.setUseProxy(false) I recieve "HTTP/1.1 405 Method Not Allowed", when I have look at request it was "OPTIONS /oauth/request_token HTTP/1.1", but I need "POST /oauth/request_token HTTP/1.1". In documentation there are no words about how to specify method customly.

Integrate sha1 hash library

To avoid external dependencies and not-included helper files, the hashing function SHA1 should be integrated into Codebird itself, instead of a separate file sha1.js.

Application-only auth not working on Internet Explorer (All versions)

Hi guys,

Thanks for your great library! I am having an issue with Internet Explorer while trying to get application-only auth:

cb = new Codebird();
cb.setConsumerKey('key', 'secret');
cb.__call('oauth2_token', {}, function(reply) {
    console.log(reply)
});

Result: Access denied

On some old versions of Internet Explorer the dev tools direct me towards the line 485 of the library:

var xml;
try {
  xml = new XMLHttpRequest();
} catch (e) {
  xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.open("POST", url, true);

I thought it might be related to the following: http://stackoverflow.com/questions/5087549/access-denied-to-jquery-script-on-ie
Do you have any suggestions? Thanks a lot for your help!

Can't post a tweet.


function twLogin() {
  cb.setConsumerKey("KEY", "SECRET");
  var id;
  // check if we already have access tokens
  if(localStorage.accessToken && localStorage.tokenSecret) {
    // then directly setToken() and read the timeline
    cb.setToken(localStorage.accessToken, localStorage.tokenSecret);
    // now poll periodically and send an auto-reply when we are mentioned.
    //fetchTweets(id);
  } else { // authorize the user and ask her to get the pin.
    cb.__call(
      "oauth_requestToken",
          {oauth_callback: "http://www.neilmarion.com"},
          function (reply) {
          // nailed it!
              console.log(reply);
              cb.setToken(reply.oauth_token, reply.oauth_token_secret);
              cb.__call(
              "oauth_authorize",  {},
              function (auth_url) {
                var ref = window.open(auth_url, '_blank', 'location=no'); // redirection.
                // check if the location the phonegap changes to matches our callback url or not
                ref.addEventListener("loadstart", function(iABObject) {
                  if(iABObject.url.match(/neilmarion/)) {
                    ref.close();
                    authorize(iABObject);
                  }
                });
              }
        );
          }
    );
  }
}

function twTweetLink(fileName) { // not a photo upload. Just merely a tweeting of a public link
  var url = "http://www.testphotorestapi.neilmarion.com/avatars/"+fileName;

  cb.__call("statuses_update",
    {"status": "This is a test. " + url}, function (reply) {
      console.log(reply);
  });
}

Whenever I call twLogin, the user seems to be authenticated properly - a inAppBrowser pops up that shows the "authenticate" app form. But I'm trying to call twTweetPhoto, nothing's happening. No tweet being updated in my feed.

What could be the problem here?

Support AMD module definition syntax

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded. This is particularly well suited for the browser environment where synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems.

Codebird should support getting loaded either as vanilla file or as an AMD module.

statuses_userTimeline returning error "Failed to load resource https://api.jublo.net/codebird/1.1/statuses/user_timeline.json?screen_name=adityapratap270&count=20

statuses_userTimeline returning error "Failed to load resource https://api.jublo.net/codebird/1.1/statuses/user_timeline.json?screen_name=adityapratap270&count=20

Also I tried

objTwitterCB.__call(
"oauth_requestToken",
{oauth_callback: "oob"},
function (reply) {
// stores it
objTwitterCB.setToken(reply.oauth_token, reply.oauth_token_secret);
console.log(reply);
// gets the authorize screen URL
objTwitterCB.__call(
"oauth_authorize",
{},
function (auth_url) {
window.codebird_auth = window.open(auth_url);
}
);
}
);

It returned an error 👎
Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

OPTIONS error ???

What does this error mean? I do not use a proxy. It is a completely JavaScript based tool I am developing and I don't want to use PHP. Thank you

OPTIONS https://api.jublo.net/codebird/oauth2/token codebird.js:516
oauth2_token codebird.js:516
_callApi codebird.js:1184
(anonymous function) codebird.js:1185
xml.onreadystatechange

Better Documentation

I would prefer a better documentation, also with completet but easy programming examples, like an easy website for a twitter stream of an user and with example tokens. So that everybody can copy&paste this website, replace the tokens and then run the website.

cb.setProxy(false) leads to error page on twitter

Running this from Win7 desktop Firefox 27.0.1 code is here:

Copied and pasted the code from codebird.js so last revision https://github.com/jublonet/codebird-js/blob/3b9dddee624fc07934685ad6b5084ead802ca299/codebird.js

var cb = new Codebird;
cb.setConsumerKey("AjONvgAdbD8YWCtRn5U9yA", "jrcJKxvJ92NeeV48RL1lotN9PigbxCCbqUkKj237yio");
cb.setUseProxy(false);


// gets a request token
cb.__call(
    "oauth_requestToken",
    {oauth_callback: "oob"},
    function (reply) {
        // stores it
        cb.setToken(reply.oauth_token, reply.oauth_token_secret);

        // gets the authorize screen URL
        cb.__call(
            "oauth_authorize",
            {},
            function (auth_url) {
                window.codebird_auth = window.open(auth_url);
            }
        );
    }
);

Instead of the authorize page it leads you to a twitter page saying

Whoa there!

There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

invalid or expired token code 89

Hi all
I have using codebird.js 2.4.3 . I login authentical ok but when I statuses_update show error invalid or expired token code 89 . this my code
var cb = new Codebird;
function loginTwitter(){
cb.setConsumerKey(mykey, mysecret);
cb.__call(
"oauth_requestToken",
{},
function (reply) {
// stores it
token = reply.oauth_token;
token_secret=reply.oauth_token_secret;
cb.setToken(token, token_secret);

                // gets the authorize screen URL
                cb.__call(
                    "oauth_authorize",
                    {},
                    function (auth_url) {
                        window.codebird_auth = window.open(auth_url);
                    }
                );

            }
        );
}
function tweet(){
    var msg= $("#Tweetwall").val();
    cb.setConsumerKey(mykey, mysecret);
     cb.setToken(token,token_secret);

    // alert(token.trim());
    // alert(token_secret);
    // alert(msg);
    cb.__call(
            "statuses_update",
            {"status": msg},
            function (reply) {
                //alert(enumerateObject(reply.errors[0]));
            //   alert("tweet to wall");
            }
        );
}

please relpy help me. thank

Support streaming API

Streaming API. That means, you call the API server once and get back a continuous stream of data, running as long as you wish. Unfortunately, web browsers today do not fully support the necessary WebSockets API, as you can see on this graph.

Access api.twitter.com directly, bypassing the proxy

I guess may of you today started experiencing problems with Codebird due to the fact that the proxy, api.jublo.net, is down.

Is there a way to point the library directly to the twitter.com servers and avoid the proxy altogether?

statuses/destroy/:id auth?

I am trying to destroy a status using statuses/destroy/:id (statuses_destroy_ID also using id_str as the id). I consistently receive a 403 with the message of "{"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]}". I have read and write access set up for my app.

I am able to successfully retrieve the timeline and update the status.

I noticed that the successful status update is using OAuth for x-authorization where as the 403'd status destroy is using Bearer as the x-authorization.

I am running @Version 2.3.3.

By the way, thank you for your work on this great library!

Places & Geo API call issue

Codebird doesn't recognize the palce_id paramter.
Following the documentation to access geo/id/:place_id
We should call geo_id_PLACE_ID
But it is translated into geo/id/:place/_i_d

Call to users_lookup in IE7-9 get JS error

i have an issue with ie7-9. i do an authentication server side and when i make a call to 'users_lookup' i get a js error: SCRIPT1004: Expected ';' on returned json. it might be a Twitter issue, but may be someone else have found a solution. unfortunately i have to use ie.

it works fine with other api calls (friends_ids)

statuses/show:id not working

I'm fairly new to the Twitter API 1.1, so this could be the wrong solution to the problem.

When trying to call 'statuses_show', I was getting the error "Uncaught ReferenceError: c is not defined " meaning that httpmethod was not in the array httpmethods['GET'].

I tried using the parameter "statuses_show_:id" to satisfy the httpmethods array in the plugin (line 800), but then I was getting Code 34 (Sorry, that page does not exist) from Twitter. This was because the url the plugin was generating was: https://api.jublo.net/codebird/1.1/statuses/show/:id.json?id=333746084075692032 and according to the API docs, ":id" shouldn't be included in the url.

However, if I changed 'statuses/show/:id' to 'statuses/show/' (just removed ":id") that fixed the problem.

I'm thinking that the ":id" shouldn't be in any of the array items at all.

Thanks for this plugin! It makes API calls so much easier! Just had this one little issue.

Simple Authenticacion snippet code

Hi!

I have been trying to use the library but I could not...

Can someone provide me a simple Twitter authentication code please?? I always receive a 401 ERROR...

Thank you very much!

Don't force to send base64 media uploads via proxy

@kurrik wrote:

We just rolled out an update which supports [base64-encoding the JavaScript media multipart]. Can you test again and confirm that the JS version works now?

Sending media uploads via base64, without forcing proxy, should be enabled in codebirs-js now.

Add xAuth docs to README

Codebird supports authenticating via OAuth and xAuth. The README should contain a section about xAuth. Can be adopted from codebird-php.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.