-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.ts
120 lines (112 loc) · 2.64 KB
/
chat.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
import { DiscourseApi } from "@/api";
import { Uploads } from "@/types/discourse";
export type ChatMessageOptions = {
/**
* Reply to message id
*/
in_reply_to_id?: number;
/**
* An array of uploads_ids
*/
uploads?: Uploads[] | { id: number }[] | number[];
};
export class ChatApi {
private _api: DiscourseApi;
get api() {
return this._api;
}
constructor(api: DiscourseApi) {
this._api = api;
}
/**
* Send a message to channel
* @param channelId The id of channel
* @param message message raw text
* @param options message options
* @returns
*/
sendMessage(
channelId: number,
message: string,
options?: ChatMessageOptions,
) {
const data: { [key: string]: unknown } = {
message,
};
if (options?.uploads) {
data.upload_ids = options.uploads.map((upload) => {
return typeof upload === "number" ? upload : upload.id;
});
}
if (options?.in_reply_to_id) {
data.in_reply_to_id = options.in_reply_to_id;
}
return this.api._request(`/chat/${channelId}`, "POST", data);
}
/**
* Edit a message of a channel
* @param channelId The id of channel
* @param messageId The id of message
* @param message new message, raw text
* @returns
*/
editMessage(
channelId: number,
messageId: number,
message: string,
options?: ChatMessageOptions,
) {
const data: { [key: string]: unknown } = {
new_message: message,
};
if (options?.uploads) {
data.upload_ids = options.uploads.map((upload) => {
return typeof upload === "number" ? upload : upload.id;
});
}
if (options?.in_reply_to_id) {
data.in_reply_to_id = options.in_reply_to_id;
}
return this.api._request(
`/chat/${channelId}/edit/${messageId}`,
"PUT",
data,
);
}
/**
* Delete a message from a channel
*
* Example:
*
* ```
* api.chat.deleteMessage(1, 1024).then(() => {
* console.log("Delete successfully");
* }).catch((err) => {
* console.log("Delete failed!");
* console.error(err);
* });
* ```
*
* @param channelId The id of channel
* @param messageId The id of message to delete
* @returns
*/
deleteMessage(channelId: number, messageId: number) {
return this.api._request(
`/chat/api/channels/${channelId}/messages/${messageId}`,
"DELETE",
);
}
}
export interface BasicChatMessage {
id: number;
message: string;
cooked: string;
created_at: string;
edited?: boolean;
excerpt: string;
deleted_at?: null | string;
deleted_by_id?: null | number;
thread_id?: null | number;
chat_channel_id: number;
}