-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.mjs
136 lines (114 loc) · 4.76 KB
/
bot.mjs
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import { Telegraf } from 'telegraf';
import dotenv from 'dotenv';
import { initializeDatabase, saveUserData, getUserData, fetchNowPlaying, createText, getReplyMarkup } from './src/utils.mjs';
import { getYouTubeMusicDetails } from './src/youtube.mjs';
dotenv.config();
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
console.log('Bot token:', process.env.TELEGRAM_BOT_TOKEN);
await initializeDatabase();
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
// Bot commands
bot.start((ctx) => {
ctx.reply(
'Tunified bot fetches the currently playing song from Last.fm and posts details about the song to a specified channel.\n\n' +
'Firstly Add the bot as Admin to your channnel and then use the setup cmds accordingly,\n' +
'Setup Commands:\n' +
'/setname your_nickname - To be shown on the post.\n' +
'/setchannel channel_id - Use @chatidrobot to get ID.\n' +
'/setlastfm lastfm_username - Last.FM usrname for scrobbling.',
{ parse_mode: 'HTML' }
);
});
// Command to set the user's name
bot.command('setname', async (ctx) => {
const value = ctx.message.text.split(' ').slice(1).join(' ');
const userId = ctx.from.id.toString();
console.log('Received /setname command from user:', userId);
if (!value) {
return ctx.reply("Please provide a name using `/setname [your name]`.");
}
console.log('Saving user data:', { userId, tgUser: value });
await saveUserData(userId, { tgUser: value });
return ctx.reply(`Name has been set to ${value}.`);
});
// Command to set the user's channel ID
bot.command('setchannel', async (ctx) => {
const value = ctx.message.text.split(' ').slice(1).join(' ');
const userId = ctx.from.id.toString();
console.log('Received /setchannel command from user:', userId);
if (!value) {
return ctx.reply("Please provide a channel ID using `/setchannel` you cam Use @chatidrobot to get ID.");
}
console.log('Saving user data:', { userId, channelId: value });
await saveUserData(userId, { channelId: value });
return ctx.reply(`Channel ID has been set to ${value}.`);
});
// Command to set the user's Last.fm username
bot.command('setlastfm', async (ctx) => {
const value = ctx.message.text.split(' ').slice(1).join(' ');
const userId = ctx.from.id.toString();
console.log('Received /setlastfm command from user:', userId);
if (!value) {
return ctx.reply("Please provide your Last.fm username using `/setlastfm [username]`.");
}
console.log('Saving user data:', { userId, lastfmUsername: value });
await saveUserData(userId, { lastfmUsername: value });
return ctx.reply(`Last.fm username has been set to ${value}.`);
});
async function checkAndPostNowPlaying() {
const users = await getUserData();
if (!users || !Array.isArray(users)) {
console.error("No users found or users is not an array");
return;
}
for (const user of users) {
const track = await fetchNowPlaying(user.userId);
if (track) {
let details = await getYouTubeMusicDetails(track.artistName, track.trackName);
if (!details) {
console.error('Could not fetch details from YouTube Music');
continue;
}
const { albumCover, id } = details;
const text = createText({ ...track, ...user });
const replyMarkup = getReplyMarkup({ id, artistName: track.artistName });
try {
if (user.lastMessageId) {
await bot.telegram.editMessageMedia(
user.channelId,
user.lastMessageId,
null,
{
type: 'photo',
media: albumCover,
caption: text,
parse_mode: 'HTML'
},
replyMarkup
);
} else {
const message = await bot.telegram.sendPhoto(user.channelId, albumCover, {
caption: text,
parse_mode: 'HTML',
...replyMarkup
});
await saveUserData(user.userId, { lastMessageId: message.message_id });
}
} catch (error) {
console.error("Error posting to Telegram:", error);
}
}
}
}
function initialize() {
setInterval(checkAndPostNowPlaying, 5000); // Check every 5 seconds
}
// Add this to log all incoming messages
bot.on('message', (ctx) => {
console.log('Received message:', ctx.message);
});
initialize();
bot.launch().then(() => {
console.log('Bot is running!');
});