@alemonjs/telegram 2.1.0-alpha.0 → 2.1.0-alpha.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/lib/config.d.ts CHANGED
@@ -1,3 +1,11 @@
1
- declare const platform = "telegram";
2
-
3
- export { platform };
1
+ export declare const platform = "telegram";
2
+ export type Options = {
3
+ token: string;
4
+ base_api_url?: string;
5
+ request_url?: string;
6
+ proxy?: string;
7
+ master_key?: string[];
8
+ master_id?: string[];
9
+ };
10
+ export declare const getTGConfig: () => Options;
11
+ export declare const getMaster: (UserId: string) => readonly [boolean, string];
package/lib/hook.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { EventKeys, Events } from 'alemonjs';
2
+ import API from 'node-telegram-bot-api';
2
3
  import TelegramClient from 'node-telegram-bot-api';
3
-
4
4
  type MAP = {
5
5
  'message.create': TelegramClient.Message;
6
6
  'private.message.create': undefined;
@@ -10,8 +10,8 @@ type MAP = {
10
10
  'message.delete': undefined;
11
11
  'message.reaction.add': undefined;
12
12
  'message.reaction.remove': undefined;
13
- 'channal.create': undefined;
14
- 'channal.delete': undefined;
13
+ 'channel.create': undefined;
14
+ 'channel.delete': undefined;
15
15
  'guild.join': undefined;
16
16
  'guild.exit': undefined;
17
17
  'member.add': undefined;
@@ -21,17 +21,6 @@ type MAP = {
21
21
  'private.friend.add': undefined;
22
22
  'private.guild.add': undefined;
23
23
  };
24
- /**
25
- *
26
- * @param event
27
- * @returns
28
- */
29
- declare const useValue: <T extends EventKeys>(event: Events[T]) => readonly [MAP[T]];
30
- /**
31
- *
32
- * @param event
33
- * @returns
34
- */
35
- declare const useClient: <T extends EventKeys>(event: Events[T]) => readonly [TelegramClient, MAP[T]];
36
-
37
- export { useClient, useValue };
24
+ export declare const useValue: <T extends EventKeys>(event: Events[T]) => readonly [MAP[T]];
25
+ export declare const useClient: <T extends EventKeys>(event: Events[T]) => readonly [API, MAP[T]];
26
+ export {};
package/lib/hook.js CHANGED
@@ -1,20 +1,10 @@
1
1
  import { createEventValue, useClient as useClient$1 } from 'alemonjs';
2
2
  import TelegramClient from 'node-telegram-bot-api';
3
3
 
4
- /**
5
- *
6
- * @param event
7
- * @returns
8
- */
9
4
  const useValue = (event) => {
10
5
  const value = createEventValue(event);
11
6
  return [value];
12
7
  };
13
- /**
14
- *
15
- * @param event
16
- * @returns
17
- */
18
8
  const useClient = (event) => {
19
9
  const [client] = useClient$1(event, TelegramClient);
20
10
  const value = createEventValue(event);
package/lib/index.d.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import TelegramClient from 'node-telegram-bot-api';
2
- export { platform } from './config.js';
3
- export { useClient, useValue } from './hook.js';
4
-
5
- declare const API: typeof TelegramClient;
6
-
7
- declare const _default: () => void;
8
-
9
- export { API, _default as default };
2
+ export { platform } from './config';
3
+ export { type Options } from './config';
4
+ export declare const API: typeof TelegramClient;
5
+ export * from './hook';
6
+ declare const _default: () => any;
7
+ export default _default;
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { cbpPlatform, createResult, ResultCode } from 'alemonjs';
1
+ import { definePlatform, cbpPlatform, createResult, ResultCode } from 'alemonjs';
2
2
  import { getBufferByURL } from 'alemonjs/utils';
3
3
  import TelegramClient from 'node-telegram-bot-api';
4
4
  import { getTGConfig, getMaster, platform } from './config.js';
@@ -6,7 +6,7 @@ import { readFileSync } from 'fs';
6
6
  export { useClient, useValue } from './hook.js';
7
7
 
8
8
  const API = TelegramClient;
9
- var index = () => {
9
+ const main = () => {
10
10
  const config = getTGConfig();
11
11
  const client = new TelegramClient(config.token, {
12
12
  polling: true,
@@ -16,97 +16,67 @@ var index = () => {
16
16
  proxy: config?.proxy ?? ''
17
17
  }
18
18
  });
19
- const url = `ws://127.0.0.1:${process.env?.port || config?.port || 17117}`;
19
+ const url = `ws://127.0.0.1:${process.env?.port || 17117}`;
20
20
  const cbp = cbpPlatform(url);
21
- /**
22
- *
23
- * @param UserId
24
- * @returns
25
- */
26
- const getUserProfilePhotosUrl = (UserId) => {
27
- return new Promise((resolve, reject) => {
28
- if (!UserId) {
29
- reject(new Error('UserId 不能为空'));
30
- return;
21
+ const getUserProfilePhotosUrl = async (UserId) => {
22
+ if (!UserId) {
23
+ return '';
24
+ }
25
+ try {
26
+ const profilePhotos = await client.getUserProfilePhotos(UserId);
27
+ if (profilePhotos.total_count > 0) {
28
+ const fileId = profilePhotos.photos[0][0].file_id;
29
+ const file = await client.getFile(fileId);
30
+ return `https://api.telegram.org/file/bot${config.token}/${file.file_path}`;
31
31
  }
32
- client
33
- .getUserProfilePhotos(UserId)
34
- .then(profilePhotos => {
35
- if (profilePhotos.total_count > 0) {
36
- // 获取第一张头像的文件 Id
37
- const fileId = profilePhotos.photos[0][0].file_id;
38
- // 获取文件信息以获取下载链接
39
- client
40
- .getFile(fileId)
41
- .then(file => {
42
- const filePath = file.file_path;
43
- resolve(`https://api.telegram.org/file/bot${config.token}/${filePath}`);
44
- })
45
- .catch(reject);
46
- }
47
- else {
48
- reject(new Error('用户没有头像'));
49
- }
50
- })
51
- .catch(reject);
52
- });
32
+ }
33
+ catch {
34
+ }
35
+ return '';
53
36
  };
54
37
  client.on('text', async (event) => {
55
38
  const UserId = String(event?.from?.id);
56
39
  const [isMaster, UserKey] = getMaster(UserId);
57
- const UserAvatar = (await getUserProfilePhotosUrl(event?.from?.id));
58
- if (event?.chat.type == 'channel' || event?.chat.type == 'supergroup') {
59
- // 机器人消息不处理
60
- if (event?.from?.is_bot)
40
+ const UserAvatar = await getUserProfilePhotosUrl(event?.from?.id);
41
+ if (event?.chat.type === 'channel' || event?.chat.type === 'supergroup') {
42
+ if (event?.from?.is_bot) {
61
43
  return;
62
- // 定义消
44
+ }
63
45
  const e = {
64
- // 事件类型
65
46
  Platform: platform,
66
47
  name: 'message.create',
67
- // 频道
68
48
  GuildId: String(event?.chat.id),
69
49
  ChannelId: String(event?.chat.id),
70
50
  SpaceId: String(event?.chat.id),
71
- // user
72
51
  UserId: UserId,
73
52
  UserKey: UserKey,
74
53
  UserName: event?.chat.username,
75
54
  UserAvatar: UserAvatar,
76
55
  IsMaster: isMaster,
77
56
  IsBot: false,
78
- // message
79
57
  MessageId: String(event?.message_id),
80
58
  MessageText: event?.text,
81
59
  OpenId: String(event?.chat?.id),
82
60
  CreateAt: Date.now(),
83
- // other
84
61
  tag: 'txt',
85
62
  value: event
86
63
  };
87
- // 发送消息
88
64
  cbp.send(e);
89
- //
90
65
  }
91
- else if (event?.chat.type == 'private') {
92
- // 定义消
66
+ else if (event?.chat.type === 'private') {
93
67
  const e = {
94
68
  name: 'private.message.create',
95
- // 事件类型
96
69
  Platform: platform,
97
- // 用户Id
98
70
  UserId: String(event?.from.id),
99
71
  UserKey: UserKey,
100
72
  UserName: event?.from?.username,
101
73
  UserAvatar: UserAvatar,
102
74
  IsMaster: isMaster,
103
75
  IsBot: false,
104
- // message
105
76
  MessageId: String(event?.message_id),
106
77
  MessageText: event?.text,
107
78
  OpenId: String(event?.chat?.id),
108
79
  CreateAt: Date.now(),
109
- // other
110
80
  tag: 'txt',
111
81
  value: event
112
82
  };
@@ -114,22 +84,18 @@ var index = () => {
114
84
  }
115
85
  });
116
86
  client.on('new_chat_members', async (event) => {
117
- // 机器人消息不处理
118
- if (event?.from.is_bot)
87
+ if (event?.from.is_bot) {
119
88
  return;
89
+ }
120
90
  const UserId = String(event?.from?.id);
121
91
  const [isMaster, UserKey] = getMaster(UserId);
122
- const UserAvatar = (await getUserProfilePhotosUrl(event?.from?.id));
123
- // 定义消
92
+ const UserAvatar = await getUserProfilePhotosUrl(event?.from?.id);
124
93
  const e = {
125
- naem: 'member.add',
126
- // 事件类型
94
+ name: 'member.add',
127
95
  Platform: platform,
128
- // guild
129
96
  GuildId: String(event?.chat.id),
130
97
  ChannelId: String(event?.chat.id),
131
98
  SpaceId: String(event?.chat.id),
132
- // user
133
99
  UserId: UserId,
134
100
  UserKey: UserKey,
135
101
  UserName: event?.chat.username,
@@ -138,7 +104,6 @@ var index = () => {
138
104
  IsBot: false,
139
105
  MessageId: String(event?.message_id),
140
106
  CreateAt: Date.now(),
141
- // othder
142
107
  tag: 'txt',
143
108
  value: event
144
109
  };
@@ -147,10 +112,11 @@ var index = () => {
147
112
  const api = {
148
113
  use: {
149
114
  send: async (event, val) => {
150
- if (val.length < 0)
115
+ if (!val || val.length <= 0) {
151
116
  return [];
117
+ }
152
118
  const content = val
153
- .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
119
+ .filter(item => item.type === 'Link' || item.type === 'Mention' || item.type === 'Text')
154
120
  .map(item => item.value)
155
121
  .join('');
156
122
  const e = event?.value;
@@ -159,15 +125,32 @@ var index = () => {
159
125
  const res = await client.sendMessage(e.chat.id, content);
160
126
  return [createResult(ResultCode.Ok, 'message.send', res)];
161
127
  }
162
- const images = val.filter(item => item.type == 'Image' || item.type == 'ImageFile' || item.type == 'ImageURL');
163
- if (images.length > 1) {
128
+ const images = val.filter(item => item.type === 'Image' || item.type === 'ImageFile' || item.type === 'ImageURL');
129
+ if (images.length > 0) {
164
130
  let data = null;
165
131
  for (let i = 0; i < images.length; i++) {
166
- if (data)
132
+ if (data) {
167
133
  break;
134
+ }
168
135
  const item = images[i];
169
136
  if (item.type === 'Image') {
170
- data = item.value;
137
+ if (Buffer.isBuffer(item.value)) {
138
+ data = item.value;
139
+ }
140
+ else if (typeof item.value === 'string') {
141
+ if (item.value.startsWith('http://') || item.value.startsWith('https://')) {
142
+ data = await getBufferByURL(item.value);
143
+ }
144
+ else if (item.value.startsWith('base64://')) {
145
+ data = Buffer.from(item.value.slice(9), 'base64');
146
+ }
147
+ else if (item.value.startsWith('file://')) {
148
+ data = readFileSync(item.value.slice(7));
149
+ }
150
+ else {
151
+ data = Buffer.from(item.value, 'base64');
152
+ }
153
+ }
171
154
  }
172
155
  else if (item.type === 'ImageFile') {
173
156
  data = readFileSync(item.value);
@@ -176,8 +159,10 @@ var index = () => {
176
159
  data = await getBufferByURL(item.value);
177
160
  }
178
161
  }
179
- const res = await client.sendPhoto(e.chat.id, data);
180
- return [createResult(ResultCode.Ok, 'message.send', res)];
162
+ if (data) {
163
+ const res = await client.sendPhoto(e.chat.id, data);
164
+ return [createResult(ResultCode.Ok, 'message.send', res)];
165
+ }
181
166
  }
182
167
  }
183
168
  catch (err) {
@@ -185,36 +170,57 @@ var index = () => {
185
170
  }
186
171
  return [];
187
172
  },
188
- mention: async () => {
189
- return [];
173
+ mention: () => {
174
+ return new Promise(resolve => {
175
+ resolve([]);
176
+ });
190
177
  }
191
178
  }
192
179
  };
193
- cbp.onactions(async (data, consume) => {
194
- if (data.action === 'message.send') {
195
- const event = data.payload.event;
196
- const paramFormat = data.payload.params.format;
197
- const res = await api.use.send(event, paramFormat);
198
- consume(res);
199
- }
200
- else if (data.action === 'message.send.channel') {
201
- consume([]);
202
- }
203
- else if (data.action === 'message.send.user') {
204
- consume([]);
180
+ const onactions = async (data, consume) => {
181
+ try {
182
+ if (data.action === 'message.send') {
183
+ const event = data.payload.event;
184
+ const paramFormat = data.payload.params.format;
185
+ const res = await api.use.send(event, paramFormat);
186
+ consume(res);
187
+ }
188
+ else if (data.action === 'message.send.channel') {
189
+ consume([createResult(ResultCode.Fail, '暂未支持,请尝试升级版本', null)]);
190
+ }
191
+ else if (data.action === 'message.send.user') {
192
+ consume([createResult(ResultCode.Fail, '暂未支持,请尝试升级版本', null)]);
193
+ }
194
+ else if (data.action === 'mention.get') {
195
+ consume([createResult(ResultCode.Fail, '暂未支持,请尝试升级版本', null)]);
196
+ }
197
+ else {
198
+ consume([createResult(ResultCode.Fail, '未知请求,请尝试升级版本', null)]);
199
+ }
205
200
  }
206
- else if (data.action === 'mention.get') {
207
- consume([]);
201
+ catch (error) {
202
+ consume([createResult(ResultCode.Fail, '请求失败', error)]);
208
203
  }
209
- });
210
- cbp.onapis(async (data, consume) => {
204
+ };
205
+ cbp.onactions((data, consume) => void onactions(data, consume));
206
+ const onapis = async (data, consume) => {
211
207
  const key = data.payload?.key;
212
208
  if (client[key]) {
213
209
  const params = data.payload.params;
214
- const res = await client[key](...params);
215
- consume([createResult(ResultCode.Ok, '请求完成', res)]);
210
+ try {
211
+ const res = await client[key](...params);
212
+ consume([createResult(ResultCode.Ok, '请求完成', res)]);
213
+ }
214
+ catch (error) {
215
+ consume([createResult(ResultCode.Fail, '请求失败', error)]);
216
+ }
216
217
  }
217
- });
218
+ else {
219
+ consume([createResult(ResultCode.Fail, '未知请求,请尝试升级版本', null)]);
220
+ }
221
+ };
222
+ cbp.onapis((data, consume) => void onapis(data, consume));
218
223
  };
224
+ var index = definePlatform({ main });
219
225
 
220
226
  export { API, index as default, platform };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alemonjs/telegram",
3
- "version": "2.1.0-alpha.0",
3
+ "version": "2.1.0-alpha.1",
4
4
  "description": "telegram platform connection",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -8,13 +8,16 @@
8
8
  "main": "lib/index.js",
9
9
  "types": "lib",
10
10
  "scripts": {
11
- "build": "node bundle.js"
11
+ "build": "lvy build"
12
12
  },
13
13
  "dependencies": {
14
14
  "@types/node-telegram-bot-api": "^0.64.9",
15
15
  "grammy": "^1.30.0",
16
16
  "node-telegram-bot-api": "^0.66.0"
17
17
  },
18
+ "peerDependencies": {
19
+ "alemonjs": "^2.1.0-alpha.15"
20
+ },
18
21
  "exports": {
19
22
  ".": {
20
23
  "import": "./lib/index.js",
@@ -43,4 +46,4 @@
43
46
  "type": "git",
44
47
  "url": "https://github.com/lemonade-lab/alemonjs.git"
45
48
  }
46
- }
49
+ }