无法加入Sendbird上的群组频道

时间:2019-03-13 06:45:18

标签: javascript sendbird

总是在尝试加入小组频道时,出现此错误

code: 800101
message: "Connection should be made first."
name: "SendBirdException"

这是我连接到群组频道的代码。

我在另一个函数async中使用connect连接到SendBird,然后才调用connectToChat

该群组是由另一个用户创建的,这是用户尝试加入该群组时的代码。

用户连接工作正常。 小组检索工作正常。

但是当我尝试连接到该群组时,它会出错。

public connectToChat(chatId: string) {
  return new Promise((s, e) => {
    const sendBirdEngine = SendBird.getInstance();

    try {
      if (ChatService.isReady) {
        this.log("Connecting to chat...", chatId);

        sendBirdEngine.GroupChannel.getChannel(
          chatId,
          (groupChannel, error) => {
            if (error) {
              this.logError(
                "An error occured while getting channel",
                chatId,
                error
              );
              return;
            }

            this.log("Got the channel!", chatId, groupChannel);

            if (groupChannel.isPublic) {
              groupChannel.join((response, err) => {
                this.log(
                  "groupChannel Join",
                  response
                  // Always getting error here
                );

                if (err) {
                  this.logError("connectToChat", err);
                  e(false);
                  return;
                } else {
                  s(true);

                  this.log("Joined the Chat!", chatId);
                }

                ChatService.chatRooms[
                  chatId
                ] = groupChannel;

                this.log(
                  "Successfully Cached the Channel",
                  chatId
                );
              });
            } else {
              this.logError("[ERROR] Channel is Private");
            }

            // s(true);
          }
        );
      } else {
        this.logError("[ERROR] Chat Service is not ready");
      }
    } catch (err) {
      e(err);
    }
  });
}

编辑:添加了完整的类文件以供完整参考

class ChatService {
  public static userId: string;

  public static chatRooms: {
    [index: string]: SendBird.BaseChannel;
  } = {};

  private static isReady: boolean = false;

  constructor(userId ? : string) {
    if (userId && !ChatService.userId) {
      ChatService.userId = userId;
    } else {
      this.log("userId already set", ChatService.userId);
    }
  }

  /**
   * create
   */
  public create() {
    return new Promise((s, e) => {
      if (!ChatService.isReady) {
        // connecting to sendbird here
        const sendBirdEngine = new SendBird({
          appId: "XXXXX-XXXXXX-XXXXXX",
        });

        this.log("Engine Initialised!", sendBirdEngine);

        // init the user
        this.initialiseUser((data: any) => {
          s(data);
        });
      }
    });
  }

  /**
   * initialise
   */
  public async initialiseUser(onReadyHandler: any) {
    const userId = ChatService.userId;

    this.log("Starting ChatService", userId);

    try {
      this.connectUserToEngine((res: any) => {
        this.log("connectUser() callback", res);
        ChatService.isReady = true;
        // this.getListOfChatRooms();
        onReadyHandler(true);
      });
    } catch (err) {
      onReadyHandler(false);
      this.log("[ChatService Error]", err);
    }
  }

  /**
   * connects user to engine
   */
  public connectUserToEngine(callback: any) {
    const sendBirdEngine = SendBird.getInstance();
    const userId = ChatService.userId;

    this.log("Connecting user...", userId);

    sendBirdEngine.connect(userId, (user: any, error: any) => {
      if (error) {
        this.log("[Error]", error);
        this.log("Reconnecting User in 5 seconds...");
        setTimeout(() => {
          this.connectUserToEngine(callback);
        }, 5000);
        return;
      } else {
        this.log("User Connected", user);
        callback(user);
      }
    });
  }

  /**
   * connect to a particular chat
   */
  public connectToChat(chatId: string, onNewMessageListener: any) {
    return new Promise((s, e) => {
      const sendBirdEngine = SendBird.getInstance();

      this.log("Current User", sendBirdEngine.currentUser);

      try {
        if (ChatService.isReady) {
          this.log("Connecting to chat...", chatId);

          // this.connectUserToEngine(() => {
          sendBirdEngine.GroupChannel.getChannel(
            chatId,
            (groupChannel, error) => {
              if (error) {
                this.logError(
                  "An error occured while getting channel",
                  chatId,
                  error
                );
                return;
              }

              this.log("Got the channel!", chatId, groupChannel);

              if (groupChannel.isPublic) {
                groupChannel.join((response, err) => {
                  this.log(
                    "groupChannel Join",
                    response
                    // err
                  );

                  // FIXME: Assuming it always works

                  if (err) {
                    this.logError("connectToChat", err);
                    e(false);
                    return;
                  } else {
                    s(true);

                    this.log("Joined the Chat!", chatId);
                  }

                  ChatService.chatRooms[
                    chatId
                  ] = groupChannel;

                  this.log(
                    "Successfully Cached the Channel",
                    chatId
                  );
                });
              } else {
                this.logError("[ERROR] Channel is Private");
              }
              // s(true);
            }
          );
          // });
        } else {
          this.logError("[ERROR] Chat Service is not ready");
        }
      } catch (err) {
        e(err);
      }
    });
  }

  /**
   * connects to all chat rooms
   */
  public async connectToAllChatRooms(
    chatRooms: string[],
    onNewMessageListener: any
  ) {
    try {
      this.log("connectToAllChatRooms()", chatRooms);

      // connect to all chat rooms
      for (const chatRoom of chatRooms) {
        const x = await this.connectToChat(
          chatRoom,
          onNewMessageListener
        );
      }

      this.log("connectToAllChatRooms() done");

      return true;
    } catch (err) {
      this.logError("connectToAllChatRooms", err);
      throw new Error(err);
    }
  }

  export default ChatService;

1 个答案:

答案 0 :(得分:0)

我看了看你的代码。您的ChatService类可能需要一些更改。

想法1

在ChatService类上,如果用户已经存在,则有一个create()方法不会返回promise。

   public create() {
    return new Promise((s, e) => {
      if (!ChatService.isReady) {
        // connecting to sendbird here
        const sendBirdEngine = new SendBird({
          appId: "APP_ID"
        });
        this.log("Engine Initialised!", sendBirdEngine);
        // init the user
        this.initialiseUser((data: any) => {
          s(data);
        });
      } else {
      // Resolve promise when user already exists
        s("Already Connected!");
      }
    });
  }

从那里似乎可以正常工作。如果我错了,请指正我,但这就是我实现班级的方式。

const initChat = () => {
  const url = "CHANNEL_URL";
  const chat = new ChatService("USER_ID");
  chat.create().then(res => {
    chat.connectToChat(url).then((res)=>{
      console.log("DONE", res)
    })
  });
};

想法2

也:也许检查一下您是否在打电话

sendBirdEngine.GroupChannel.getChannel()

与用户的连接完成之前。

示例

如果需要,这里是代码的working example。它需要:

  • index.js-CHANNEL_URL和USER_ID
  • ChatService.ts-APP_ID