1
+ import { useEffect } from "react" ;
2
+
3
+ import { RcbPreInjectMessageEvent , useBotId } from "react-chatbotify" ;
4
+ import { PluginConfig } from "../types/PluginConfig" ;
5
+
6
+ /**
7
+ * Plugin hook that handles all the core logic.
8
+ *
9
+ * @param pluginConfig configurations for the plugin
10
+ */
11
+ const useRcbPlugin = ( pluginConfig ?: PluginConfig ) => {
12
+ // uses hook to get bot id
13
+ const { getBotId } = useBotId ( ) ;
14
+
15
+ // provides plugin logic
16
+ useEffect ( ( ) => {
17
+ // handles message sent
18
+ const handlePreInjectMessage = ( event : RcbPreInjectMessageEvent ) => {
19
+ // checks bot id to prevent conflicts with multiple chatbots
20
+ if ( getBotId ( ) !== event . detail . botId ) {
21
+ return ;
22
+ }
23
+
24
+ // checks if message is from user
25
+ if ( event . data . message . sender . toUpperCase ( ) !== "USER" ) {
26
+ return ;
27
+ }
28
+
29
+ // checks if message content is a string (it may be a JSX element)
30
+ const message = event . data . message ;
31
+ if ( typeof message . content !== "string" ) {
32
+ return ;
33
+ }
34
+
35
+ // reverses the message string if it is
36
+ message . content = message . content . split ( "" ) . reverse ( ) . join ( "" ) ;
37
+ } ;
38
+
39
+ // relies on rcb-pre-inject-message event to intercept and modify messages
40
+ window . addEventListener ( "rcb-pre-inject-message" , handlePreInjectMessage ) ;
41
+ return ( ) => {
42
+ window . removeEventListener ( "rcb-pre-inject-message" , handlePreInjectMessage ) ;
43
+ } ;
44
+ } , [ getBotId ] ) ;
45
+
46
+ // name is a required field, recommended to match the npm package name to be unique
47
+ const pluginMetaData = { name : "rcb-example-plugin" , settings : { } } ;
48
+
49
+ // if auto config is true, then automatically enable the require events (or other settings as required)
50
+ if ( pluginConfig ?. autoConfig ) {
51
+ pluginMetaData . settings = {
52
+ event : {
53
+ rcbPreInjectMessage : true
54
+ }
55
+ }
56
+ }
57
+
58
+ // returns plugin metadata to be consumed by the core library
59
+ return pluginMetaData ;
60
+ } ;
61
+
62
+ export default useRcbPlugin ;
0 commit comments