Check if a new fiverr message is received jquery
Fiverr doesn't provide a direct API to check for new messages in real-time. However, you can use the Fiverr API to fetch the latest messages and then compare them with the previous messages to detect new ones.
Here's a step-by-step guide to achieve this using jQuery and the Fiverr API:
Step 1: Get your Fiverr API token
- Go to the Fiverr API dashboard and create an account if you don't have one.
- Generate an API token by clicking on the "Generate API Token" button.
- Note down the API token, you'll need it later.
Step 2: Set up the Fiverr API
- Create a new JavaScript file (e.g.,
fiverr-api.js
) and add the following code:const apiUrl = 'https://api.fiverr.com/v2'; const apiKey = 'YOUR_API_TOKEN_HERE'; // Replace with your API token const apiSecret = 'YOUR_API_SECRET_HERE'; // Replace with your API secret const apiVersion = 'v2';
const headers = {
'Authorization': Bearer ${apiKey}
,
'Content-Type': 'application/json'
};
function getMessages() {
const url = ${apiUrl}/messages
;
const params = {
'user_id': 'YOUR_FIVERR_USERNAME_HERE', // Replace with your Fiverr username
'limit': 10 // Fetch the latest 10 messages
};
return $.ajax({ url: url, method: 'GET', headers: headers, data: params }); }
**Step 3: Check for new messages**
1. Create a new JavaScript file (e.g., `fiverr-new-messages.js`) and add the following code:
```javascript
const fiverrApi = require('./fiverr-api');
function checkForNewMessages() {
fiverrApi.getMessages().then((response) => {
const messages = response.data.messages;
const previousMessages = localStorage.getItem('fiverr-messages')? JSON.parse(localStorage.getItem('fiverr-messages')) : [];
const newMessages = messages.filter((message) =>!previousMessages.includes(message.id));
if (newMessages.length > 0) {
console.log('New messages received:', newMessages);
// Handle new messages here (e.g., display a notification)
}
localStorage.setItem('fiverr-messages', JSON.stringify(messages.map((message) => message.id)));
});
}
setInterval(checkForNewMessages, 10000); // Check for new messages every 10 seconds
How it works
- The
fiverr-api.js
file sets up the Fiverr API with your API token and secret. - The
getMessages()
function fetches the latest messages using the Fiverr API. - The
checkForNewMessages()
function checks if there are new messages by comparing the latest messages with the previous messages stored in local storage. - If new messages are found, it logs them to the console and you can handle them as needed (e.g., display a notification).
- The
setInterval()
function callscheckForNewMessages()
every 10 seconds to check for new messages.
Note: This code is just a starting point, and you'll need to modify it to fit your specific use case. Additionally, be aware that Fiverr's API has usage limits, so make sure to check their documentation for more information.