Last active
June 17, 2018 17:13
-
-
Save Toliak/30782f30fa093421d7bc543bbccdd762 to your computer and use it in GitHub Desktop.
Reads last VK message or amount of messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function vk_read(token, id) { | |
if (!typeof(token) === "string") throw "TypeError: Expected string at 1 argument"; | |
if (!typeof(id) === "number") throw "TypeError: Expected number at 2 argument"; | |
// Упрощение AJAX запроса | |
let ajax = function(method, url, data) { | |
let xhr = new XMLHttpRequest(); | |
// формируем запрос | |
let send = ""; | |
for (let i in data) { | |
if (!data.hasOwnProperty(i)) continue; | |
send += `${i}=${data[i]}&`; | |
} | |
xhr.open(method, `${url}?${send}`, false); | |
xhr.send(); | |
return xhr.response; | |
}; | |
// Распаковка ответа | |
let r_j = ajax("GET", "https://api.vk.com/method/messages.getDialogs", { | |
"access_token": token, | |
"v": "5.78", | |
"unread": 1, | |
"count": 1 | |
}); | |
let r = JSON.parse(r_j).response; | |
if (r.error) throw `VkError: ${r.error.error_msg}`; | |
// Обработка диалога | |
let message = r.items[0].message; | |
let chat_id = message.chat_id | |
if (!chat_id && message.user_id) { | |
return ajax("GET", "https://api.vk.com/method/messages.markAsRead", { | |
"access_token": token, | |
"v": "5.78", | |
"peer_id": message.user_id | |
}); | |
} else if (chat_id) { | |
ajax("GET", "https://api.vk.com/method/messages.markAsRead", { | |
"access_token": token, | |
"v": "5.78", | |
"peer_id": 2000000000 + chat_id | |
}); | |
return ajax("GET", "https://api.vk.com/method/messages.removeChatUser", { | |
"access_token": token, | |
"v": "5.78", | |
"chat_id": chat_id, | |
"user_id": id | |
}); | |
} else return false; | |
} | |
function vk_read_loop(token, id, amount) { | |
if (!typeof(amount) === "number") throw "TypeError: Expected number at 3 argument"; | |
const DELAY = 1003; | |
for (let i = 0; i < amount; i++) { | |
setTimeout(function(token, id) { | |
console.log(vk_read(token, id)); | |
}, DELAY * (i + 1), token, id); | |
} | |
} | |
// Для чтения 1 диалога / выхода из 1 беседы | |
vk_read("your_token", your_id); | |
// Для чтения amount сообщений | |
vk_read_loop("your_token", your_id, amount); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment