85 lines
2.8 KiB
JavaScript
85 lines
2.8 KiB
JavaScript
const { WebcastPushConnection } = require('tiktok-live-connector');
|
|
const mysql = require('mysql2/promise');
|
|
|
|
const [,, username, dbHost, dbUser, dbPass, dbName, userId] = process.argv;
|
|
|
|
if (!username) {
|
|
console.error('Usage: node tiktok_bridge.js <username> <dbHost> <dbUser> <dbPass> <dbName> <userId>');
|
|
process.exit(1);
|
|
}
|
|
|
|
async function start() {
|
|
console.log(`TikTok Bridge starting for @${username} (User ID: ${userId})`);
|
|
|
|
let connection;
|
|
try {
|
|
connection = await mysql.createConnection({
|
|
host: dbHost || '127.0.0.1',
|
|
user: dbUser || 'root',
|
|
password: dbPass || '',
|
|
database: dbName || 'app_db'
|
|
});
|
|
console.log('Connected to database');
|
|
} catch (err) {
|
|
console.error('DB Connection failed:', err);
|
|
process.exit(1);
|
|
}
|
|
|
|
const tiktokConnection = new WebcastPushConnection(username);
|
|
|
|
tiktokConnection.connect().then(state => {
|
|
console.log(`Connected to TikTok Live @${username} (Room ID: ${state.roomId})`);
|
|
}).catch(err => {
|
|
console.error('TikTok Connection failed:', err);
|
|
process.exit(1);
|
|
});
|
|
|
|
tiktokConnection.on('chat', async (data) => {
|
|
console.log(`[Chat] ${data.uniqueId}: ${data.comment}`);
|
|
try {
|
|
await connection.execute(
|
|
'INSERT INTO tiktok_history (username, comment_author, comment_text, user_id, created_at) VALUES (?, ?, ?, ?, NOW())',
|
|
[username, data.uniqueId, data.comment, userId || null]
|
|
);
|
|
} catch (err) {
|
|
console.error('Error inserting chat:', err);
|
|
}
|
|
});
|
|
|
|
tiktokConnection.on('gift', async (data) => {
|
|
const giftMsg = `sent ${data.repeatCount}x ${data.giftName}!`;
|
|
console.log(`[Gift] ${data.uniqueId}: ${giftMsg}`);
|
|
try {
|
|
await connection.execute(
|
|
'INSERT INTO tiktok_history (username, comment_author, comment_text, user_id, created_at) VALUES (?, ?, ?, ?, NOW())',
|
|
[username, data.uniqueId, giftMsg, userId || null]
|
|
);
|
|
} catch (err) {
|
|
console.error('Error inserting gift:', err);
|
|
}
|
|
});
|
|
|
|
tiktokConnection.on('disconnected', () => {
|
|
console.log('TikTok connection disconnected');
|
|
process.exit(0);
|
|
});
|
|
|
|
tiktokConnection.on('error', (err) => {
|
|
console.error('TikTok error:', err);
|
|
});
|
|
|
|
// Keep alive
|
|
setInterval(async () => {
|
|
try {
|
|
await connection.query('SELECT 1');
|
|
} catch (err) {
|
|
console.error('DB connection lost, reconnecting...');
|
|
connection = await mysql.createConnection({
|
|
host: dbHost, user: dbUser, password: dbPass, database: dbName
|
|
});
|
|
}
|
|
}, 30000);
|
|
}
|
|
|
|
start();
|