-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAiServerGuideAgentApp.ts
More file actions
210 lines (194 loc) · 8 KB
/
AiServerGuideAgentApp.ts
File metadata and controls
210 lines (194 loc) · 8 KB
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
import {
IAppAccessors,
ILogger,
} from '@rocket.chat/apps-engine/definition/accessors';
import { IAppInstallationContext } from '@rocket.chat/apps-engine/definition/accessors';
import { IHttp, IModify, IPersistence, IRead } from '@rocket.chat/apps-engine/definition/accessors';
import { IConfigurationExtend } from '@rocket.chat/apps-engine/definition/accessors';
import { IEnvironmentRead } from '@rocket.chat/apps-engine/definition/accessors';
import { App } from '@rocket.chat/apps-engine/definition/App';
import { IMessage } from '@rocket.chat/apps-engine/definition/messages';
import { IPostMessageSentToBot } from '@rocket.chat/apps-engine/definition/messages/IPostMessageSentToBot';
import { IAppInfo } from '@rocket.chat/apps-engine/definition/metadata';
import { UIKitViewSubmitInteractionContext } from '@rocket.chat/apps-engine/definition/uikit';
import { IPostUserCreated } from '@rocket.chat/apps-engine/definition/users';
import { IUserContext } from '@rocket.chat/apps-engine/definition/users';
import { Settings } from './config/settings';
import { IAdminConfig } from './definitions/IAdminConfig';
import { ServerGuideCommand } from './src/commands/ServerGuideCommand';
import { AdminPersistence } from './src/persistence/AdminPersistence';
import { sendDirectMessageOnInstall } from './utils/message';
import { getDirectRoom, sendMessage } from './utils/message';
import { processAdminMessage, processUserMessage } from './utils/processMessage';
import { IApiConfig } from './definitions/IApiConfig';
import { ApiConfigPersistence } from './src/persistence/ApiConfigPersistence';
export class AiServerGuideAgentApp extends App implements IPostMessageSentToBot, IPostUserCreated {
constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors) {
super(info, logger, accessors);
}
public async onInstall(
context: IAppInstallationContext,
read: IRead,
http: IHttp,
persistence: IPersistence,
modify: IModify,
): Promise<void> {
const { user } = context;
await sendDirectMessageOnInstall(read, modify, user, persistence);
return;
}
public async extendConfiguration(
configuration: IConfigurationExtend,
environmentRead: IEnvironmentRead,
): Promise<void> {
await Promise.all([
Settings.map((setting) =>
configuration.settings.provideSetting(setting),
),
configuration.slashCommands.provideSlashCommand(
new ServerGuideCommand(this),
),
],
);
}
public async executePostMessageSentToBot(
message: IMessage,
read: IRead,
http: IHttp,
persistence: IPersistence,
modify: IModify,
): Promise<void> {
try {
if (!message.text) {
return;
}
let responseText;
if (message.sender.roles.includes('admin')) {
responseText = await processAdminMessage(
message,
read,
http,
modify,
persistence,
);
}
else {
responseText = await processUserMessage(
message,
read,
http,
modify,
persistence,
);
}
const msgBuilder = modify.getCreator().startMessage();
msgBuilder.setText(responseText);
msgBuilder.setRoom(message.room);
await modify.getCreator().finish(msgBuilder);
} catch (error) {
console.log("Error processing DM:", error);
}
}
public async executePostUserCreated(
context: IUserContext,
read: IRead,
http: IHttp,
persistence: IPersistence,
modify: IModify,
): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 3000));
const createdUser = await read.getUserReader().getById(context.user.id);
if (!createdUser || !createdUser.username) {
return;
}
const appUser = await read.getUserReader().getAppUser();
if (!appUser || createdUser.roles.includes('admin')) {
return;
}
const adminStorage = new AdminPersistence(
persistence,
read.getPersistenceReader(),
);
const adminConfig = await adminStorage.getAdminConfig();
if (!adminConfig) {
return;
}
const dmRoom = await getDirectRoom(
read,
modify,
createdUser,
appUser.username,
);
if (!dmRoom) {
return;
}
if (adminConfig.welcomeMessage) {
await sendMessage(modify, dmRoom, appUser, adminConfig.welcomeMessage);
}
if (adminConfig.newComerChannel) {
for (const channel of adminConfig.newComerChannel) {
const channelName = channel.startsWith('#') ? channel.slice(1) : channel;
const room = await read.getRoomReader().getByName(channelName);
if (!room) {
console.log(`Room not found: ${channelName}`);
continue;
}
const roomUpdater = await modify.getUpdater().room(room.id, createdUser);
roomUpdater.addMemberToBeAddedByUsername(createdUser.username);
await modify.getUpdater().finish(roomUpdater);
}
}
if (adminConfig.serverRules) {
await sendMessage(modify, dmRoom, appUser, adminConfig.serverRules);
}
}
public async executeViewSubmitHandler(
context: UIKitViewSubmitInteractionContext,
read: IRead,
http: IHttp,
persistence: IPersistence,
): Promise<void> {
const { view, user } = context.getInteractionData();
const viewState = view.state as {
serverUrl: { server_url_config: string };
xAuthToken: { x_auth_token_config: string };
xUserId: { x_user_id_config: string };
welcomeMessage: { welcome_message_config: string };
serverRules: { server_rules_config: string };
recommendedChannels: { channel_recommendation_config: string };
newComerChannel: { new_user_channel_config: string };
};
const apiConfigStore = new ApiConfigPersistence(persistence, read.getPersistenceReader());
const updatedApiConfig: IApiConfig = {
serverUrl: viewState.serverUrl?.server_url_config ?? '',
xAuthToken: viewState.xAuthToken?.x_auth_token_config ?? '',
xUserId: viewState.xUserId?.x_user_id_config ?? '',
}
await apiConfigStore.storeApiConfig(updatedApiConfig, user.id);
if (user.roles.includes('user')) {
return;
}
const welcomeMessageText = viewState.welcomeMessage?.welcome_message_config ?? '';
const serverRulesText = viewState.serverRules?.server_rules_config ?? '';
const recommendedChannelsText = viewState.recommendedChannels?.channel_recommendation_config ?? '';
const newComerChannelText = viewState.newComerChannel?.new_user_channel_config ?? '';
const newComerChannelList: Array<string> = newComerChannelText
.split(',')
.map((channel) => channel.trim())
.filter((channel) => channel !== '');
const adminStorage = new AdminPersistence(
persistence,
read.getPersistenceReader(),
);
const currentConfig = await adminStorage.getAdminConfig();
const updatedConfig: IAdminConfig = {
...currentConfig,
welcomeMessage: welcomeMessageText,
serverRules: serverRulesText,
recommendedChannels: recommendedChannelsText,
newComerChannel: newComerChannelList,
channelReport: currentConfig?.channelReport ?? '',
};
await adminStorage.storeAdminConfig(updatedConfig);
}
}