-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.js
78 lines (75 loc) · 2.64 KB
/
telegram.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import axios from "axios";
import fs from 'fs'
class Telegram{
constructor(token, destinationChat) {
this.token = token
this.destinationChat = destinationChat
this.token = token
}
async callMethod(method, params){
try{
return await axios.post(`https://api.telegram.org/bot${this.token}/${method}`, params)
}catch (e){
console.error('Error with callMethod', e.response.data)
}
}
async sendText(text){
return await this.callMethod('sendMessage', {
"chat_id":this.destinationChat,
"text":text
})
}
async sendPhoto(text, photo){
return await this.callMethod('sendPhoto', {
"chat_id":this.destinationChat,
"caption":text,
photo
})
}
async sendMediaGroup(text, arrayOfPhotos){
let mediaTypes = arrayOfPhotos.map((url, key) => {
let media = {
type: 'photo',
media: url
}
return key === 0 ? {caption: text, ...media} : media
})
return await this.callMethod('sendMediaGroup', {
"chat_id":this.destinationChat,
"caption":text,
'media': mediaTypes
})
}
async processVkPosts(posts){
let request = 0
for (const post of posts) {
if(request++ % 14 === 0){
await this.sleep(1000)
}
console.log('Process', request)
if('photo' in post){
if(post['photo'].length > 1){
await this.sendMediaGroup(post['text'], post['photo'])
}else{
await this.sendPhoto(post['text'], post['photo'][0])
}
}else{
await this.sendText(post['text'])
}
}
}
async postPartGroup({length, posts}){
const chunkSize = Math.floor((7 / 100) * length )
const sliceEnd = chunkSize > length ? length : chunkSize
const processPosts = posts.slice(0, sliceEnd)
const otherPosts = posts.slice(sliceEnd, posts.length-1)
console.log('Proccess part, json len: ', length, 'real post: ', posts.length,' process post: ', processPosts.length, ' other posts: ', otherPosts.length, ' slice end: ', sliceEnd)
const resObject = {length, posts: otherPosts}
fs.writeFileSync('posts.txt', JSON.stringify(resObject));
await this.processVkPosts(processPosts)
}
sleep(ms){
return new Promise(r => setTimeout(r, ms));
}
}
export default Telegram