-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
72 lines (60 loc) · 2.02 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import express from "express";
import { Client, auth } from "twitter-api-sdk";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const URL = process.env.URL || 'http://127.0.0.1';
const PORT = process.env.PORT ? parseInt(process.env.PORT) : 3000;
/**
* OAuth 2.0 Settings instructions:
* - Use the Twitter Developer Portal to create a Project and an App.
* - Configure your App by selecting the cog icon next to the App you wish to use.
* - Click Edit under User authentication settings.
* - Under OAuth 2.0 Settings, enable OAuth 2.0. Select "Web App" as your Type of App.
* - Under General Authentication Settings make sure your Callback URI / Redirect URL is the hosted URL of Web App. Save your changes.
*/
const authClient = new auth.OAuth2User({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
callback: `${URL}:${PORT}/callback`,
scopes: ["dm.read","tweet.read","users.read"],
});
const client = new Client(authClient);
const STATE = "my-state";
app.get("/callback", async function (req, res) {
try {
const { code, state } = req.query;
if (state !== STATE) return res.status(500).send("State isn't matching");
await authClient.requestAccessToken(code);
res.redirect("/tweets");
} catch (error) {
console.log(error);
}
});
app.get("/login", async function (req, res) {
const authUrl = authClient.generateAuthURL({
state: STATE,
code_challenge_method: "s256",
});
res.redirect(authUrl);
});
app.get("/revoke", async function (req, res) {
try {
const response = await authClient.revokeAccessToken();
res.send(response);
} catch (error) {
console.log(error);
}
});
app.get("/tweets", async function (req, res) {
try {
const response = await client.direct messages.getDmEvents();
console.log("response", JSON.stringify(response, null, 2));
res.send(response);
} catch (error) {
console.log("tweets error", error);
}
});
app.listen(PORT, () => {
console.log(`Go here to login: ${URL}:${PORT}/login`);
});