Skip to content

Commit

Permalink
feat: Add call suppoirt
Browse files Browse the repository at this point in the history
  • Loading branch information
laxeder committed Jun 10, 2024
1 parent 17d692f commit d3b68a4
Show file tree
Hide file tree
Showing 13 changed files with 2,050 additions and 402 deletions.
73 changes: 55 additions & 18 deletions example/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import Client, { WhatsAppBot, Message, Command, CMDRunType, CMDPerms, EmptyMessage, MultiFileAuthState, QuickResponse, ChatType } from "../src";
import Client, {
WhatsAppBot,
Message,
Command,
CMDRunType,
CMDPerms,
EmptyMessage,
MultiFileAuthState,
QuickResponse,
ChatType,
} from "../src";

const wbot = new WhatsAppBot({
autoSyncHistory: false,
Expand Down Expand Up @@ -110,6 +120,14 @@ client.on("user", async (update) => {
}
});

client.on("new-call", async (call) => {
console.info("Nova chamada:", call);

await call.reject();

await call.chat.send("Não aceitamos chamadas!");
});

client.on("error", (err: any) => {
console.info("Um erro ocorreu:", err);
});
Expand All @@ -122,28 +140,45 @@ client.on("error", (err: any) => {
client.commandController.config.prefix = "/";
client.commandController.config.lowerCase = true;

client.commandController.on("no-allowed", async ({ message, command, permission }) => {
if (permission.id == CMDPerms.BotChatAdmin) {
await message.reply("Eu preciso de permissão de admin para executar esse comando!");
}

if (permission.id == CMDPerms.UserChatAdmin) {
await message.reply("Somente admins podem usar esse comando!");
}

if (permission.id == CMDPerms.ChatGroup) {
await message.chat.send("Somente grupos podem usar esse comando!");
client.commandController.on(
"no-allowed",
async ({ message, command, permission }) => {
if (permission.id == CMDPerms.BotChatAdmin) {
await message.reply(
"Eu preciso de permissão de admin para executar esse comando!"
);
}

if (permission.id == CMDPerms.UserChatAdmin) {
await message.reply("Somente admins podem usar esse comando!");
}

if (permission.id == CMDPerms.ChatGroup) {
await message.chat.send("Somente grupos podem usar esse comando!");
}
}
});
);

const quickResponse1 = new QuickResponse(["comprar", "pedido", "quero"], "Vamos fazer um pedido?");
const quickResponse1 = new QuickResponse(
["comprar", "pedido", "quero"],
"Vamos fazer um pedido?"
);

const quickResponse2 = new QuickResponse(/vendem(.*?)\?/, "Vou estar conferindo...", { priority: 1 });
const quickResponse2 = new QuickResponse(
/vendem(.*?)\?/,
"Vou estar conferindo...",
{ priority: 1 }
);

const quickResponse3 = new QuickResponse({ patterns: ["hello", "hi", /ola(.*?)\!/], reply: "Hello There!", priority: 2 });
const quickResponse3 = new QuickResponse({
patterns: ["hello", "hi", /ola(.*?)\!/],
reply: "Hello There!",
priority: 2,
});

const quickResponse4 = new QuickResponse(
(text, message) => message.chat.type !== ChatType.Group && text.includes("hi"),
(text, message) =>
message.chat.type !== ChatType.Group && text.includes("hi"),
(message) => `Hello ${message.chat.name}!`,
{ priority: 1 }
);
Expand All @@ -156,5 +191,7 @@ client.on("error", (err: any) => {
//? Ao inserir o número do bot é ativado o pareamento por código
const botPhoneNumber = "";

await client.connect(new MultiFileAuthState("./example/sessions/whatsapp", botPhoneNumber));
await client.connect(
new MultiFileAuthState("./example/sessions/whatsapp", botPhoneNumber)
);
})();
49 changes: 40 additions & 9 deletions src/bot/BotBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import BotEvents from "./BotEvents";
import Chat from "../chat/Chat";
import User from "../user/User";
import IBot from "./IBot";
import Call from "../models/Call";

export default class BotBase extends BotEvents implements IBot {
public id: string = "";
Expand Down Expand Up @@ -36,7 +37,11 @@ export default class BotBase extends BotEvents implements IBot {
return message;
}

public async sendMessage(chat: Chat | string, message: string | Message, mention?: Message): Promise<Message> {
public async sendMessage(
chat: Chat | string,
message: string | Message,
mention?: Message
): Promise<Message> {
return new Promise<Message>(() => {});
}

Expand Down Expand Up @@ -96,7 +101,9 @@ export default class BotBase extends BotEvents implements IBot {
return null;
}

public async updateChat(chat: { id: string } & Partial<Chat>): Promise<void> {}
public async updateChat(
chat: { id: string } & Partial<Chat>
): Promise<void> {}

public async removeChat(chat: Chat): Promise<void> {}

Expand All @@ -112,7 +119,10 @@ export default class BotBase extends BotEvents implements IBot {

public async demoteUserInChat(chat: Chat, user: User): Promise<void> {}

public async changeChatStatus(chat: Chat, status: ChatStatus): Promise<void> {}
public async changeChatStatus(
chat: Chat,
status: ChatStatus
): Promise<void> {}

public async getChatUsers(chat: Chat): Promise<string[]> {
return [];
Expand All @@ -136,13 +146,22 @@ export default class BotBase extends BotEvents implements IBot {
return "";
}

public async setChatDescription(chat: Chat, description: string): Promise<void> {}
public async setChatDescription(
chat: Chat,
description: string
): Promise<void> {}

public async getChatProfile(chat: Chat, lowQuality?: boolean): Promise<Buffer> {
public async getChatProfile(
chat: Chat,
lowQuality?: boolean
): Promise<Buffer> {
return Buffer.from("");
}

public async getChatProfileUrl(chat: Chat, lowQuality?: boolean): Promise<string> {
public async getChatProfileUrl(
chat: Chat,
lowQuality?: boolean
): Promise<string> {
return "";
}

Expand All @@ -158,6 +177,10 @@ export default class BotBase extends BotEvents implements IBot {
return "";
}

public async rejectCall(call: Call): Promise<void> {
return;
}

//! #################################################################
//! ########## MÉTODOS DO USUÁRIO
//! #################################################################
Expand All @@ -172,7 +195,9 @@ export default class BotBase extends BotEvents implements IBot {
return null;
}

public async updateUser(user: { id: string } & Partial<User>): Promise<void> {}
public async updateUser(
user: { id: string } & Partial<User>
): Promise<void> {}

public async removeUser(user: User): Promise<void> {}

Expand All @@ -190,13 +215,19 @@ export default class BotBase extends BotEvents implements IBot {
return "";
}

public async setUserDescription(user: User, description: string): Promise<void> {}
public async setUserDescription(
user: User,
description: string
): Promise<void> {}

public async getUserProfile(user: User): Promise<Buffer> {
return Buffer.from("");
}

public async getUserProfileUrl(user: User, lowQuality?: boolean): Promise<string> {
public async getUserProfileUrl(
user: User,
lowQuality?: boolean
): Promise<string> {
return "";
}

Expand Down
24 changes: 18 additions & 6 deletions src/bot/BotEvents.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import EventEmitter from "events";

import { ChatAction } from "../chat/ChatAction";
import { UserAction } from "../user/UserAction";
import { UserEvent } from "../user/UserEvent";
import { UserAction } from "../user/UserAction";
import { ChatAction } from "../chat/ChatAction";

import Message from "../messages/Message";
import Chat from "../chat/Chat";
import User from "../user/User";
import Call from "../models/Call";
import Message from "../messages/Message";
/**
* Mapeia os eventos disponíveis para um bot.
*/
Expand Down Expand Up @@ -48,6 +49,8 @@ export type BotEventsMap = {
};
/** Ocorre quando uma nova mensagem é recebida pelo bot. */
message: Message;
/** Ocorre ao receber uma atualizaçãod e chamada */
call: Call;
/** Ocorre quando um erro é detectado. */
error: Error;
};
Expand All @@ -64,7 +67,10 @@ export default class BotEvents {
* @param eventName - O nome do evento ao qual o ouvinte será associado.
* @param listener - A função que será chamada quando o evento ocorrer.
*/
public on<T extends keyof BotEventsMap>(eventName: T, listener: (arg: BotEventsMap[T]) => void) {
public on<T extends keyof BotEventsMap>(
eventName: T,
listener: (arg: BotEventsMap[T]) => void
) {
this.ev.on(eventName, listener);
}

Expand All @@ -73,7 +79,10 @@ export default class BotEvents {
* @param eventName - O nome do evento do qual o ouvinte será removido.
* @param listener - A função de ouvinte a ser removida.
*/
public off<T extends keyof BotEventsMap>(eventName: T, listener: (arg: BotEventsMap[T]) => void): void {
public off<T extends keyof BotEventsMap>(
eventName: T,
listener: (arg: BotEventsMap[T]) => void
): void {
this.ev.off(eventName, listener);
}

Expand All @@ -91,7 +100,10 @@ export default class BotEvents {
* @param arg - Os argumentos a serem passados para os ouvintes.
* @returns Verdadeiro se algum ouvinte for chamado, caso contrário, falso.
*/
public emit<T extends keyof BotEventsMap>(eventName: T, arg: BotEventsMap[T]): boolean {
public emit<T extends keyof BotEventsMap>(
eventName: T,
arg: BotEventsMap[T]
): boolean {
if (this.eventsIsStoped) return false;

return this.ev.emit(eventName, arg);
Expand Down
7 changes: 7 additions & 0 deletions src/bot/IBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import IAuth from "../client/IAuth";
import BotEvents from "./BotEvents";
import User from "../user/User";
import Chat from "../chat/Chat";
import Call from "../models/Call";

/** Interface do bot */
export default interface IBot extends BotEvents {
Expand Down Expand Up @@ -265,6 +266,12 @@ export default interface IBot extends BotEvents {
*/
revokeChatInvite(chat: Chat): Promise<string>;

/**
* Rejeita uma chamada.
* @param call - A chamada que será rejeitada.
*/
rejectCall(call: Call): Promise<void>;

/**
* @param user Usuário
* @returns Retorna um usuário
Expand Down
Loading

0 comments on commit d3b68a4

Please sign in to comment.