Guides

Advanced Bot Examples

Beyond sending basic messages, robust ModVC bots often need to integrate with our real-time Presence and Audit Log systems. Here are detailed examples of implementing these patterns in Node.js.

Fetching Server Presence

To sync your bot's internal state with the live voice channels, you can query the presence endpoint.

sync_presence.js
const fetchServerPresence = async (serverId) => {
  try {
    const response = await fetch(`https://api.modvc.org/v1/servers/${serverId}/presence`, {
      method: 'GET',
      headers: {
        'Authorization': `Bot ${process.env.BOT_TOKEN}`
      }
    });

    if (!response.ok) {
      if (response.status === 429) {
        console.warn("Rate limited! Backing off...");
        return null;
      }
      throw new Error(`API returned ${response.status}`);
    }

    const { online_users } = await response.json();
    console.log(`Currently ${online_users.length} users in voice.`);
    return online_users;
  } catch (err) {
    console.error("Failed to fetch presence:", err.message);
  }
};

Writing to Audit Logs

When your bot performs an administrative action (like kicking a user or changing a role), it should log the action to the server's audit log for transparency.

log_action.js
const createAuditEntry = async (serverId, actionType, targetId, reason) => {
  try {
    const response = await fetch(`https://api.modvc.org/v1/servers/${serverId}/audit-logs`, {
      method: 'POST',
      headers: {
        'Authorization': `Bot ${process.env.BOT_TOKEN}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        action: actionType, // e.g. "MEMBER_KICK"
        target_id: targetId,
        reason: reason
      })
    });

    if (response.ok) {
      console.log("Successfully logged action to Audit Logs.");
    }
  } catch (err) {
    console.error("Audit log creation failed:", err.message);
  }
};