Skip to content

Commit

Permalink
feat: Created option to sendTextMessage
Browse files Browse the repository at this point in the history
  • Loading branch information
edgardmessias committed Sep 11, 2021
1 parent ca316cc commit a979a82
Show file tree
Hide file tree
Showing 14 changed files with 342 additions and 86 deletions.
45 changes: 45 additions & 0 deletions src/assert/assertChat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import Chat from '../chat';
import { WPPError } from '../util';
import { ChatModel, Wid } from '../whatsapp';

export class InvalidChat extends WPPError {
constructor(readonly id: string | { _serialized: string }) {
super('chat_not_found', `Chat not found for ${id}`);
}
}

export async function assertFindChat(id: string | Wid): Promise<ChatModel> {
const chat = await Chat.find(id);

if (!chat) {
throw new InvalidChat(id);
}

return chat;
}

export function assertGetChat(id: string | Wid): ChatModel {
const chat = Chat.get(id);

if (!chat) {
throw new InvalidChat(id);
}

return chat;
}
34 changes: 34 additions & 0 deletions src/assert/assertWid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { createWid, WPPError } from '../util';
import { Wid } from '../whatsapp';

export class InvalidWid extends WPPError {
constructor(readonly id: string | { _serialized: string }) {
super('invalid_wid', `Invalid WID value for ${id}`);
}
}

export function assertWid(id: string | { _serialized: string }): Wid {
const wid = createWid(id);

if (!wid) {
throw new InvalidWid(id);
}

return wid;
}
18 changes: 18 additions & 0 deletions src/assert/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export * from './assertChat';
export * from './assertWid';
135 changes: 135 additions & 0 deletions src/chat/Chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import Debug from 'debug';
import Emittery from 'emittery';

import { assertFindChat, assertGetChat, assertWid } from '../assert';
import * as webpack from '../webpack';
import {
ChatModel,
ChatStore,
ClockSkew,
Constants,
MsgKey,
UserPrefs,
Wid,
} from '../whatsapp';
import {
addAndSendMsgToChat,
findChat,
randomMessageId,
} from '../whatsapp/functions';
import { ChatRawMessage } from '.';
import { ChatEventTypes, ChatSendMessageOptions } from './types';

const debugChat = Debug('WPP:chat');
const debugMessage = Debug('WPP:message');

export class Chat extends Emittery<ChatEventTypes> {
constructor() {
super();
webpack.onInjected(() => this.initialize());
}

async initialize() {
ChatStore.on(Constants.COLLECTION_HAS_SYNCED, () => {
debugChat(Constants.COLLECTION_HAS_SYNCED);
});

debugChat('initialized');
}

async find(chatId: string | Wid): Promise<ChatModel> {
const wid = assertWid(chatId);
return findChat(wid);
}

get(chatId: string | Wid): ChatModel | undefined {
const wid = assertWid(chatId);
return ChatStore.get(wid);
}

async sendRawMessage(
chatId: any,
message: ChatRawMessage,
options: ChatSendMessageOptions = {}
): Promise<any> {
const chat = options.createChat
? await assertFindChat(chatId)
: assertGetChat(chatId);

message = Object.assign(
{},
{
t: ClockSkew.globalUnixTime(),
from: UserPrefs.getMaybeMeUser(),
to: chat.id,
self: 'out',
isNewMsg: true,
local: true,
ack: Constants.ACK.CLOCK,
},
message
);

if (!message.id) {
message.id = new MsgKey({
from: UserPrefs.getMaybeMeUser(),
to: chat.id,
id: randomMessageId(),
selfDir: 'out',
});
}

debugMessage(`sending message (${message.type}) with id ${message.id}`);
const result = await addAndSendMsgToChat(chat, message);
debugMessage(`message ${message.id} queued`);

const finalMessage = await result[0];

if (options.waitForAck) {
debugMessage(`waiting ack for ${message.id}`);

await result[1];

debugMessage(`ack received for ${message.id} (ACK: ${finalMessage.ack})`);
}

return {
id: finalMessage.id.toString(),
ack: finalMessage.ack,
};
}

async sendTextMessage(
chatId: any,
content: any,
options: ChatSendMessageOptions = {}
): Promise<any> {
const message: ChatRawMessage = {
body: content,
type: 'chat',
subtype: null,
urlText: null,
urlNumber: null,
};

const result = await this.sendRawMessage(chatId, message, options);

return result;
}
}
65 changes: 4 additions & 61 deletions src/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,66 +14,9 @@
* limitations under the License.
*/

import * as util from '../util';
import {
ChatModel,
ChatStore,
ClockSkew,
Constants,
ModelPropertiesContructor,
MsgKey,
MsgModel,
UserPrefs,
} from '../whatsapp';
import { addAndSendMsgToChat, randomMessageId } from '../whatsapp/functions';
import { Chat } from './Chat';

export function get(chatId: string): ChatModel | undefined {
const wid = util.createWid(chatId);
export * from './Chat';
export * from './types';

if (!wid) {
throw 'invalid id';
}

return ChatStore.get(wid);
}

export async function sendMessage(
chatId: any,
content: any,
options = {}
): Promise<any> {
console.log(options);

const chat = get(chatId);

if (!chat) {
return null;
}

const newMsgId = new MsgKey({
from: UserPrefs.getMaybeMeUser(),
to: chat.id,
id: randomMessageId(),
selfDir: 'out',
});

const message: ModelPropertiesContructor<MsgModel, 'id'> = {
id: newMsgId,
body: content,
type: 'chat',
subtype: null,
t: ClockSkew.globalUnixTime(),
from: UserPrefs.getMaybeMeUser(),
to: chat.id,
self: 'out',
isNewMsg: true,
local: true,
ack: Constants.ACK.CLOCK,
urlText: null,
urlNumber: null,
};

const result = await addAndSendMsgToChat(chat, message);

return result;
}
export default new Chat();
29 changes: 29 additions & 0 deletions src/chat/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { ModelPropertiesContructor, MsgModel } from '../whatsapp';

export interface ChatEventTypes {
change: string;
idle: undefined;
}

export interface ChatSendMessageOptions {
waitForAck?: boolean;
createChat?: boolean;
}

export type ChatRawMessage = ModelPropertiesContructor<MsgModel>;
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import * as webpack from './webpack';

export { webpack };
export { default as auth } from './auth';
export * as chat from './chat';
export { default as chat } from './chat';
export { isInjected, isReady } from './webpack';
export * as whatsapp from './whatsapp';

Expand Down
21 changes: 21 additions & 0 deletions src/util/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*!
* Copyright 2021 WPPConnect Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export class WPPError extends Error {
constructor(readonly code: string, message: string) {
super(message);
}
}
1 change: 1 addition & 0 deletions src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@
*/

export * from './createWid';
export * from './errors';
export * from './types';
2 changes: 1 addition & 1 deletion src/whatsapp/functions/addAndSendMsgToChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { ChatModel, ModelPropertiesContructor, MsgModel } from '../models';
export declare function addAndSendMsgToChat(
chat: ChatModel,
message: ModelPropertiesContructor<MsgModel>
): Promise<string>;
): Promise<[Promise<MsgModel>, Promise<string>]>;

exportModule(
exports,
Expand Down
Loading

0 comments on commit a979a82

Please sign in to comment.