• Stars
    star
    411
  • Rank 105,247 (Top 3 %)
  • Language
    Elixir
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Twitter client library for elixir.

ExTwitter

CI Coverage Status Module Version Hex Docs Total Download License Last Updated

Twitter client library for Elixir. It uses OAuther to call Twitter's REST API v1.1.

It only supports very limited set of functions yet. Refer to lib/extwitter.ex and test/extwitter_test.exs for available functions and examples.

Installation

The package can be installed by adding :extwitter to your list of dependencies in mix.exs:

By default, ExTwitter uses OAuther and Jason library to call Twitter's REST API.

defp deps do
  [
    {:oauther, "~> 1.1"},
    {:jason, "~> 1.1"},
    {:extwitter, "~> 0.12"}
  ]
end

Configuration

Refer to Twitter API doc for the detail.

The default behaviour is to configure using the application environment:

In config/config.exs, add:

config :extwitter, :oauth, [
   consumer_key: "",
   consumer_secret: "",
   access_token: "",
   access_token_secret: ""
]

Or manually at runtime through ExTwitter.configure/1:

iex> ExTwitter.configure([consumer_key: "", ...])

You can also configure the current process only:

iex> ExTwitter.configure(:process, [consumer_key: "", ...])

You can also customize it to use another library via the :json_library configuration:

config :extwitter, :json_library, Poison

Proxy for accessing twitter server can be configured as follows:

config :extwitter, :proxy, [
   server: "www-proxy.mycompany.com",
   port: 8000,
   user: "user",
   password: "password"
]

Usage

Sample execution on IEx.

Setup and configuration

$ iex -S mix
Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)
ExTwitter.configure(
   consumer_key: System.get_env("TWITTER_CONSUMER_KEY"),
   consumer_secret: System.get_env("TWITTER_CONSUMER_SECRET"),
   access_token: System.get_env("TWITTER_ACCESS_TOKEN"),
   access_token_secret: System.get_env("TWITTER_ACCESS_SECRET")
 )

Authentication / Authorization

Example for authentication (Sign-in with twitter).

Authorization (3-legged authorization) uses the same workflow, just swap :authenticate_url for :authorize_url where indicated.

# Request twitter for a new token
token = ExTwitter.request_token("http://myapp.com/twitter-callback")

# Generate the url for "Sign-in with twitter".
# For "3-legged authorization" use ExTwitter.authorize_url instead
{:ok, authenticate_url} = ExTwitter.authenticate_url(token.oauth_token)

# Copy the url, paste it in your browser and authenticate
IO.puts authenticate_url

After sign-in you will be redirected to the callback URL you configured for your app. Get the tokens from the URL's query:

https://myapp.com/twitter-callback?oauth_token=<TOKEN>&oauth_verifier=<VERIFIER>

Copy the oauth_token and oauth_verifier query strings from the URL and use it in the IEx snippet below.

oauth_token = "<TOKEN>"
oauth_verifier = "<VERIFIER>"

# Exchange for an access token
{:ok, access_token} = ExTwitter.access_token(oauth_verifier, oauth_token)

# Configure ExTwitter to use your newly obtained access token
ExTwitter.configure(
  consumer_key: System.get_env("TWITTER_CONSUMER_KEY"),
  consumer_secret: System.get_env("TWITTER_CONSUMER_SECRET"),
  access_token: access_token.oauth_token,
  access_token_secret: access_token.oauth_token_secret
)

ExTwitter.user_timeline

Searching

Example for normal API.

iex> ExTwitter.search("elixir-lang", [count: 5]) |>
     Enum.map(fn(tweet) -> tweet.text end) |>
     Enum.join("\n-----\n") |>
     IO.puts

# => Tweets will be displayed in the console as follows.
@xxxx have you tried this yet?
-----
@yyyy You mean this? http://t.co/xxxx That had sailed below my radar thus far.
-----
@zzzz #elixir-lang. I'm jadams
-----
Akala ko 100 nalang kulang ko sa dark elixir para sa Barb King summoner level.
-----
@aaaa usually kasi magbbuzz lang yan pag luma na string. talaga ang elixir.

Streaming

Example for streaming API.

stream = ExTwitter.stream_filter(track: "apple") |>
Stream.map(fn(x) -> x.text end) |>
Stream.map(fn(x) -> IO.puts "#{x}\n---------------\n" end)

Enum.to_list(stream)

# => Tweets will be displayed in the console as follows.
Apple 'iWatch' rumour round-up
---------------
Apple iPhone 4s 16GB Black Verizon - Cracked Screen, WORKS PERFECTLY!
---------------
Apple iPod nano 7th Generation (PRODUCT) RED (16 GB) (Latest Model) - Full read by
---------------
...

The ExTwitter.stream_control/2 function to send a message to stop the stream.

# An example to stop receiving stream after 5 seconds passed.
pid = spawn(fn ->
  stream = ExTwitter.stream_filter(track: "apple")
  for tweet <- stream do
    IO.puts tweet.text
  end
end)

:timer.sleep(5000)
ExTwitter.stream_control(pid, :stop)

Twitter returns several streaming message types. These messages are returned when :receive_messages option is specified.

stream = ExTwitter.stream_sample(receive_messages: true)

for message <- stream do
  case message do
    tweet = %ExTwitter.Model.Tweet{} ->
      IO.puts "tweet = #{tweet.text}"

    deleted_tweet = %ExTwitter.Model.DeletedTweet{} ->
      IO.puts "deleted tweet = #{deleted_tweet.status[:id]}"

    limit = %ExTwitter.Model.Limit{} ->
      IO.puts "limit = #{limit.track}"

    stall_warning = %ExTwitter.Model.StallWarning{} ->
      IO.puts "stall warning = #{stall_warning.code}"

    _ ->
      IO.inspect message
  end
end

Cursor

Some of Twitter API have paging capability for retrieving large number of items through cursor. The following is an example to iteratively call the API to fetch all the items.

defmodule Retriever do
  def follower_ids(screen_name, acc \\ [], cursor \\ -1) do
    cursor = fetch_next(screen_name, cursor)
    if Enum.count(cursor.items) == 0 do
      List.flatten(acc)
    else
      follower_ids(screen_name, [cursor.items|acc], cursor.next_cursor)
    end
  end

  defp fetch_next(screen_name, cursor) do
    try do
      ExTwitter.follower_ids(screen_name, cursor: cursor)
    rescue
      e in ExTwitter.RateLimitExceededError ->
        :timer.sleep ((e.reset_in + 1) * 1000)
        fetch_next(screen_name, cursor)
    end
  end
end

ids = Retriever.follower_ids("TwitterDev")
IO.puts "Follower count for TwitterDev is #{Enum.count(ids)}."
# => Follower count for TwitterDev is 38469.

Development

run_iex.sh launches IEx, with initially calling ExTwitter.configure/1 defined as iex/dot.iex.

$ ./run_iex.sh
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:4:4] [async-threads:10]...
Interactive Elixir (1.0.2) - press Ctrl+C to exit (type h() ENTER for help)

iex> (ExTwitter.search("elixir") |> List.first).text

Copyright and License

Copyright (c) 2014 parroty

This work is free. You can redistribute it and/or modify it under the terms of the MIT License. See the LICENSE.md file for more details.

More Repositories

1

excoveralls

Coverage report tool for Elixir with coveralls.io integration.
Elixir
819
star
2

exvcr

HTTP request/response recording library for elixir, inspired by VCR.
Elixir
721
star
3

excheck

Property-based testing library for Elixir (QuickCheck style).
Elixir
316
star
4

exprof

A simple code profiler for Elixir using eprof.
Elixir
178
star
5

exfirebase

An elixir library for accessing the Firebase REST API.
Elixir
88
star
6

oauth2ex

An OAuth 2.0 client library for elixir.
Elixir
57
star
7

kindle-your-highlights

Scrape highlights from kindle.amazon.com
Ruby
48
star
8

exprintf

A printf / sprintf library for Elixir. It works as a wrapper for :io.format.
Elixir
35
star
9

http_server

A simple and self-contained HTTP Server for elixir.
Elixir
12
star
10

spawn_viewer

Trial implementation to visualize process spawning.
Elixir
8
star
11

dynamo_angular

Sample AngularJS scaffolding with dynamo and angular-resource backend.
Elixir
5
star
12

dynamo_firebase

Sample dynamo project for implementing rails-like scaffold page with Firebase backend.
Elixir
4
star
13

ruboto_flickr

Flickr search sample app using Ruboto
Java
4
star
14

chef-cookbook-elixir

Chef cookbook for installing elixir (elixir-lang)
Ruby
4
star
15

big_query

[WIP] Elixir + Google BigQuery Sample
Elixir
4
star
16

dynamo_scaffold

Sample dynamo project for implementing rails-like scaffold page with REST API backend.
Elixir
3
star
17

coverage_sample

sample code for excoveralls
Elixir
3
star
18

chef-cookbook-dynamo

Chef cookbook for deploying dynamo application (elixir-lang)
Ruby
3
star
19

exfuture

A trial implementation of future
Elixir
2
star
20

docker-poxa

Dockerfile for poxa installation.
Shell
2
star
21

mono_timer

Pomodoro-style 25 minutes timer rails-app with notification feature.
Ruby
2
star
22

circle_sample

A test project for CircleCI and Elixir.
Elixir
2
star
23

exrtm

An elixir library for remember the milk API.
Elixir
2
star
24

angularjs_samples

Angular JS sample
JavaScript
1
star
25

excov

testing for coverage
Elixir
1
star
26

sample_future

Sample parallel map program for Future on elixir
Elixir
1
star
27

dynamo_sample

Just a sample for deployment trial
Elixir
1
star
28

pogo

simple tool for starting/stopping erlang nodes via the command line
Elixir
1
star
29

ruboto_spinner

An ruboto example for Android spinner widget.
Java
1
star
30

readline

(experimental) A readline wrapper for Elixir. It's experimental and may not work well.
C
1
star
31

angularjs_sample_rails

angularjs sample with angular-resource and rails backend.
Ruby
1
star
32

ereadline

(WIP) A readline wrapper for Erlang.
C
1
star
33

thought_mapper

[WIP] Thinking assistant tool on comparing options.
Ruby
1
star
34

rtmgo

Remember the milk api client for golang
Go
1
star
35

excoveralls_umbrella

Sample project for excoveralls on umbrella elixir projects.
Elixir
1
star