betty2 / example copy 2.js
sdgsdggds's picture
Upload folder using huggingface_hub
e7c953d verified
// Enhanced example of using the DubAPI library
const DubAPI = require('./index.js');
console.log('Starting DubAPI example...');
// Replace with your queup.net credentials
const username = 'kuber';
const password = 'cookTV12';
// Replace with the room you want to connect to
const roomName = 'nononono';
// Bot configuration
const config = {
commandPrefix: '!', // Prefix for commands
autoReconnect: true, // Automatically reconnect on disconnection
reconnectInterval: 15000, // Time in ms to wait before reconnecting
greetUsers: true, // Whether to greet users when they join
autoUpvote: true, // Whether to automatically upvote songs
botName: 'Kuber', // Bot's name for mention detection
respondToMentions: true // Whether to respond when mentioned
};
console.log('Attempting to create DubAPI instance with username:', username);
console.log('Connecting to room:', roomName);
new DubAPI({username: username, password: password}, function(err, bot) {
if (err) return console.error('Error connecting:', err);
console.log('Running DubAPI v' + bot.version);
// ========== Utility Functions ==========
// Format time in seconds to mm:ss
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs < 10 ? '0' + secs : secs}`;
}
// Check if user has staff permissions
function isStaff(user) {
return user && bot.isStaff(user);
}
// ========== Command Handler ==========
// Handle chat commands
function handleCommand(data) {
// Ignore if not a command
if (!data.message.startsWith(config.commandPrefix)) return;
// Parse command and arguments
const args = data.message.slice(config.commandPrefix.length).trim().split(/\s+/);
const command = args.shift().toLowerCase();
// Get user who sent the command
const user = bot.getUser(data.user.id);
switch (command) {
case 'ping':
bot.sendChat('Pong! 🏓');
break;
case 'info':
const currentMedia = bot.getMedia();
if (currentMedia) {
bot.sendChat(`Current track: ${currentMedia.name} by ${currentMedia.artist || 'Unknown'}`);
} else {
bot.sendChat('No track is currently playing.');
}
break;
case 'time':
const remaining = bot.getTimeRemaining();
const elapsed = bot.getTimeElapsed();
if (remaining >= 0) {
bot.sendChat(`Time remaining: ${formatTime(remaining)} | Elapsed: ${formatTime(elapsed)}`);
} else {
bot.sendChat('No track is currently playing.');
}
break;
case 'skip':
if (isStaff(user) && bot.hasPermission(user, 'skip')) {
bot.moderateSkip(function(err) {
if (err) return console.error('Error skipping track:', err);
bot.sendChat('Track skipped by ' + user.username);
});
} else {
bot.sendChat('You need to be staff with skip permission to use this command.');
}
break;
case 'users':
const users = bot.getUsers();
bot.sendChat(`There are ${users.length} users in the room.`);
break;
case 'staff':
const staff = bot.getStaff();
bot.sendChat(`There are ${staff.length} staff members in the room.`);
break;
case 'help':
bot.sendChat('Available commands: !ping, !info, !time, !users, !staff, !help');
break;
default:
// Unknown command
break;
}
}
// ========== Connection Functions ==========
function connect() {
console.log('Attempting to connect to room:', roomName);
bot.connect(roomName);
}
// ========== Event Listeners ==========
bot.on('connected', function(name) {
console.log('Connected to ' + name);
console.log('Bot is ready to respond to commands. Use ' + config.commandPrefix + 'help for available commands');
});
bot.on('disconnected', function(name) {
console.log('Disconnected from ' + name);
if (config.autoReconnect) {
console.log(`Attempting to reconnect in ${config.reconnectInterval / 1000} seconds...`);
setTimeout(connect, config.reconnectInterval);
}
});
bot.on('error', function(err) {
console.error('Error:', err);
});
// Chat message handler
bot.on(bot.events.chatMessage, function(data) {
console.log(data.user.username + ': ' + data.message);
// Handle commands
handleCommand(data);
// Handle mentions (when bot is called by name)
if (config.respondToMentions && data.user.username !== config.botName) {
// Use simple string methods instead of regex for more reliable detection
const message = data.message;
const lowerMessage = message.toLowerCase();
const botName = config.botName.toLowerCase();
// Check for mentions in several ways
const isMentioned =
lowerMessage.includes('@' + botName) || // @kuber
lowerMessage.startsWith(botName) || // starts with kuber
lowerMessage.includes(' ' + botName + ' ') || // kuber with spaces around
lowerMessage.endsWith(' ' + botName); // ends with kuber
console.log('Checking for mentions in message:', message, 'Mentioned:', isMentioned);
// Check if bot is mentioned
if (isMentioned) {
console.log(`Bot was mentioned by ${data.user.username}`);
// Generate a response based on the message content
let response;
const lowerMsg = data.message.toLowerCase();
// Check for question patterns
if (lowerMsg.includes('?')) {
if (lowerMsg.includes('how are you') || lowerMsg.includes('how\'s it going')) {
response = `I'm doing great, @${data.user.username}! How about you?`;
} else if (lowerMsg.includes('help')) {
response = `Need help, @${data.user.username}? Try using !help to see my commands.`;
} else if (lowerMsg.includes('what') && (lowerMsg.includes('song') || lowerMsg.includes('track') || lowerMsg.includes('playing'))) {
// Get current song info
const currentMedia = bot.getMedia();
if (currentMedia) {
response = `@${data.user.username}, we're listening to ${currentMedia.name} by ${currentMedia.artist || 'Unknown'}.`;
} else {
response = `@${data.user.username}, there's no track playing right now.`;
}
} else {
// Generic question response
response = `@${data.user.username}, that's a good question! Try using my commands with ${config.commandPrefix}help.`;
}
}
// Check for greeting patterns
else if (lowerMsg.includes('hello') || lowerMsg.includes('hi') || lowerMsg.includes('hey') || lowerMsg.includes('sup')) {
response = `Hey there, @${data.user.username}! How can I help you today?`;
}
// Check for thank you patterns
else if (lowerMsg.includes('thank') || lowerMsg.includes('thanks') || lowerMsg.includes('thx')) {
response = `You're welcome, @${data.user.username}! 😊`;
}
// Default response if no pattern matched
else {
const responses = [
`Yes, @${data.user.username}? How can I help you?`,
`I'm here, @${data.user.username}! Need something?`,
`Hey @${data.user.username}, what's up?`,
`@${data.user.username}, at your service! Try ${config.commandPrefix}help for commands.`
];
response = responses[Math.floor(Math.random() * responses.length)];
}
// Send the response with a small delay to seem more natural
setTimeout(() => {
bot.sendChat(response);
}, 1000 + Math.random() * 1000); // Random delay between 1-2 seconds
}
}
});
// User join handler
bot.on(bot.events.userJoin, function(data) {
console.log(`${data.user.username} joined the room`);
// Greet users when they join
if (config.greetUsers) {
bot.sendChat(`Welcome to the room, @${data.user.username}!`);
}
});
// User leave handler
bot.on(bot.events.userLeave, function(data) {
console.log(`${data.user.username} left the room`);
});
// Song change handler
bot.on(bot.events.roomPlaylistUpdate, function(data) {
if (!data.media) return;
console.log(`Now playing: ${data.media.name} by ${data.media.artist || 'Unknown'}`);
// Auto upvote songs if enabled
if (config.autoUpvote) {
setTimeout(() => {
bot.updub(function(err) {
if (err) console.error('Error upvoting:', err);
else console.log('Auto-upvoted current song');
});
}, 5000); // Wait 5 seconds before upvoting
}
});
// Connect to the room
connect();
});