@alemonjs/telegram 0.2.3 → 2.1.0-alpha.0

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/README.md CHANGED
@@ -1,6 +1,20 @@
1
1
  # [https://alemonjs.com/](https://alemonjs.com/)
2
2
 
3
- 跨平台开发的事件驱动机器人
3
+ [文档 https://core.telegram.org/bots ](https://core.telegram.org/bots)
4
+
5
+ ## 创建机器人
6
+
7
+ [访问 https://core.telegram.org/bots/tutorial#obtain-your-bot-token](https://core.telegram.org/bots/tutorial#obtain-your-bot-token)
8
+
9
+ 点击添加`@BotFather`并发送`/newbot`,并继续发送 `NameXBot` 得以生产 `token`
10
+
11
+ ```yaml
12
+ 79179797979:AAAAAAAAAAAAAABBBBBBCCCCCCCCCC
13
+ ```
14
+
15
+ - NameXdBot 即自定义的 bot 名
16
+
17
+ [访问 https://web.telegram.org/k/#@NameXdBot 以添加](https://web.telegram.org/k/#@NameXdBot)
4
18
 
5
19
  ## USE
6
20
 
@@ -22,9 +36,12 @@ telegram:
22
36
  master_key: null
23
37
  # other
24
38
  base_api_url: null
39
+ #
25
40
  request_url: null
41
+ # 使用 user_key
42
+ master_key:
43
+ - 'xxx'
44
+ # 使用 user_id
45
+ master_id:
46
+ - 'yyy'
26
47
  ```
27
-
28
- ## Community
29
-
30
- QQ Group 806943302
@@ -0,0 +1,3 @@
1
+ declare const platform = "telegram";
2
+
3
+ export { platform };
package/lib/config.js ADDED
@@ -0,0 +1,20 @@
1
+ import { getConfigValue, useUserHashKey } from 'alemonjs';
2
+
3
+ const platform = 'telegram';
4
+ const getTGConfig = () => {
5
+ const value = getConfigValue() || {};
6
+ return value[platform] || {};
7
+ };
8
+ const getMaster = (UserId) => {
9
+ const config = getTGConfig();
10
+ const master_key = config.master_key || [];
11
+ const master_id = config.master_id || [];
12
+ const UserKey = useUserHashKey({
13
+ Platform: platform,
14
+ UserId: UserId
15
+ });
16
+ const is = master_key.includes(UserKey) || master_id.includes(UserId);
17
+ return [is, UserKey];
18
+ };
19
+
20
+ export { getMaster, getTGConfig, platform };
package/lib/hook.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { EventKeys, Events } from 'alemonjs';
2
+ import TelegramClient from 'node-telegram-bot-api';
3
+
4
+ type MAP = {
5
+ 'message.create': TelegramClient.Message;
6
+ 'private.message.create': undefined;
7
+ 'interaction.create': undefined;
8
+ 'private.interaction.create': undefined;
9
+ 'message.update': undefined;
10
+ 'message.delete': undefined;
11
+ 'message.reaction.add': undefined;
12
+ 'message.reaction.remove': undefined;
13
+ 'channal.create': undefined;
14
+ 'channal.delete': undefined;
15
+ 'guild.join': undefined;
16
+ 'guild.exit': undefined;
17
+ 'member.add': undefined;
18
+ 'member.remove': undefined;
19
+ 'private.message.update': undefined;
20
+ 'private.message.delete': undefined;
21
+ 'private.friend.add': undefined;
22
+ 'private.guild.add': undefined;
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 };
package/lib/hook.js ADDED
@@ -0,0 +1,24 @@
1
+ import { createEventValue, useClient as useClient$1 } from 'alemonjs';
2
+ import TelegramClient from 'node-telegram-bot-api';
3
+
4
+ /**
5
+ *
6
+ * @param event
7
+ * @returns
8
+ */
9
+ const useValue = (event) => {
10
+ const value = createEventValue(event);
11
+ return [value];
12
+ };
13
+ /**
14
+ *
15
+ * @param event
16
+ * @returns
17
+ */
18
+ const useClient = (event) => {
19
+ const [client] = useClient$1(event, TelegramClient);
20
+ const value = createEventValue(event);
21
+ return [client, value];
22
+ };
23
+
24
+ export { useClient, useValue };
package/lib/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import * as alemonjs from 'alemonjs';
2
1
  import TelegramClient from 'node-telegram-bot-api';
2
+ export { platform } from './config.js';
3
+ export { useClient, useValue } from './hook.js';
3
4
 
4
- type Client = typeof TelegramClient.prototype;
5
- declare const client: Client;
6
- declare const platform = "telegram";
7
- declare const _default: () => alemonjs.ClientAPI;
5
+ declare const API: typeof TelegramClient;
8
6
 
9
- export { type Client, client, _default as default, platform };
7
+ declare const _default: () => void;
8
+
9
+ export { API, _default as default };
package/lib/index.js CHANGED
@@ -1,22 +1,13 @@
1
- import { defineBot, getConfigValue, useUserHashKey, OnProcessor } from 'alemonjs';
1
+ import { cbpPlatform, createResult, ResultCode } from 'alemonjs';
2
+ import { getBufferByURL } from 'alemonjs/utils';
2
3
  import TelegramClient from 'node-telegram-bot-api';
4
+ import { getTGConfig, getMaster, platform } from './config.js';
5
+ import { readFileSync } from 'fs';
6
+ export { useClient, useValue } from './hook.js';
3
7
 
4
- const client = new Proxy({}, {
5
- get: (_, prop) => {
6
- if (prop in global.client) {
7
- const original = global.client[prop];
8
- // 防止函数内this丢失
9
- return typeof original === 'function' ? original.bind(global.client) : original;
10
- }
11
- return undefined;
12
- }
13
- });
14
- const platform = 'telegram';
15
- var index = defineBot(() => {
16
- let value = getConfigValue();
17
- if (!value)
18
- value = {};
19
- const config = value[platform];
8
+ const API = TelegramClient;
9
+ var index = () => {
10
+ const config = getTGConfig();
20
11
  const client = new TelegramClient(config.token, {
21
12
  polling: true,
22
13
  baseApiUrl: config?.base_api_url ?? '',
@@ -25,6 +16,8 @@ var index = defineBot(() => {
25
16
  proxy: config?.proxy ?? ''
26
17
  }
27
18
  });
19
+ const url = `ws://127.0.0.1:${process.env?.port || config?.port || 17117}`;
20
+ const cbp = cbpPlatform(url);
28
21
  /**
29
22
  *
30
23
  * @param UserId
@@ -60,41 +53,8 @@ var index = defineBot(() => {
60
53
  };
61
54
  client.on('text', async (event) => {
62
55
  const UserId = String(event?.from?.id);
63
- const UserKey = useUserHashKey({
64
- Platform: platform,
65
- UserId: UserId
66
- });
67
- const UserAvatar = {
68
- toBuffer: async () => {
69
- if (event?.chat.type == 'supergroup' || event?.chat.type == 'private') {
70
- const photo = await getUserProfilePhotosUrl(event?.from?.id).catch(console.error);
71
- if (typeof photo == 'string') {
72
- const arrayBuffer = await fetch(photo).then(res => res.arrayBuffer());
73
- return Buffer.from(arrayBuffer);
74
- }
75
- }
76
- return;
77
- },
78
- toURL: async () => {
79
- if (event?.chat.type == 'supergroup' || event?.chat.type == 'private') {
80
- const photo = await getUserProfilePhotosUrl(event?.from?.id).catch(console.error);
81
- if (typeof photo == 'string') {
82
- return photo;
83
- }
84
- }
85
- return;
86
- },
87
- toBase64: async () => {
88
- if (event?.chat.type == 'supergroup' || event?.chat.type == 'private') {
89
- const photo = await getUserProfilePhotosUrl(event?.from?.id).catch(console.error);
90
- if (typeof photo == 'string') {
91
- const arrayBuffer = await fetch(photo).then(res => res.arrayBuffer());
92
- return Buffer.from(arrayBuffer).toString('base64');
93
- }
94
- }
95
- return;
96
- }
97
- };
56
+ const [isMaster, UserKey] = getMaster(UserId);
57
+ const UserAvatar = (await getUserProfilePhotosUrl(event?.from?.id));
98
58
  if (event?.chat.type == 'channel' || event?.chat.type == 'supergroup') {
99
59
  // 机器人消息不处理
100
60
  if (event?.from?.is_bot)
@@ -103,32 +63,29 @@ var index = defineBot(() => {
103
63
  const e = {
104
64
  // 事件类型
105
65
  Platform: platform,
66
+ name: 'message.create',
106
67
  // 频道
107
68
  GuildId: String(event?.chat.id),
108
69
  ChannelId: String(event?.chat.id),
70
+ SpaceId: String(event?.chat.id),
109
71
  // user
110
72
  UserId: UserId,
111
73
  UserKey: UserKey,
112
74
  UserName: event?.chat.username,
113
75
  UserAvatar: UserAvatar,
114
- IsMaster: false,
76
+ IsMaster: isMaster,
115
77
  IsBot: false,
116
78
  // message
117
79
  MessageId: String(event?.message_id),
80
+ MessageText: event?.text,
118
81
  OpenId: String(event?.chat?.id),
119
82
  CreateAt: Date.now(),
120
83
  // other
121
84
  tag: 'txt',
122
- value: null
85
+ value: event
123
86
  };
124
- // 当访问的时候获取
125
- Object.defineProperty(e, 'value', {
126
- get() {
127
- return event;
128
- }
129
- });
130
- //
131
- OnProcessor(e, 'message.create');
87
+ // 发送消息
88
+ cbp.send(e);
132
89
  //
133
90
  }
134
91
  else if (event?.chat.type == 'private') {
@@ -142,7 +99,7 @@ var index = defineBot(() => {
142
99
  UserKey: UserKey,
143
100
  UserName: event?.from?.username,
144
101
  UserAvatar: UserAvatar,
145
- IsMaster: false,
102
+ IsMaster: isMaster,
146
103
  IsBot: false,
147
104
  // message
148
105
  MessageId: String(event?.message_id),
@@ -151,16 +108,9 @@ var index = defineBot(() => {
151
108
  CreateAt: Date.now(),
152
109
  // other
153
110
  tag: 'txt',
154
- value: null
111
+ value: event
155
112
  };
156
- // 当访问的时候获取
157
- Object.defineProperty(e, 'value', {
158
- get() {
159
- return event;
160
- }
161
- });
162
- // 处理消息
163
- OnProcessor(e, 'private.message.create');
113
+ cbp.send(e);
164
114
  }
165
115
  });
166
116
  client.on('new_chat_members', async (event) => {
@@ -168,35 +118,8 @@ var index = defineBot(() => {
168
118
  if (event?.from.is_bot)
169
119
  return;
170
120
  const UserId = String(event?.from?.id);
171
- const UserKey = useUserHashKey({
172
- Platform: platform,
173
- UserId: UserId
174
- });
175
- const UserAvatar = {
176
- toBuffer: async () => {
177
- const photo = await getUserProfilePhotosUrl(event?.from?.id).catch(console.error);
178
- if (typeof photo == 'string') {
179
- const arrayBuffer = await fetch(photo).then(res => res.arrayBuffer());
180
- return Buffer.from(arrayBuffer);
181
- }
182
- return;
183
- },
184
- toURL: async () => {
185
- const photo = await getUserProfilePhotosUrl(event?.from?.id).catch(console.error);
186
- if (typeof photo == 'string') {
187
- return photo;
188
- }
189
- return;
190
- },
191
- toBase64: async () => {
192
- const photo = await getUserProfilePhotosUrl(event?.from?.id).catch(console.error);
193
- if (typeof photo == 'string') {
194
- const arrayBuffer = await fetch(photo).then(res => res.arrayBuffer());
195
- return Buffer.from(arrayBuffer).toString('base64');
196
- }
197
- return;
198
- }
199
- };
121
+ const [isMaster, UserKey] = getMaster(UserId);
122
+ const UserAvatar = (await getUserProfilePhotosUrl(event?.from?.id));
200
123
  // 定义消
201
124
  const e = {
202
125
  naem: 'member.add',
@@ -205,60 +128,93 @@ var index = defineBot(() => {
205
128
  // guild
206
129
  GuildId: String(event?.chat.id),
207
130
  ChannelId: String(event?.chat.id),
208
- // GuildName: event?.chat.title,
131
+ SpaceId: String(event?.chat.id),
209
132
  // user
210
133
  UserId: UserId,
211
134
  UserKey: UserKey,
212
135
  UserName: event?.chat.username,
213
136
  UserAvatar: UserAvatar,
214
- IsMaster: false,
137
+ IsMaster: isMaster,
215
138
  IsBot: false,
216
- // message
217
139
  MessageId: String(event?.message_id),
218
- // MessageText: event?.text,
219
- // OpenId: String(event?.chat?.id),
220
140
  CreateAt: Date.now(),
221
141
  // othder
222
142
  tag: 'txt',
223
- value: null
143
+ value: event
224
144
  };
225
- // 当访问的时候获取
226
- Object.defineProperty(e, 'value', {
227
- get() {
228
- return event;
229
- }
230
- });
231
- //
232
- OnProcessor(e, 'member.add');
145
+ cbp.send(e);
233
146
  });
234
- global.client = client;
235
- return {
236
- api: {
237
- use: {
238
- send: (event, val) => {
239
- if (val.length < 0)
240
- return Promise.all([]);
241
- const content = val
242
- .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
243
- .map(item => item.value)
244
- .join('');
245
- const e = event?.value;
147
+ const api = {
148
+ use: {
149
+ send: async (event, val) => {
150
+ if (val.length < 0)
151
+ return [];
152
+ const content = val
153
+ .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
154
+ .map(item => item.value)
155
+ .join('');
156
+ const e = event?.value;
157
+ try {
246
158
  if (content) {
247
- return Promise.all([content].map(item => client.sendMessage(e.chat.id, item)));
159
+ const res = await client.sendMessage(e.chat.id, content);
160
+ return [createResult(ResultCode.Ok, 'message.send', res)];
248
161
  }
249
- const images = val.filter(item => item.type == 'Image').map(item => item.value);
250
- if (images) {
251
- return Promise.all(images.map(item => client.sendPhoto(e.chat.id, item)));
162
+ const images = val.filter(item => item.type == 'Image' || item.type == 'ImageFile' || item.type == 'ImageURL');
163
+ if (images.length > 1) {
164
+ let data = null;
165
+ for (let i = 0; i < images.length; i++) {
166
+ if (data)
167
+ break;
168
+ const item = images[i];
169
+ if (item.type === 'Image') {
170
+ data = item.value;
171
+ }
172
+ else if (item.type === 'ImageFile') {
173
+ data = readFileSync(item.value);
174
+ }
175
+ else if (item.type === 'ImageURL') {
176
+ data = await getBufferByURL(item.value);
177
+ }
178
+ }
179
+ const res = await client.sendPhoto(e.chat.id, data);
180
+ return [createResult(ResultCode.Ok, 'message.send', res)];
252
181
  }
253
- return Promise.all([]);
254
- },
255
- mention: async () => {
256
- // const event: TelegramClient.Message = e.value
257
- return [];
258
182
  }
183
+ catch (err) {
184
+ return [createResult(ResultCode.Fail, err?.response?.data ?? err?.message ?? err, null)];
185
+ }
186
+ return [];
187
+ },
188
+ mention: async () => {
189
+ return [];
259
190
  }
260
191
  }
261
192
  };
262
- });
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([]);
205
+ }
206
+ else if (data.action === 'mention.get') {
207
+ consume([]);
208
+ }
209
+ });
210
+ cbp.onapis(async (data, consume) => {
211
+ const key = data.payload?.key;
212
+ if (client[key]) {
213
+ const params = data.payload.params;
214
+ const res = await client[key](...params);
215
+ consume([createResult(ResultCode.Ok, '请求完成', res)]);
216
+ }
217
+ });
218
+ };
263
219
 
264
- export { client, index as default, platform };
220
+ export { API, index as default, platform };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@alemonjs/telegram",
3
- "version": "0.2.3",
4
- "description": "telegram-bot",
3
+ "version": "2.1.0-alpha.0",
4
+ "description": "telegram platform connection",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
7
7
  "type": "module",
@@ -11,6 +11,7 @@
11
11
  "build": "node bundle.js"
12
12
  },
13
13
  "dependencies": {
14
+ "@types/node-telegram-bot-api": "^0.64.9",
14
15
  "grammy": "^1.30.0",
15
16
  "node-telegram-bot-api": "^0.66.0"
16
17
  },