-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
79 lines (72 loc) · 2.28 KB
/
main.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
73
74
75
76
77
78
79
/**
* Importing required modules and libraries
*/
import util from "util";
import { exec } from "child_process";
import { AppTokenAuthProvider } from "@twurple/auth";
import { ApiClient } from "@twurple/api";
import { EventSubHttpListener, EnvPortAdapter } from "@twurple/eventsub-http";
let recording = false;
/**
* The main function that initializes the Twitch auto-downloader
*/
async function main() {
// Load environment variables from a .env file
const clientId = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;
const userName = process.env.USERNAME;
const token = process.env.TOKEN;
const hostName = process.env.HOSTNAME;
const port = process.env.PORT;
const secret = process.env.SECRET;
// Create a new AppTokenAuthProvider
const authProvider = new AppTokenAuthProvider(clientId, clientSecret);
// Create a new ApiClient
const apiClient = new ApiClient({ authProvider });
const user = await apiClient.users.getUserByName(userName);
// Create a new EventSubHttpListener and start it
const listener = new EventSubHttpListener({
apiClient,
adapter: new EnvPortAdapter({
hostName: hostName,
}),
secret: secret,
});
listener.start();
console.log(
`Listening on http://localhost:${port} for incoming events on ${hostName}...`
);
// Subscribe to the stream.online event
listener.onStreamOnline(user.id, async (e) => {
console.log(`${userName} went online, start recording...`);
if (recording) {
console.log("Already recording, skipping...");
return;
}
try {
recording = true;
await runStreamLink(userName, token);
} catch (error) {
console.error("Error during recording:", error);
} finally {
recording = false;
}
});
}
/**
* Function to run the streamlink command and record the stream
* @param {string} userName - The Twitch username
* @param {string} token - The Twitch access token
*/
async function runStreamLink(userName, token) {
const { stdout, stderr } = await util.promisify(exec)(
`streamlink "--twitch-api-header=Authorization=OAuth ${token}" twitch.tv/${userName} best -o "/files/{time:%Y%m%d%H%M%S}-{title}.ts"`
);
console.log("stdout:", stdout);
console.log("stderr:", stderr);
}
try {
await main();
} catch (e) {
console.error(e);
}