Real-time Integration

Setting up Webhooks for Vote Events

Learn how to receive real-time notifications when users vote for your bot or server. Implement reward systems, analytics tracking, and user engagement features with webhooks.

Setup Overview

Get webhooks working in 4 simple steps

1

Set Webhook URL

Configure endpoint

2

Add Authorization

Secure with auth token

3

Handle Requests

Process vote events

4

Test & Deploy

Verify webhook works

Prerequisites

Standard Webhooks

  • A publicly accessible web server (HTTP or HTTPS)
  • SSL certificate recommended for security
  • Custom code to handle webhook data

Discord Webhooks (Easy Setup)

  • No server setup required
  • Discord channel with webhook URL
  • Automatic vote announcements

Security Recommendation

While HTTP endpoints are supported for development and testing, we strongly recommend using HTTPS in production to protect your webhook data and authorization tokens from interception.

Need a server?

Consider using services like Railway, Heroku, DigitalOcean, or AWS to host your webhook endpoint. Many offer free tiers perfect for webhook handling and provide automatic HTTPS.Or use Discord webhooks for a simpler no-server solution!

Discord Webhook Setup (Simple Option)

No Server Required!

If you don't want to set up a web server, you can use Discord webhooks instead! Rank.top will automatically detect Discord webhook URLs and send formatted messages directly to your Discord channel when users vote.

What you get:

  • Automatic vote announcements in your Discord channel
  • User mentions and vote counts
  • Rank.top branding and logo
  • No coding or server management required

Example message:

Rank.topRank.topToday at 12:34 PM

@username has cast the 1,234th vote for @YourBot! 🎉

How to set up a Discord webhook:

  1. 1

    Go to your Discord server

    Navigate to the channel where you want vote announcements

  2. 2

    Open channel settings

    Right-click the channel → Edit Channel → Integrations → Webhooks

  3. 3

    Create a new webhook

    Click "New Webhook" and give it a name (e.g., "Vote Notifications")

  4. 4

    Copy the webhook URL

    It will look like: https://discord.com/api/webhooks/...

  5. 5

    Paste in Rank.top settings

    Go to your bot/server edit page → Webhooks tab → paste the Discord webhook URL

  6. 6

    Test it!

    Use the test button to see a vote announcement in your Discord channel

That's it!

No authorization token needed for Discord webhooks. Rank.top automatically detects Discord webhook URLs and sends appropriately formatted messages.

Standard Webhook Data Format

This section applies to standard webhooks only

Discord webhooks are handled automatically by Rank.top. If you're using a Discord webhook URL, you can skip this section - no coding required!

Request Structure

When a user votes, Rank.top sends a POST request to your webhook URL with this structure:

Headers

Content-Type: application/json
Authorization: your-auth-token

Example JSON Body

{
"type": "vote",
"target_type": "bot", // or "server"
"target_id": "123456789012345678",
"is_test": false,
"user_id": "123456789012345678",
"timestamp": 1710504000,
"guild_id": "987654321098765432"
}

Field Descriptions

Authorizationheader

Your webhook authentication token (sent in request headers)

typestring

Always "vote" for vote events

target_typestring

Always "bot" for bot webhooks, "server" for server webhooks

target_idstring

The ID of the bot or server that was voted for

is_testboolean

True for test webhooks, false for real votes

user_idstring

Discord ID of the user who voted

timestampnumber

Unix timestamp when the vote occurred (in seconds)

guild_idstring?

Discord guild ID where bot was voted from (requires search param ?guildId=guildId in the URL)

Implementation Examples

🟢

Node.js (Express)

const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhook/vote', (req, res) => {
const { type, user_id, is_test, timestamp, guild_id } = req.body;
const authorization = req.headers['authorization'];

// Verify authorization token
if (authorization !== process.env.WEBHOOK_TOKEN) {
return res.status(401).json({ error: 'Unauthorized' });
}

// Handle test webhooks
if (is_test) {
console.log('Test webhook received successfully!');
return res.status(200).json({ success: true });
}

// Process the vote
if (type === 'vote') {
console.log(`User ${user_id} voted! Guild: ${guild_id || 'N/A'}`);

// Add your reward logic here
giveVoteRewards(user_id, guild_id);
}

res.status(200).json({ success: true });
});

async function giveVoteRewards(userId, guildId) {
// Your reward implementation
// e.g., database updates, Discord API calls, etc.
}

app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
🐍

Python (Flask)

from flask import Flask, request, jsonify
import os
import time

app = Flask(__name__)

@app.route('/webhook/vote', methods=['POST'])
def handle_vote():
data = request.get_json()
authorization = request.headers.get('Authorization')

# Verify authorization
if authorization != os.getenv('WEBHOOK_TOKEN'):
return jsonify({'error': 'Unauthorized'}), 401

# Handle test webhooks
if data.get('is_test'):
print('Test webhook received successfully!')
return jsonify({'success': True})

# Process vote event
if data.get('type') == 'vote':
user_id = data.get('user_id')
guild_id = data.get('guild_id')

print(f"User {user_id} voted! Guild: {guild_id or 'N/A'}")

# Add your reward logic here
give_vote_rewards(user_id, guild_id)

return jsonify({'success': True})

def give_vote_rewards(user_id, guild_id):
# Your reward implementation
pass

if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
🤖

Discord.js Bot Integration

const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const express = require('express');

const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers]
});

const app = express();
app.use(express.json());

// Webhook endpoint
app.post('/webhook/vote', async (req, res) => {
const { type, user_id, is_test, guild_id } = req.body;
const authorization = req.headers['authorization'];

if (authorization !== process.env.WEBHOOK_TOKEN) {
return res.status(401).json({ error: 'Unauthorized' });
}

if (type === 'vote' && !is_test) {
try {
const user = await client.users.fetch(user_id);

// Give rewards
await giveVoteRewards(user_id, guild_id);

// Send thank you message
const Embed = new EmbedBuilder()
.setTitle('🎉 Thanks for voting!')
.setDescription('You received 100 coins as a reward!')
.setColor('#00ff00')
.setTimestamp();

await user.send({ embeds: [Embed] });
} catch (error) {
console.error('Error processing vote:', error);
}
}

res.status(200).json({ success: true });
});

async function giveVoteRewards(userId, guildId) {
// Example: Add coins to database
// await db.users.updateOne(
// { discordId: userId },
// { $inc: { coins: 100 } }
// );
}

client.login(process.env.BOT_TOKEN);
app.listen(3000);

Configuration Steps

Setting up in Rank.top

  1. 1

    Navigate to your bot/server settings

    Go to your dashboard and click "Edit" on your listing

  2. 2

    Go to the Webhooks tab

    Find the webhook configuration section in the sidebar

  3. 3

    Enter your webhook URL

    Choose one of these options:

    Standard webhooks:

    https://yourserver.com/webhook/votehttp://your-ip-address:port/webhook/vote

    Discord webhooks:

    https://discord.com/api/webhooks/1234567890/abc...
  4. 4

    Set an authorization token (optional)

    For standard webhooks: Use a secure random string and store it in your environment variables.
    For Discord webhooks: Leave this blank - not needed!

  5. 5

    Test your webhook

    Use the built-in test button to verify everything works

Security Best Practices

Always verify authorization headers

Check the Authorization header against your stored token to prevent unauthorized requests.

HTTPS is strongly recommended

While HTTP endpoints are supported, HTTPS ensures secure data transmission and protects against eavesdropping.

Implement timeout handling

Respond within 10 seconds to avoid webhook retries and potential duplicates.

Handle retry logic gracefully

Failed webhooks are retried up to 6 times with increasing intervals.

Troubleshooting

Webhook not receiving requests

  • Verify your webhook URL is publicly accessible
  • Check that your server is running and listening on the correct port
  • Ensure your firewall allows incoming connections
  • Test with the built-in webhook tester in your bot settings

Getting 401 Unauthorized errors

  • Verify the authorization token matches exactly
  • Check for extra whitespace or special characters in your token
  • Ensure you're reading the Authorization header (not the request body)
  • Make sure your environment variables are loaded correctly

Receiving duplicate vote events

  • Implement idempotency using the timestamp field
  • Respond with 200 status code quickly to prevent retries
  • Check your server logs for timeout issues

Next Steps