multi-scrobbler-now-playing/index.js

66 lines
1.9 KiB
JavaScript

import fetch from 'node-fetch';
import readline from "readline";
import { TelegramClient } from 'telegram';
import { StoreSession } from 'telegram/sessions/index.js';
import 'dotenv/config';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const apiId = process.env.API_ID;
const apiHash = process.env.API_HASH;
const sessionStore = new StoreSession("tg_session");
async function getCurrentSong() {
return fetch('https://multi-scrobbler.riksolo.com/api/status').then((data) => {
return data.json();
}).then(data => {
const players = [];
// get all players of all sources
data.sources.forEach(source => {
if (!source.players) return;
const sourcePlayers = Object.values(source.players);
sourcePlayers.forEach(player => {
players.push(player);
});
});
// sort players in order of most recent new song
const sortedPlayers = players.sort((a, b) => new Date(a.playFirstSeenAt).getTime() - new Date(b.playFirstSeenAt).getTime());
// default string
let nowPlaying = "";
// if a player exists, get it's song
if (sortedPlayers.length !== 0) {
const playData = sortedPlayers[0].play.data;
nowPlaying = `${playData.artists.join(', ')} - ${playData.track}`;
}
return nowPlaying;
});
}
async function initTelegram() {
if (!apiId) { console.error("missing env var API_ID"); return; };
if (!apiHash) { console.error("missing env var API_HASH"); return; };
const client = new TelegramClient(sessionStore, apiId, apiHash, {
connectionRetries: 5
});
await client.start({
phoneNumber: async (res) => { rl.question("Phone number: ", res); },
password: async (res) => { rl.question("password: ", res); },
phoneCode: async (res) => { rl.question("code: ", res); },
onError: (err) => console.error(err)
});
console.log(client.session.save());
await CloseEvent.sendMessage("me", { message: "hi" });
}
initTelegram();