webmaxsocket 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/example-sms.js ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Пример авторизации по SMS (IOS/ANDROID)
3
+ *
4
+ * Использование:
5
+ * node example-sms.js
6
+ * node example-sms.js +79001234567 # с номером в аргументе
7
+ */
8
+
9
+ const readline = require('readline');
10
+ const { WebMaxClient } = require('./index');
11
+
12
+ function ask(question) {
13
+ const rl = readline.createInterface({
14
+ input: process.stdin,
15
+ output: process.stdout
16
+ });
17
+ return new Promise((resolve) => {
18
+ rl.question(question, (answer) => {
19
+ rl.close();
20
+ resolve(answer.trim());
21
+ });
22
+ });
23
+ }
24
+
25
+ async function main() {
26
+ // Получаем номер телефона из аргумента или запрашиваем
27
+ let phone = process.argv[2];
28
+
29
+ if (!phone) {
30
+ phone = await ask('📱 Введите номер телефона (+79001234567): ');
31
+ }
32
+
33
+ // Валидация номера
34
+ if (!/^\+?\d{10,15}$/.test(phone.replace(/\s/g, ''))) {
35
+ console.error('❌ Неверный формат номера телефона');
36
+ process.exit(1);
37
+ }
38
+
39
+ console.log('\n🚀 Запуск клиента с SMS авторизацией...\n');
40
+
41
+ // Создаем клиент с IOS deviceType для SMS авторизации
42
+ const client = new WebMaxClient({
43
+ name: 'sms_session',
44
+ deviceType: 'IOS', // Обязательно для SMS авторизации
45
+ debug: process.env.DEBUG === '1'
46
+ });
47
+
48
+ // Обработчик запуска
49
+ client.onStart(async () => {
50
+ if (client.me) {
51
+ console.log('\n📋 ДАННЫЕ ПОЛЬЗОВАТЕЛЯ:');
52
+ console.log('─'.repeat(40));
53
+ console.log(`👤 Имя: ${client.me.fullname || client.me.firstname}`);
54
+ console.log(`🆔 ID: ${client.me.id}`);
55
+ console.log(`📱 Телефон: +${client.me.phone || '—'}`);
56
+ }
57
+
58
+ try {
59
+ const chats = await client.getChats();
60
+ console.log(`\n📂 Диалогов: ${chats.length}`);
61
+ } catch (e) {
62
+ console.log('⚠️ Не удалось загрузить диалоги:', e.message);
63
+ }
64
+ });
65
+
66
+ // Обработчик сообщений
67
+ client.onMessage(async (message) => {
68
+ if (message.senderId === client.me?.id) return;
69
+ console.log(`\n💬 ${message.getSenderName()}: ${message.text}`);
70
+
71
+ await message.reply({
72
+ text: 'Автоответ: сообщение получено!',
73
+ cid: Date.now()
74
+ });
75
+ console.log('✅ Отправлен автоответ');
76
+ });
77
+
78
+ client.onError((err) => console.error('❌', err.message));
79
+
80
+ try {
81
+ // Подключаемся
82
+ await client.connect();
83
+
84
+ // Проверяем есть ли сохраненный токен
85
+ const savedToken = client.session.get('token');
86
+
87
+ if (savedToken) {
88
+ console.log('✅ Найдена сохраненная сессия, вход по токену...\n');
89
+ client._token = savedToken;
90
+ await client.sync();
91
+ client.isAuthorized = true;
92
+ } else {
93
+ // SMS авторизация
94
+ console.log('📱 Требуется SMS авторизация\n');
95
+ const authSession = await client.authorizeBySMS(phone);
96
+
97
+ // Запрашиваем код
98
+ const code = await ask('\n📲 Введите код из SMS (6 цифр): ');
99
+
100
+ if (!/^\d{6}$/.test(code)) {
101
+ console.error('❌ Неверный формат кода');
102
+ process.exit(1);
103
+ }
104
+
105
+ // Отправляем код и завершаем авторизацию
106
+ await authSession.sendCode(code);
107
+ }
108
+
109
+ // Запускаем обработчики start
110
+ await client.triggerHandlers(client.handlers.START);
111
+
112
+ console.log('\n✅ Клиент запущен успешно!');
113
+ console.log('🤖 Бот работает (Ctrl+C — выход)\n');
114
+
115
+ } catch (error) {
116
+ console.error('❌ Ошибка:', error.message);
117
+ process.exit(1);
118
+ }
119
+ }
120
+
121
+ process.on('SIGINT', () => {
122
+ console.log('\n\n👋 Завершение работы...');
123
+ console.log('\n💝 Нравится библиотека? Поддержите разработку:');
124
+ console.log(' USDT (TRC20): TXfs1iVbp2aLd3rbc4cenVzMoTevP5RbBE');
125
+ process.exit(0);
126
+ });
127
+
128
+ main().catch((error) => {
129
+ console.error('❌ Критическая ошибка:', error);
130
+ process.exit(1);
131
+ });
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Пример входа по токену (token auth)
3
+ *
4
+ * Конфиг: config/default.json — token, agent
5
+ * node example-token.js
6
+ * node example-token.js other — config/other.json
7
+ * Вариант 3 — TOKEN в env: TOKEN="..." node example-token.js
8
+ */
9
+
10
+ const { WebMaxClient } = require('./index');
11
+
12
+ const CONFIG_NAME = process.argv[2] || process.env.CONFIG || 'default';
13
+
14
+ async function main() {
15
+ let client;
16
+ try {
17
+ client = new WebMaxClient({
18
+ name: 'token_session',
19
+ configPath: CONFIG_NAME,
20
+ token: process.env.TOKEN,
21
+ saveToken: true,
22
+ debug: process.env.DEBUG === '1'
23
+ });
24
+ } catch (e) {
25
+ console.error('❌ Не удалось загрузить конфиг:', e.message);
26
+ console.error(' Создайте config/default.json (см. config/example.json)');
27
+ process.exit(1);
28
+ }
29
+
30
+ if (!client._providedToken || client._providedToken.length < 50) {
31
+ console.error('❌ Укажите токен в config/default.json (поле "token")');
32
+ console.error(' Или: TOKEN="ваш_токен" node example-token.js');
33
+ process.exit(1);
34
+ }
35
+
36
+ client.onStart(async () => {
37
+ if (client.me) {
38
+ console.log('\n📋 ДАННЫЕ ПОЛЬЗОВАТЕЛЯ:');
39
+ console.log('─'.repeat(40));
40
+ console.log(`👤 Имя: ${client.me.fullname || client.me.firstname}`);
41
+ console.log(`🆔 ID: ${client.me.id}`);
42
+ console.log(`📱 Телефон: +${client.me.phone || '—'}`);
43
+ console.log(`🖼 Avatar: ${client.me.avatar ? 'есть' : 'нет'}`);
44
+ }
45
+
46
+ try {
47
+ const chats = await client.getChats();
48
+ console.log('\n📂 ДИАЛОГИ (' + chats.length + '):');
49
+ console.log('─'.repeat(40));
50
+ chats.slice(0, 15).forEach((chat, i) => {
51
+ const chatId = chat.id ?? chat.chatId;
52
+ const title = chat.title || chat.name || `Chat ${chatId}`;
53
+ const lastMsg = chat.lastMessage?.text || chat.lastMessage?.message || '—';
54
+ const preview = String(lastMsg).slice(0, 40) + (String(lastMsg).length > 40 ? '…' : '');
55
+ console.log(`${i + 1}. [${chatId}] ${title}`);
56
+ console.log(` Последнее: ${preview}`);
57
+ });
58
+ if (chats.length > 15) console.log(` ... и ещё ${chats.length - 15}`);
59
+
60
+ if (chats.length > 0) {
61
+ const firstChat = chats[0];
62
+ const firstChatId = firstChat.id ?? firstChat.chatId;
63
+ const history = await client.getHistory(firstChatId, Date.now(), 5, 0);
64
+ console.log(`\n💬 Последние 5 сообщений в «${firstChat.title || firstChat.id}»:`);
65
+ console.log('─'.repeat(40));
66
+ history.reverse().forEach((m, i) => {
67
+ const from = m.senderId === client.me?.id ? 'Вы' : `User ${m.senderId}`;
68
+ console.log(` ${i + 1}. ${from}: ${String(m.text || '').slice(0, 50)}`);
69
+ });
70
+ }
71
+ console.log('\n');
72
+ } catch (e) {
73
+ console.log('⚠️ Не удалось загрузить диалоги:', e.message);
74
+ }
75
+ });
76
+
77
+ client.onMessage(async (message) => {
78
+ if (message.senderId === client.me?.id) return;
79
+ console.log(`💬 ${message.getSenderName()}: ${message.text}`);
80
+ await message.reply({ text: 'Получено!', cid: Date.now() });
81
+ });
82
+
83
+ client.onError(async (err) => console.error('❌', err.message));
84
+
85
+ try {
86
+ await client.start();
87
+ console.log('🤖 Токен-авторизация успешна. Бот работает.\n');
88
+ } catch (error) {
89
+ console.error('❌ Ошибка:', error.message);
90
+ process.exit(1);
91
+ }
92
+ }
93
+
94
+ process.on('SIGINT', () => {
95
+ console.log('\n\n👋 Завершение работы...');
96
+ console.log('\n💝 Нравится библиотека? Поддержите разработку:');
97
+ console.log(' USDT (TRC20): TXfs1iVbp2aLd3rbc4cenVzMoTevP5RbBE');
98
+ process.exit(0);
99
+ });
100
+ main().catch(console.error);
package/example.js CHANGED
@@ -113,6 +113,8 @@ async function main() {
113
113
  // Обработка завершения
114
114
  process.on('SIGINT', async () => {
115
115
  console.log('\n\n👋 Завершение работы...');
116
+ console.log('\n💝 Нравится библиотека? Поддержите разработку:');
117
+ console.log(' USDT (TRC20): TXfs1iVbp2aLd3rbc4cenVzMoTevP5RbBE');
116
118
  process.exit(0);
117
119
  });
118
120
 
package/index.js CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  const WebMaxClient = require('./lib/client');
9
+ const { MaxSocketTransport } = require('./lib/socketTransport');
9
10
  const { User, Message, ChatAction } = require('./lib/entities');
10
11
  const { ChatActions, EventTypes, MessageTypes } = require('./lib/constants');
11
12
  const { Opcode, getOpcodeName } = require('./lib/opcodes');
@@ -13,6 +14,7 @@ const { UserAgentPayload } = require('./lib/userAgent');
13
14
 
14
15
  module.exports = {
15
16
  WebMaxClient,
17
+ MaxSocketTransport,
16
18
  User,
17
19
  Message,
18
20
  ChatAction,