1:- module(twitter,
    2         [token/1,
    3          get_bearer_token/5,
    4          make_a_search/4]).
    5
    6:- use_module(library(http/thread_httpd)).
    7:- use_module(library(http/http_dispatch)).
    8:- use_module(library(http/http_error)).
    9:- use_module(library(http/html_write)).
   10:- use_module(library(http/http_session)).
   11:- use_module(library(http/js_write)).
   12:- use_module(library(http/http_files)).
   13:- use_module(library(http/json)).
   14:- use_module(library(http/http_open)).
   15:- use_module(library(http/http_json)).
   16:- use_module(library(http/http_parameters)).
   17:- use_module(library(http/http_client)).
   18:- use_module(library(http/http_ssl_plugin)).
   19
   20:- dynamic
   21	token/1.
   22
   23bearer_token_credentials(Key,Secret,B_Token):-
   24        format(atom(B_Token),"~w:~w",[Key,Secret]).
   25
   26get_bearer_token(Key,Secret,JSON,Token,ErrorCode):-
   27	bearer_token_credentials(Key,Secret,B_Token),
   28	base64(B_Token,B_Token64),
   29	format(atom(My_Auth),"Basic ~w",[B_Token64]),
   30	ListofData =[grant_type=client_credentials],
   31        http_open('https://api.twitter.com/oauth2/token', In,
   32                  [ request_header(authorization=My_Auth),status_code(ErrorCode),
   33		    method(post),post(form(ListofData))
   34                  ]),
   35	call_cleanup(json_read_dict(In, JSON),
   36	close(In)),
   37	Token = JSON.access_token,
   38	assertz(token(Token)).
   39
   40
   41make_a_search(My_Search,B_Token64,JSON,ErrorCode):-
   42	format(atom(My_Auth),"Bearer ~w",[B_Token64]),
   43	URL0='https://api.twitter.com/1.1/search/tweets.json',
   44	url_extend(search([q(My_Search)]),URL0,URL),
   45	http_open(URL, In,
   46                  [ request_header(authorization=My_Auth),
   47		    status_code(ErrorCode)
   48
   49                  ]),
   50	call_cleanup(json_read_dict(In, JSON),
   51	close(In)).
   52
   53
   54url_extend(search(Params), URL0, URL) :-
   55	uri_components(URL0, Components0),
   56	uri_data(search, Components0, Search0),
   57	extend_search(Search0, Params, Search),
   58	uri_data(search, Components0, Search, Components),
   59	uri_components(URL, Components).
   60
   61extend_search(Var, Params, String) :-
   62	var(Var), !,
   63	uri_query_components(String, Params).
   64extend_search(String0, Params, String) :-
   65	uri_query_components(String0, Params0),
   66	append(Params0, Params, AllParams),
   67	uri_query_components(String, AllParams)