1 | const { pluck, last } = require('ramda')
|
2 | const { inputField } = require('./fixtures')
|
3 |
|
4 | const telegram = require('./init')
|
5 |
|
6 | const getChat = async () => {
|
7 | const dialogs = await telegram('messages.getDialogs', {
|
8 | offset : 0,
|
9 | limit : 50,
|
10 | offset_peer: { _: 'inputPeerEmpty' }
|
11 | })
|
12 | const { chats } = dialogs
|
13 | const selectedChat = await selectChat(chats)
|
14 |
|
15 | return selectedChat
|
16 | }
|
17 |
|
18 | const chatHistory = async chat => {
|
19 | const max = 400
|
20 | const limit = 100
|
21 | let offset = 0
|
22 | let full = [],
|
23 | messages = []
|
24 | do {
|
25 | const history = await telegram('messages.getHistory', {
|
26 | peer: {
|
27 | _ : 'inputPeerChannel',
|
28 | channel_id : chat.id,
|
29 | access_hash: chat.access_hash
|
30 | },
|
31 | max_id: offset,
|
32 | offset: -full.length,
|
33 | limit
|
34 | })
|
35 | messages = history.messages.filter(filterLastDay)
|
36 | full = full.concat(messages)
|
37 | messages.length > 0 && (offset = messages[0].id)
|
38 | messages.length > 0 && console.log(offset, messages[0].id)
|
39 | } while (messages.length === limit && full.length < max)
|
40 | printMessages(full)
|
41 | return full
|
42 | }
|
43 |
|
44 | const filterLastDay = ({ date }) => new Date(date*1e3) > dayRange()
|
45 |
|
46 | const dayRange = () => Date.now() - new Date(86400000*4)
|
47 |
|
48 | const selectChat = async (chats) => {
|
49 | const chatNames = pluck('title', chats)
|
50 | console.log('Your chat list')
|
51 | chatNames.map((name, id) => console.log(`${id} ${name}`))
|
52 | console.log('Select chat by index')
|
53 | const chatIndex = await inputField('index')
|
54 | return chats[+chatIndex]
|
55 | }
|
56 |
|
57 | const filterUsersMessages = ({ _ }) => _ === 'message'
|
58 |
|
59 | const formatMessage = ({ message, date, from_id }) => {
|
60 | const dt = new Date(date*1e3)
|
61 | const hours = dt.getHours()
|
62 | const mins = dt.getMinutes()
|
63 | return `${hours}:${mins} [${from_id}] ${message}`
|
64 | }
|
65 |
|
66 | const printMessages = messages => {
|
67 | const filteredMsg = messages.filter(filterUsersMessages)
|
68 | const formatted = filteredMsg.map(formatMessage)
|
69 | formatted.forEach(e => console.log(e))
|
70 | return formatted
|
71 | }
|
72 |
|
73 | module.exports = {
|
74 | getChat,
|
75 | chatHistory
|
76 | } |
\ | No newline at end of file |