forked from Zain-ul-din/whatsapp-ai-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
230 lines (177 loc) · 8.27 KB
/
index.ts
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import { Client, Message } from 'whatsapp-web.js';
import { login, search, verifyOtp, type LoginResponse } from 'truecallerjs';
import { ENV } from './env'; // Ensure you import your environment variables from the env module
const client = new Client();
type BotCommand =
| "/start"
| "/login"
| "/installation_id"
| "/logout"
| "/stop"
| "/info"
| "/search";
client.on('qr', (qr) => {
// Generate and display the QR code
console.log('QR RECEIVED', qr);
});
client.on('ready', () => {
console.log('Client is ready!');
});
let waChatId: string | undefined;
client.on('message', async (message: Message) => {
const msgText = message.body;
// Initialize key-value storage (or use an alternative storage method)
const kv = new Map();
const chatIdKey: string = message.from;
waChatId = message.from;
type KvValue =
| { status: 'awaiting_phone_no' }
| {
status: 'awaiting_otp';
phoneNumber: string;
loginResponse: LoginResponse;
}
| { status: 'awaiting_installation_id' }
| {
status: 'awaiting_country_code';
installationId: string;
}
| {
status: 'logged_in';
installationId: string;
countryCode: string;
}
| { status: 'logged_out' };
const kvValue: KvValue = kv.get(chatIdKey) ?? { status: 'logged_out' };
if (msgText === '/start') {
if (kvValue.status === 'logged_out') reportEvent('/start');
return sendMessage(message.from, "You need to /login to Truecaller with your existing account to use the bot.\nOnly you will be using your own account to search the numbers.");
}
if (msgText === '/info') {
let status: string;
let installationId: string | undefined;
if (kvValue.status === 'logged_in') {
status = 'Logged in';
installationId = kvValue.installationId;
} else {
status = 'Logged out';
}
status = `*Status:* ${status}`;
installationId = installationId ? `\n[Installation ID:](https://github.com/sumithemmadi/truecallerjs#simple-example) \`${installationId}\`` : "";
const about = "[Source Code](https://github.com/ni554n/truecallerjs_bot) *\\|* [anissan\\.com](https://anissan.com)";
return sendMessage(message.from, `${status}${installationId}\n\n${about}`);
}
//#region Command: /installation_id
if (msgText === '/installation_id') {
if (kvValue.status === 'logged_in') {
return sendMessage(message.from, "You are already logged in.\n/logout first and then try again.");
}
kv.set(chatIdKey, { status: 'awaiting_installation_id' } satisfies KvValue);
return sendMessage(message.from, "_installation\\_id_ is the final auth token generated after a successful truecaller login\\. If you know how to retrieve it from an already logged in device, you can directly set it here without going through the login process again\\. Enter the installation ID:", true);
}
if (kvValue.status === 'awaiting_installation_id' && !msgText.startsWith('/')) {
const installationId = msgText;
kv.set(chatIdKey, { status: 'awaiting_country_code', installationId } satisfies KvValue);
reportEvent('/installation_id');
return sendMessage(message.from, "Enter your phone number's 2\\-letter [ISO country code](https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes):", true);
}
if (kvValue.status === 'awaiting_country_code' && !msgText.startsWith('/')) {
const countryCode = msgText;
kv.set(chatIdKey, { status: 'logged_in', installationId: kvValue.installationId, countryCode } satisfies KvValue);
return sendMessage(message.from, "Successfully logged in to Truecaller.\nYou can now search any number.");
}
//#endregion /installation_id
if (msgText === '/logout') {
kv.delete(chatIdKey);
reportEvent('/logout');
return sendMessage(message.from, "You've been logged out");
}
//#region Command: /login
if (msgText === '/login') {
if (kvValue.status === 'logged_in') {
return sendMessage(message.from, "You are already logged in. /logout first and then try /login again.");
}
kv.set(chatIdKey, { status: 'awaiting_phone_no' } satisfies KvValue);
return sendMessage(message.from, "Enter your Truecaller account phone no. in international (+19...) format:");
}
if (kvValue.status === 'awaiting_phone_no' && !msgText.startsWith('/')) {
const phoneNumber = msgText;
if (!phoneNumber?.startsWith('+')) {
return sendMessage(message.from, "Phone number should be in international format like +91...");
}
const responseBody = await login(phoneNumber);
if (responseBody.status === 6 || responseBody.status === 5) {
return sendMessage(message.from, "You have exceeded the limit of verification attempts.\nPlease try again after some time (up to 24h).");
}
if (!(responseBody.status === 1 || responseBody.status === 9 || responseBody.message === 'Sent')) {
return sendMessage(message.from, responseBody.message);
}
kv.set(chatIdKey, { status: 'awaiting_otp', phoneNumber, loginResponse: responseBody } satisfies KvValue);
return sendMessage(message.from, "Enter the OTP from SMS or WhatsApp:");
}
if (kvValue.status === 'awaiting_otp' && !msgText.startsWith('/')) {
const otp = msgText;
const otpResponse = (await verifyOtp(kvValue.phoneNumber, kvValue.loginResponse, otp)) as Record<string, unknown>;
if (otpResponse.suspended) {
return sendMessage(message.from, "Your account has been suspended by Truecaller.\nTry to /login with another number.");
}
if (otpResponse.status === 11) {
return sendMessage(message.from, "Invalid OTP");
}
if (otpResponse.status === 7) {
return sendMessage(message.from, "Retries limit exceeded");
}
if (!otpResponse.installationId) {
return sendMessage(message.from, (otpResponse.message as string) || "Unknown error. Try again.");
}
kv.set(chatIdKey, { status: 'logged_in', installationId: otpResponse.installationId as string, countryCode: kvValue.loginResponse.parsedCountryCode } satisfies KvValue);
reportEvent('/login');
return sendMessage(message.from, "Successfully logged in to Truecaller.\nYou can now search any number.");
}
//#endregion /login
if (kvValue.status !== 'logged_in') {
return sendMessage(message.from, "Please /login first before searching for a number");
}
const searchData = {
number: msgText,
countryCode: kvValue.countryCode,
installationId: kvValue.installationId,
};
const searchResult = await search(searchData);
// Handle Axios error
if (searchResult.json() instanceof Error) {
const error = searchResult.json() as any;
const { status = "", message: apiMessage = "" } = error.response?.data ?? {};
if (status === 40101 || status === 42601) {
return sendMessage(message.from, `Truecaller responded with an account error: \`${apiMessage}\`\\. Make sure your account is still valid by logging into the official app. Try to /login here again after checking.`, true);
}
throw searchResult.json();
}
reportEvent('/search');
return sendMessage(message.from, searchResult.getName());
});
function sendMessage(chatId: string, text: string, formatted = false) {
client.sendMessage(chatId, text);
}
function reportEvent(eventName: BotCommand): void {
const EVENT_PING_URL = ENV.EVENT_PING_URL;
const EVENT_PING_PROJECT_ID = ENV.EVENT_PING_PROJECT_ID;
if (!(EVENT_PING_URL && EVENT_PING_PROJECT_ID)) {
console.warn("Optional env vars 'EVENT_PING_*' are not set.");
return;
}
fetch(EVENT_PING_URL, {
method: 'POST',
headers: {
'User-Agent': 'whatsapp (truecallerjs;)',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'event',
payload: {
website: ENV.EVENT_PING_PROJECT_ID,
url: eventName,
},
}),
}).catch(console.error);
}