-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
133 lines (117 loc) · 4.49 KB
/
Copy pathindex.js
File metadata and controls
133 lines (117 loc) · 4.49 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
require('dotenv').config();
const { TelegramClient, Api } = require("telegram");
const { StringSession } = require("telegram/sessions");
const { NewMessage } = require('telegram/events');
const readline = require("readline");
const axios = require("axios");
// local imports
const { getMessageUser } = require('./users');
const apiId = Number(process.env.API_ID);
const apiHash = process.env.API_HASH;
const stringSession = new StringSession(process.env.API_SESSION);
// Create a readline interface for user input
// Note: Make sure to set the API_SESSION environment variable with your session string
// If you don't have a session string, you can leave it empty and it will be generated after the first run
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
(async () => {
console.log("Loading interactive example...");
// Initialize the Telegram client with the session string
// If you don't have a session string, it will prompt you to log in
// and generate a new session string for you.
const client = new TelegramClient(stringSession, apiId, apiHash, {
connectionRetries: 5,
});
await client.start({
phoneNumber: async () =>
new Promise((resolve) =>
rl.question("Please enter your number: ", resolve)
),
password: async () =>
new Promise((resolve) =>
rl.question("Please enter your password: ", resolve)
),
phoneCode: async () =>
new Promise((resolve) =>
rl.question("Please enter the code you received: ", resolve)
),
onError: (err) => {
console.error('Error catched!');
console.error(err);
},
});
// Save the session string to the environment variable for future use (on the first run only)
// client.session.save();
console.log("You should now be connected!");
// TODO: move to the airtable
const chats = [
// TODO: figure out how to listen for subchats
// Here you can add the chat IDs you want to listen to
// { name: 'Name of the channel', id: 'Channel ID, e.g. -1234567891234' },
];
function runWebhook(data) {
// Check if the data contains a message and if it has a valid length.
// Here you might want to customize it prior to your requirements.
// If the message is too short, we skip sending it to the webhook.
if (data.message && data.message.message && data.message.message.length < 100) {
console.log('Message is too short:');
console.log(data.message);
return;
}
// Prepare the data to be sent to the webhook (automation).
axios.post(process.env.MAKE_COM_WEBHOOK_URL, data)
.then(result => {
console.log('Webhook data has been successfully transfered!', result.status, result.statusText);
})
.catch(error => {
console.error('Webhook data has been failed to transfer:', error);
});
}
// Listening for new messages
const callbackFunction= async (event) => {
const message = event.message;
const cache = {};
// If the message is empty, we skip it
if (message.fromId && message.fromId.userId) {
cache.sender = await getMessageUser(client, message);
}
if (message && message.peerId && message.peerId.channelId) {
try {
// If the message is from a channel, get the channel information
// Note: peerId can be a channel or a user, so we use getEntity to fetch the correct type
const channel = await client.getEntity(message.peerId);
// TODO: if no cache.sender provided -> the message is sent by Channel
// we treat Channel as a user and have to parse channel photo appropriately
// and make it a sender eventually
cache.message = message;
cache.channel = channel;
runWebhook(cache);
} catch (err) {
console.error("Failed to get channel information:", err);
}
} else if (message && message.peerId) {
try {
// If the message is from a chat, get the chat information
// Note: peerId can be a chat or a user, so we use getEntity to fetch the correct type
const chat = await client.getEntity(message.peerId);
cache.message = message;
cache.chat = chat;
runWebhook(cache);
} catch (err) {
console.error("Failed to get channel information:", err);
}
} else {
console.log('NO PEER ID!!!');
console.log(event.message);
}
}
client.addEventHandler(
callbackFunction,
new NewMessage({
incoming: true,
chats: chats.map(chat => chat.id),
})
);
})();