Vietnamese (Tiếng Việt) translation by Dai Phong (you can also view the original English article)
Trong bài hướng dẫn này, bạn sẽ tìm hiểu cách xác thực và kết nối với Twitter API bằng Node.js và Angular 6. Đến cuối hướng dẫn này, bạn sẽ có được như sau:
- xác thực với Twitter API
- đăng tweet với Twitter API
- đọc timeline Twitter với Twitter API
- và hơn thế nữa!
Tạo Node Server
Chúng ta sẽ bắt đầu bằng cách xây dựng một Node server sẽ xử lý việc tương tác với Twitter API. Bước đầu tiên sẽ là đăng ký một ứng dụng mới để có được thông tin đăng nhập để bắt đầu sử dụng Twitter API.
Chỉ cần truy cập https://apps.twitter.com/, tạo một ứng dụng mới và điền vào tất cả các chi tiết cần thiết. tên ứng dụng, mô tả và URL. Sau khi tạo ứng dụng của bạn, bạn sẽ được yêu cầu tạo các khóa duy nhất cho ứng dụng của mình. Để làm điều đó, chỉ cần đi tới tab Keys and Access Token và nhấp vào nút Create my access token nằm ở cuối trang.
Ứng dụng sẽ tạo ra bốn khóa như sau:
- Consumer Key (API key)
- Consumer Secret (API secret)
- Access Token
- Access Token Secret
Vui lòng lưu ý các khoá trên vì chúng sẽ có ích sau này.
Tạo một thư mục cho code máy chủ, tạo tập tin .json bằng cách chạy npm init
và tạo tập tin server.js.
1 |
mkdir server
|
2 |
cd server
|
3 |
npm init |
4 |
touch server.js
|
Sau đó, chúng ta sẽ cài đặt gói twit
và phần còn lại của các phụ thuộc cần thiết để khởi động ứng dụng Express.
1 |
npm install twit body-parser cors express
|
Gói twit
sẽ giúp chúng ta tương tác với Twitter API. Tiếp theo, trong server.js, khởi tạo các mô-đun, tạo ứng dụng Express và khởi chạy server.
1 |
const express = require('express'); |
2 |
const Twitter = require('twit'); |
3 |
const app = express(); |
4 |
|
5 |
app.listen(3000, () => console.log('Server running')) |
Xác thực
Sau đó chúng ta sẽ cung cấp các khóa API cho gói twit
như dưới đây.
1 |
const api-client = new Twitter({ |
2 |
consumer_key: 'CONSUMER_KEY', |
3 |
consumer_secret: 'CONSUMER_SECRET', |
4 |
access_token: 'ACCESS_TOKEN', |
5 |
access_token_secret: 'ACCESS_TOKEN_SECRET' |
6 |
});
|
Các khóa là duy nhất cho ứng dụng của bạn và được liên kết với tài khoản Twitter của bạn. Vì vậy, khi bạn thực hiện một yêu cầu với Twitter API, bạn sẽ là người dùng được xác thực.
Sau đó, chúng ta sẽ tạo các endpoint để post và truy xuất các tweet trên máy chủ Node của chúng ta.
Twitter cung cấp các endpoint sau đây sẽ cho phép chúng ta tương tác với timeline Twitter của chúng ta khi truy xuất và post các tweet.
- GET
statuses/home_timeline
—trả về các tweet gần đây nhất được post bởi người dùng và người dùng họ theo dõi - GET
statuses/home_timeline
—trả về các mention gần đây nhất cho người dùng - POST
statuses/update
—dùng để đăng tweet
Truy vấn Tweet
Endpoint đầu tiên này sẽ được sử dụng để truy xuất các tweet mới nhất trên timeline của bạn. Chúng ta cũng sẽ chỉ định số tweet mà chúng ta muốn lấy.
1 |
app.get('/home_timeline', (req, res) => { |
2 |
const params = { tweet_mode: 'extended', count: 10 }; |
3 |
|
4 |
client
|
5 |
.get(`statuses/home_timeline`, params) |
6 |
.then(timeline => { |
7 |
|
8 |
res.send(timeline); |
9 |
})
|
10 |
.catch(error => { |
11 |
res.send(error); |
12 |
});
|
13 |
|
14 |
});
|
Tiếp theo là API để truy xuất tất cả các tweet nơi mà người dùng xác thực đã được mention.
1 |
app.get('/mentions_timeline', (req, res) => { |
2 |
const params = { tweet_mode: 'extended', count: 10 }; |
3 |
|
4 |
client
|
5 |
.get(`statuses/mentions_timeline`, params) |
6 |
.then(timeline => { |
7 |
|
8 |
res.send(timeline); |
9 |
})
|
10 |
.catch(error => { |
11 |
res.send(error); |
12 |
});
|
13 |
|
14 |
});
|
Để có thể ghi vào timeline Twitter, chúng ta cần thay đổi cấp độ quyền truy cập ứng dụng (Access permissions) thành Đọc và viết (Read and write) như hình dưới đây.



Đăng Tweet
Tiếp theo, cập nhật tập tin server.js để gọi API để đăng tweet.
1 |
app.post('/post_tweet', (req, res) => { |
2 |
|
3 |
tweet = req.body; |
4 |
|
5 |
client
|
6 |
.post(`statuses/update`, tweet) |
7 |
.then(tweeting => { |
8 |
console.log(tweeting); |
9 |
|
10 |
res.send(tweeting); |
11 |
})
|
12 |
|
13 |
.catch(error => { |
14 |
res.send(error); |
15 |
});
|
16 |
|
17 |
|
18 |
});
|
Chúng ta đã xong với node server và bây giờ bạn có thể kiểm tra REST API của mình với Postman để đảm bảo nó hoạt động tốt.
Test Back-End
Nếu bạn truy vấn endpoint home_timeline
trong API của mình, bạn sẽ thấy như sau.



Và đây là một yêu cầu GET đến endpoint mentions_timeline
:



Code cho server mà chúng ta đã tạo ở trên cũng có thể được sử dụng để tạo bot Twitter. Dưới đây là một ví dụ về bot Twitter cơ bản cập nhật trạng thái của người dùng.
1 |
const express = require('express'); |
2 |
const Twitter = require('twit'); |
3 |
|
4 |
const app = express(); |
5 |
const client = new Twitter({ |
6 |
consumer_key: 'Consumer Key Here', |
7 |
consumer_secret: 'Consumer Secret Here', |
8 |
access_token: 'Access Token Here', |
9 |
access_token_secret: 'Token Secret Here' |
10 |
});
|
11 |
|
12 |
|
13 |
app.use(require('cors')()); |
14 |
app.use(require('body-parser').json()); |
15 |
|
16 |
app.post('/post_tweet', (req, res) => { |
17 |
|
18 |
tweet = {status:"Hello world"}; |
19 |
|
20 |
client
|
21 |
.post(`statuses/update`, tweet) |
22 |
.then(timeline => { |
23 |
console.log(timeline); |
24 |
|
25 |
res.send(timeline); |
26 |
})
|
27 |
|
28 |
.catch(error => { |
29 |
res.send(error); |
30 |
});
|
31 |
|
32 |
|
33 |
});
|
34 |
|
35 |
app.listen(3000, () => console.log('Server running')); |
36 |
Xây dựng một ứng dụng Angular để sử dụng REST API
Bây giờ chúng ta sẽ bắt đầu xây dựng ứng dụng Angular mà sẽ sử dụng API từ máy chủ Node của chúng ta.
Đầu tiên, tạo một ứng dụng Angular.
1 |
ng new client |
Twitter Service
Chúng ta sẽ bắt đầu bằng cách tạo một Twitter Service sẽ thực hiện các yêu cầu đến máy chủ Node. Thực thi lệnh sau trong ứng dụng Angular.
1 |
ng generate service twitterservice |
Việc này sẽ tạo ra hai tập tin, twitter.service.ts và twitter.service.spec.ts. Mở twitter.service.ts, thêm các import theo yêu cầu, khai báo API endpoint và tiêm inject mô đun HttpClient
vào constructor.
1 |
api_url = 'https://localhost:3000'; |
2 |
|
3 |
constructor(private http: HttpClient) { } |
Sau đó, chúng ta sẽ định nghĩa các hàm để sử dụng REST API.
1 |
export class TwitterService { |
2 |
|
3 |
api_url = 'http://localhost:3000'; |
4 |
|
5 |
constructor(private http: HttpClient) { } |
6 |
|
7 |
getTimeline() { |
8 |
return this.http |
9 |
.get<any[]>(this.api_url+'/home_timeline') |
10 |
.pipe(map(data => data)); |
11 |
|
12 |
}
|
13 |
|
14 |
getMentions() { |
15 |
return this.http |
16 |
.get<any[]>(this.api_url+'/mentions_timeline') |
17 |
.pipe(map(data => data)); |
18 |
|
19 |
}
|
20 |
|
21 |
}
|
Truy cập Twitter Service từ Component.
Để truy cập Twitter Service từ component của chúng ta, chúng ta sẽ cần tạo các component sau.
1 |
ng generate component twitter_timeline |
2 |
ng generate component twitter_mentions |
3 |
ng generate component tweet |
Tiếp theo, khai báo các route cho các component được tạo trong app.module.ts.
1 |
import { RouterModule, Routes } from '@angular/router'; |
2 |
|
3 |
const appRoutes: Routes = [ |
4 |
{
|
5 |
path: 'twitter_timeline', |
6 |
component: TwitterTimelineComponent |
7 |
},
|
8 |
{
|
9 |
path: 'twitter_mentions', |
10 |
component: TwitterMentionsComponent |
11 |
},
|
12 |
|
13 |
{
|
14 |
path: 'tweets', |
15 |
component: TweetComponent |
16 |
},
|
17 |
|
18 |
{ path: '', |
19 |
redirectTo: '', |
20 |
pathMatch: 'full' |
21 |
}
|
22 |
];
|
Bây giờ hãy mở app.component.html và kết xuất các component như hình bên dưới.
1 |
<mat-toolbar color="primary"> |
2 |
<mat-toolbar-row> |
3 |
<!-- <span>HOME</span> --> |
4 |
<span><a href="/">HOME</a></span> |
5 |
<span class="spacer"></span> |
6 |
<span mat-button routerLink="/twitter_timeline">Timeline</span> |
7 |
<br> |
8 |
<a mat-button routerLink="/twitter_mentions">Mentions</a> |
9 |
<br> |
10 |
<a mat-button routerLink="/tweets">Tweets</a> |
11 |
</mat-toolbar-row> |
12 |
</mat-toolbar> |
13 |
<router-outlet></router-outlet> |
14 |
Truy vấn Tweet
Chúng tôi sẽ tạo hai component để hiển thị tweet của chúng ta. TwitterTimelineComponent
sẽ hiển thị các tweet gần đây nhất từ timeline của người dùng được xác thực, trong khi TwitterMentionsComponent
sẽ hiển thị tất cả các tweet mà người dùng được xác thực đã được mention.
Chúng ta sẽ bắt đầu với TwitterTimelineComponent
. Cập nhật twitter-timeline.component.ts như sau:
1 |
export class TwitterTimelineComponent implements OnInit { |
2 |
|
3 |
myTimeline: any; |
4 |
|
5 |
constructor(private api: TwitterService) { } |
6 |
|
7 |
ngOnInit() { |
8 |
this.getTwitterTimeline(); |
9 |
}
|
10 |
|
11 |
getTwitterTimeline(): void { |
12 |
this.api.getTimeline() |
13 |
.subscribe( |
14 |
myTimeline => { |
15 |
this.myTimeline = myTimeline; |
16 |
console.log(this.myTimeline); |
17 |
}
|
18 |
)
|
19 |
}
|
20 |
|
21 |
}
|
Phương thức getTwitterTimeline
bằng TwitterService
để lấy dữ liệu từ timeline của người dùng được xác thực. Sau đó, chúng ta cập nhật twitter-timeline.component.html như minh hoạ bên dưới.
1 |
<h1>Tweeter Timeline</h1> |
2 |
<div *ngIf="undefined === myData">Loading...</div> |
3 |
<div *ngIf="undefined !== myData"> |
4 |
<div class ="card"> |
5 |
<ng-container *ngFor="let tweets of myData.data"> |
6 |
<h3>{{tweets.full_text
|
7 |
}} |
8 |
</h3>
|
9 |
<p>{{tweets.created_at}}</p> |
10 |
<p>{{tweets.user.name}}</p> |
11 |
<p>{{tweets.user.screen_name}}</p> |
12 |
<p>{{tweets.user.location}}</p> |
13 |
<p>{{tweets.user.description}}</p> |
14 |
</ng-container>
|
15 |
</div>
|
16 |
</div>
|
17 |
Ở đây, chúng ta lặp qua mảng được trả về bởi phương thức getTwitterTimeline
và hiển thị các thuộc tính sau cho mỗi tweet:
location
description
username
created_at
screen_name
Sau đó chúng ta chuyển sang TwitterMentionsComponent và cập nhật nó như sau.
1 |
export class TwitterMentionsComponent implements OnInit { |
2 |
|
3 |
myMentions: any; |
4 |
|
5 |
constructor(private api: TwitterService) { } |
6 |
|
7 |
ngOnInit() { |
8 |
this.getTwitterMentions(); |
9 |
}
|
10 |
|
11 |
getTwitterMentions(): void { |
12 |
this.api.getTimeline() |
13 |
.subscribe( |
14 |
myMentions => { |
15 |
this.myMentions = myMentions; |
16 |
console.log(this.myMentions); |
17 |
}
|
18 |
)
|
19 |
}
|
20 |
|
21 |
}
|
Sau cùng, chúng ta cần hiển thị dữ liệu từ API trong template. Cập nhật twitter-mentions.component.html như sau:
1 |
<h1>Tweeter Mentions</h1> |
2 |
<div *ngIf="undefined === myData">Loading...</div> |
3 |
<div *ngIf="undefined !== myData"> |
4 |
<div class ="card"> |
5 |
<ng-container *ngFor="let tweets of myData.data"> |
6 |
<h3>{{tweets.full_text
|
7 |
}} |
8 |
</h3>
|
9 |
<p>{{tweets.created_at}}</p> |
10 |
<p>{{tweets.user.name}}</p> |
11 |
<p>{{tweets.user.screen_name}}</p> |
12 |
<p>{{tweets.user.location}}</p> |
13 |
<p>{{tweets.user.description}}</p> |
14 |
</ng-container>
|
15 |
</div>
|
16 |
</div>
|
17 |
Bây giờ, khi bạn chạy ứng dụng, bạn sẽ thấy tất cả các thuộc tính về tweet của bạn được hiển thị.
Đăng Tweet
Chúng ta sẽ bắt đầu bằng form để post dữ liệu lên endpoint /post_tweet
, nơi chúng ta xác định một input và nút submit để đăng tweet. Chúng ta sẽ sử dụng mô-đun FormBuilder
để xây dựng form cập nhật trạng thái. Thêm code sau vào tweet.component.ts.
1 |
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; |
2 |
|
3 |
export class TweetComponent implements OnInit { |
4 |
tweetForm: FormGroup; |
5 |
|
6 |
constructor(private api: TwitterService private formBuilder: FormBuilder) { } |
7 |
|
8 |
ngOnInit() { |
9 |
|
10 |
this.tweetForm = this.formBuilder.group({ |
11 |
tweetdata: ['', Validators.required] |
12 |
}); |
13 |
} |
14 |
|
15 |
} |
Bây giờ hãy cập nhật form để Angular biết nên sử dụng form nào.
1 |
<mat-card class="contact-card"> |
2 |
<mat-card-content>
|
3 |
<form [formGroup]="tweetForm" (ngSubmit)="onSubmit()"> |
4 |
<mat-form-field>
|
5 |
<input matInput placeholder="Status" formControlName="tweetdata" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.tweetdata.errors }" > |
6 |
</mat-form-field>
|
7 |
<br>
|
8 |
<div class="form-group"> |
9 |
<button [disabled]="loading" class="btn btn-primary">TWEET</button> |
10 |
<img *ngIf="loading" src="https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif" /> |
11 |
</div>
|
12 |
</form>
|
13 |
</mat-card-content>
|
14 |
</mat-card>
|
15 |
Như bạn có thể thấy ở trên, chúng ta đã thêm validator để form không thể được gửi nếu nó trống.
Sau đó chúng ta tiếp tục sử dụng Twitter service và cập nhật nó để bao gồm code để post dữ liệu lên API.
1 |
tweet(tweetdata: string) { |
2 |
return this.http.post<any>(`${this.api_url}/post_tweet/`, { status: tweetdata}) |
3 |
.pipe(map(tweet => { |
4 |
|
5 |
alert("tweet posted") |
6 |
|
7 |
return tweet; |
8 |
}));
|
9 |
}
|
10 |
|
11 |
}
|
Sau đó, chúng ta sẽ cập nhật TweetComponent
để làm nổi bật code gọi phương thức để post lên Twitter API. Thêm phần sau vào tweet.component.ts.
1 |
export class TweetComponent implements OnInit { |
2 |
tweetForm: FormGroup; |
3 |
loading = false; |
4 |
submitted = false; |
5 |
returnUrl: string; |
6 |
error = ''; |
7 |
|
8 |
constructor(private api: TwitterService private formBuilder: FormBuilder) { } |
9 |
|
10 |
ngOnInit() { |
11 |
|
12 |
this.tweetForm = this.formBuilder.group({ |
13 |
tweetdata: ['', Validators.required] |
14 |
});
|
15 |
}
|
16 |
|
17 |
get f() { return this.tweetForm.controls; } |
18 |
|
19 |
onSubmit() { |
20 |
this.submitted = true; |
21 |
|
22 |
// stop here if form is invalid
|
23 |
if (this.tweetForm.invalid) { |
24 |
return; |
25 |
}
|
26 |
|
27 |
this.loading = true; |
28 |
this.api.tweet(this.f.tweetdata.value) |
29 |
.pipe(first()) |
30 |
.subscribe( |
31 |
data => { |
32 |
console.log("yes") |
33 |
},
|
34 |
error => { |
35 |
this.error = error; |
36 |
this.loading = false; |
37 |
});
|
38 |
}
|
39 |
|
40 |
}
|
Bây giờ bạn có thể truy xuất các tweet mới nhất bằng cách nhấn vào endpoint /home_timeline
, truy xuất các mention của bạn thông qua endpoint /mentions_timeline
và đăng tweet qua endpoint /post_tweet
.
Phần kết luận
Trong bài hướng dẫn này, bạn đã học được cách làm việc với Twitter API và cách xây dựng một bot Twitter đơn giản chỉ với một vài dòng code. Bạn cũng đã học cách kết nối với REST API từ Angular, bao gồm tạo API Service và các component để tương tác với service đó.
Để tìm hiểu thêm về Twitter API, hãy truy cập trang web của Nhà phát triển Twitter và khám phá những khả năng vô tận.