-
Notifications
You must be signed in to change notification settings - Fork 2
/
chats.ts
208 lines (180 loc) · 6.71 KB
/
chats.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
import { Bot, Context, debug, Types } from "./deps.ts";
import type {
BotCommands,
BotDescriptions,
ChatType,
EnvironmentOptions,
InlineQueryResultCached,
MyDefaultAdministratorRights,
} from "./types.ts";
import { PrivateChat, PrivateChatDetails } from "./private.ts";
import { GroupChat, GroupChatDetails } from "./group.ts";
import { SupergroupChat, SupergroupChatDetails } from "./supergroup.ts";
import { ChannelChat, ChannelChatDetails } from "./channel.ts";
import { bakeHandlers } from "./methods/mod.ts";
import * as CONSTANTS from "./constants.ts";
import { isChatAdministratorRight, isChatPermission, rand } from "./helpers.ts";
/** Emulates a Telegram environment, and everything's in it. */
export class Chats<C extends Context> {
/** Generated random values that are currently in use. */
randomsInUse: Record<string, Set<unknown>> = {};
/** Responsible for generating unique IDs and strings. */
unique<T>(generatorFn: () => T) {
const type = generatorFn.name;
let random = generatorFn();
if (this.randomsInUse[type] === undefined) {
this.randomsInUse[type] = new Set<T>();
}
while (this.randomsInUse[type].has(random)) random = generatorFn();
this.randomsInUse[type].add(random);
return random;
}
private d: ReturnType<typeof debug>;
// Properties existing without other chats.
commands: BotCommands = CONSTANTS.BotCommandsDefault;
descriptions: BotDescriptions = CONSTANTS.BotDescriptionsDefault;
myDefaultAdministratorRights: MyDefaultAdministratorRights;
defaultChatMenuButton: Types.MenuButton;
// Properties that are related with a chat.
inlineQueries: Map<Types.InlineQuery["id"], Types.InlineQuery> = new Map();
cachedInlineQueryResults: Map<
Types.InlineQueryResultCachedGif["id"],
InlineQueryResultCached
> = new Map();
updates: Map<Types.Update["update_id"], Types.Update> = new Map();
update_id = 100000000;
get updateId() {
return this.update_id++;
}
get date() {
return Math.trunc(Date.now() / 1000);
}
// Properties of the Telegram environment.
chats: Map<Types.Chat["id"], ChatType<C>> = new Map();
constructor(private bot: Bot<C>, options?: EnvironmentOptions) {
this.bot.botInfo = bot.isInited() && bot.botInfo
? bot.botInfo
: options?.botInfo ?? {
id: this.unique(rand.botId),
first_name: "Test",
last_name: "Bot",
username: "testbot",
can_join_groups: true,
can_read_all_group_messages: false,
supports_inline_queries: false,
is_bot: true,
};
this.myDefaultAdministratorRights = options?.myDefaultAdministratorRights ??
CONSTANTS.defaultBotAdministratorRights;
this.defaultChatMenuButton = options?.defaultChatMenuButton ??
CONSTANTS.MenuButtonDefault;
const handlers = bakeHandlers<C>();
this.bot.api.config.use((prev, method, payload, signal) => {
const handler = handlers[method];
return handler
// deno-lint-ignore no-explicit-any
? handler(this, payload) as any // TODO: Fix the type issue.
: prev(method, payload, signal);
});
this.d = debug("chats");
}
/** Get the bot installed on the environment. */
getBot() {
return this.bot;
}
/** Resolve an username registered in the environment */
resolveUsername(username: string): ChatType<C> | undefined {
for (const chat of this.chats.values()) {
if (chat.chat.type === "group") continue;
if (chat.chat.username === username) return chat;
}
}
getChatMember(
userId: number,
chatId: number,
): Types.ChatMember | { status: "not-found" | "chat-not-found" } {
const chat = this.chats.get(chatId);
if (chat === undefined) return { status: "chat-not-found" };
if (chat.type === "private") {
this.d("No need for checking if user is a member of private chat");
return { status: "chat-not-found" }; // Yes, thats how Bot API works.
}
return chat.getChatMember(userId);
}
/** Does the user have the permission to do something in the chat. */
userCan(
userId: number,
chatId: number,
permission:
| keyof Types.ChatPermissions
| keyof Types.ChatAdministratorRights,
): boolean {
const member = this.getChatMember(userId, chatId);
if (
member.status === "chat-not-found" ||
member.status === "not-found" ||
member.status === "kicked" ||
member.status === "left"
) return false;
if (member.status === "creator") return true;
if (member.status === "administrator") {
if (isChatAdministratorRight(permission)) {
return !!member[permission];
}
}
if (!isChatPermission(permission)) {
throw new Error(`Invalid permission '${permission}'`);
}
if (member.status === "restricted") return !!member[permission];
const chat = this.chats.get(chatId)!;
if (chat.type === "channel") return false;
if (chat.type === "private") return true; // never reached
if (chat.type === "group") return true;
return !!chat.permissions[permission];
}
/** Create and register a new Telegram user in the environment. */
newUser(details: PrivateChatDetails) {
if (this.chats.has(details.id)) {
throw new Error("Chat with the same ID already exists.");
}
const privateChat = new PrivateChat(this, details);
this.chats.set(privateChat.chat_id, privateChat);
return privateChat;
}
/** Create and register a new group in the environment. */
newGroup(details: GroupChatDetails) {
if (this.chats.has(details.id)) {
throw new Error("Chat with the same ID already exists.");
}
const groupChat = new GroupChat(this, details);
this.chats.set(groupChat.chat_id, groupChat);
return groupChat;
}
/** Create and register a new supergroup in the environment. */
newSuperGroup(details: SupergroupChatDetails) {
if (this.chats.has(details.id)) {
throw new Error("Chat with the same ID already exists.");
}
const supergroupChat = new SupergroupChat(this, details);
this.chats.set(supergroupChat.chat_id, supergroupChat);
return supergroupChat;
}
/** Create and register a new channel in the environment. */
newChannel(details: ChannelChatDetails) {
if (this.chats.has(details.id)) {
throw new Error("Chat with the same ID already exists.");
}
const channelChat = new ChannelChat(this, details);
this.chats.set(channelChat.chat_id, channelChat);
return channelChat;
}
/** Validate the update before sending it. */
validateUpdate(update: Omit<Types.Update, "update_id">): Types.Update {
// TODO: the actual validation.
return { ...update, update_id: this.updateId };
}
/** Send update to the bot. */
sendUpdate(update: Types.Update) {
return this.bot.handleUpdate(update);
}
}