Skip to content

Commit

Permalink
sing command full fixed and fassssst
Browse files Browse the repository at this point in the history
  • Loading branch information
1dev-hridoy committed Nov 12, 2024
1 parent 179e763 commit 47c088f
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 77 deletions.
23 changes: 21 additions & 2 deletions bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,27 @@ async function startBot() {
}
});

bot.on('callback_query', async (callbackQuery) => {
try {
const [commandName, ...args] = callbackQuery.data.split(':');
const command = commands[commandName];

if (command && command.handleCallback) {
console.log(rainbowText(
`[${new Date().toLocaleTimeString()}] CALLBACK - ${callbackQuery.from.username || callbackQuery.from.first_name}: ${callbackQuery.data}`
));

await command.handleCallback(bot, callbackQuery, args, db);
}
} catch (error) {
console.error(chalk.red('Error handling callback query:'), error);
await bot.answerCallbackQuery(callbackQuery.id, {
text: '💔 Oopsie woopsie! Something went wrong! 💔',
show_alert: true
}).catch(err => console.error('Error sending callback error message:', err));
}
});

bot.on('new_chat_members', async (msg) => {
const chatId = msg.chat.id;
const groupName = msg.chat.title;
Expand Down Expand Up @@ -249,6 +270,4 @@ process.on('unhandledRejection', (reason, promise) => {
process.on('uncaughtException', (error) => {
console.error(chalk.red.bold(fancyBox('🚨 Uncaught Exception: 🚨')));
console.error(error);
// Optionally, you can choose to exit the process here
// process.exit(1);
});
150 changes: 75 additions & 75 deletions commands/sing.js
Original file line number Diff line number Diff line change
@@ -1,100 +1,100 @@
const axios = require('axios');
const fs = require('fs');
const path = require('path');

module.exports = {
name: 'sing',
adminOnly: false,
ownerOnly: false,
category: 'Entertainment',
description: 'Get audio or video of a song',
guide: 'Use /sing <song name> for audio, or /sing video <song name> for video',
description: 'Search and play music from YouTube',
guide: 'Use /sing <song name> to search and play music',
execute: async (bot, msg, args) => {
const chatId = msg.chat.id;

if (args.length === 0) {
return bot.sendMessage(chatId, 'Please provide a song name. Usage: /sing <song name> or /sing video <song name>');
return bot.sendMessage(chatId, 'Please provide a song name. Usage: /sing <song name>');
}

let isVideo = false;
let query;
const query = args.join(' ');
const searchMessage = await bot.sendMessage(chatId, `🔎 Searching for "${query}"...`);

if (args[0].toLowerCase() === 'video') {
isVideo = true;
query = args.slice(1).join(' ');
if (!query) {
return bot.sendMessage(chatId, 'Please provide a song name after "video". Usage: /sing video <song name>');
try {
const searchResponse = await axios.get(`https://api.nexalo.xyz/youtube-search.php?api=na_Z21SSP93HR0123QO&query=${encodeURIComponent(query)}`);

if (searchResponse.data.status !== 200 || !searchResponse.data.result || searchResponse.data.result.length === 0) {
await bot.deleteMessage(chatId, searchMessage.message_id);
return bot.sendMessage(chatId, 'No results found. Please try a different search term.');
}
} else {
query = args.join(' ');
}

const apiUrl = `https://api.nexalo.xyz/ytv1.php?name=${encodeURIComponent(query)}&api=na_Z21SSP93HR0123QO`;

try {
const response = await axios.get(apiUrl);
if (response.data.status === 'success') {
const { title, best_audio, best_video } = response.data;
const results = searchResponse.data.result.slice(0, 3);
const keyboard = results.map((result, index) => [
{ text: `Send No ${index + 1}: ${result.title}`, callback_data: `sing:${result.videoId}:${index + 1}` }
]);

if (isVideo) {
if (best_video && best_video.video_link) {
await sendVideoToTelegram(bot, chatId, best_video.video_link, title, best_video.quality);
} else {
await bot.sendMessage(chatId, "Sorry, I couldn't find a video for this song.");
}
} else {
if (best_audio && best_audio.audio_link) {
await sendAudioToTelegram(bot, chatId, best_audio.audio_link, title, best_audio.quality);
} else {
await bot.sendMessage(chatId, "Sorry, I couldn't find audio for this song.");
}
await bot.deleteMessage(chatId, searchMessage.message_id);
await bot.sendMessage(chatId, 'Choose a song to play:', {
reply_markup: {
inline_keyboard: keyboard
}
} else {
await bot.sendMessage(chatId, "I'm sorry, I couldn't find the requested song. Please try a different query.");
}
});

} catch (error) {
console.error('Error in sing command:', error);
await bot.sendMessage(chatId, "Oops! Something went wrong while fetching the song. Please try again later.");
await bot.deleteMessage(chatId, searchMessage.message_id);
await bot.sendMessage(chatId, 'An error occurred while searching for the song. Please try again later.');
}
}
};

async function sendVideoToTelegram(bot, chatId, videoUrl, title, quality) {
try {
const videoStream = await axios({
url: videoUrl,
method: 'GET',
responseType: 'stream',
headers: {
'Content-Type': 'video/mp4' // Explicitly setting content-type for video
},

handleCallback: async (bot, callbackQuery) => {
const chatId = callbackQuery.message.chat.id;
const messageId = callbackQuery.message.message_id;
const [, videoId, index] = callbackQuery.data.split(':');
const sendingMessage = await bot.sendMessage(chatId, `Fetching song ${index}...`);

try {
await bot.deleteMessage(chatId, messageId);
const youtubeUrl = `https://youtube.com/watch?v=${videoId}`;
const audioResponse = await axios.get(`https://api.nexalo.xyz/youtube-audio?api=na_Z21SSP93HR0123QO&url=${encodeURIComponent(youtubeUrl)}`);

if (audioResponse.data.status !== 200 || !audioResponse.data.result) {
throw new Error('Invalid audio response');
}
});

await bot.sendVideo(chatId, videoStream.data, {
caption: `🎥 ${title}\n\nQuality: ${quality}`
});
} catch (error) {
console.error('Error sending video:', error);
await bot.sendMessage(chatId, "Sorry, I couldn't send the video. It might be too large or in an unsupported format.");
}
}
const audioResult = audioResponse.data.result;

// Download the audio file
const audioBuffer = await axios.get(audioResult.audio, { responseType: 'arraybuffer' });
// Create a temporary file
const tempFilePath = path.join(__dirname, `temp_${Date.now()}.mp3`);
fs.writeFileSync(tempFilePath, audioBuffer.data);

async function sendAudioToTelegram(bot, chatId, audioUrl, title, quality) {
try {
const audioStream = await axios({
url: audioUrl,
method: 'GET',
responseType: 'stream',
headers: {
'Content-Type': 'audio/mpeg' // Explicitly setting content-type for audio
}
});
// Send the audio as a file
await bot.sendAudio(chatId, tempFilePath, {
caption: `🎵 ${audioResult.title}\n👤 ${audioResult.channel_name}\n⏱ ${audioResult.duration}`,
title: audioResult.title,
performer: audioResult.channel_name,
duration: audioResult.duration
});

// Delete the temporary file
fs.unlinkSync(tempFilePath);

await bot.sendAudio(chatId, audioStream.data, {
title: title,
performer: 'Requested Song',
caption: `🎵 ${title}\n\nQuality: ${quality}`
});
} catch (error) {
console.error('Error sending audio:', error);
await bot.sendMessage(chatId, "Sorry, I couldn't send the audio. It might be too large or in an unsupported format.");
} catch (error) {
console.error('Error in sing callback:', error);
let errorMessage = 'An error occurred while fetching the audio. Please try again later.';

if (error.response) {
console.error('Error response:', error.response.data);
if (error.response.status === 400) {
errorMessage = 'Unable to process the audio. The file might be too large or in an unsupported format.';
}
}

await bot.sendMessage(chatId, errorMessage);
} finally {
await bot.deleteMessage(chatId, sendingMessage.message_id);
}
}
}
};

0 comments on commit 47c088f

Please sign in to comment.