Comparing version 2.1.22 to 2.1.23
@@ -10,3 +10,2 @@ "use strict"; | ||
this.text = this.data.text; | ||
// this.fromChatId = (this.data as NewMessageEvent).chat.chatId | ||
this.messageAuthor = this.data.from; | ||
@@ -13,0 +12,0 @@ } |
@@ -33,3 +33,3 @@ "use strict"; | ||
for (var i in this.cache) { | ||
console.log(i, event.data.msgId, this.cache[i], event.text); | ||
// console.log(i,(event.data as NewMessageEvent).msgId, this.cache[i], event.text) | ||
if (i && i == event.data.msgId && this.cache[i] == event.text) { | ||
@@ -36,0 +36,0 @@ // return false; |
@@ -5,6 +5,24 @@ import { Bot } from "./class/Bot"; | ||
import { ICQButton } from "./class/ICQButton"; | ||
/** | ||
* Фасад ICQ | ||
*/ | ||
export default class ICQ { | ||
/** | ||
* Класс кнопки для сообщений | ||
*/ | ||
static Button: typeof ICQButton; | ||
/** | ||
* Бот для вызова | ||
*/ | ||
static Bot: typeof Bot; | ||
static Filter: Filter; | ||
/** | ||
* Базовые фильтры для обработчиков | ||
*/ | ||
static Filter: typeof Filter; | ||
/** | ||
* Базовые обработчики. | ||
* | ||
* Обратите внимание, что если под одно событие | ||
* подходят несколько обработчиков, то будут вызваны оба. | ||
*/ | ||
static Handler: { | ||
@@ -11,0 +29,0 @@ HelpCommand: typeof ICQHelpCommandHandler; |
@@ -7,8 +7,26 @@ "use strict"; | ||
var ICQButton_1 = require("./class/ICQButton"); | ||
/** | ||
* Фасад ICQ | ||
*/ | ||
var ICQ = (function () { | ||
function ICQ() { | ||
} | ||
/** | ||
* Класс кнопки для сообщений | ||
*/ | ||
ICQ.Button = ICQButton_1.ICQButton; | ||
/** | ||
* Бот для вызова | ||
*/ | ||
ICQ.Bot = Bot_1.Bot; | ||
ICQ.Filter = new Filter_1.Filter(); | ||
/** | ||
* Базовые фильтры для обработчиков | ||
*/ | ||
ICQ.Filter = Filter_1.Filter; | ||
/** | ||
* Базовые обработчики. | ||
* | ||
* Обратите внимание, что если под одно событие | ||
* подходят несколько обработчиков, то будут вызваны оба. | ||
*/ | ||
ICQ.Handler = { | ||
@@ -15,0 +33,0 @@ HelpCommand: Handler_1.HelpCommandHandler, |
@@ -9,2 +9,3 @@ import { NewMessageEvent } from "./NewMessageEvent"; | ||
import { CallbackQueryEvent } from "./CallbackQueryEvent"; | ||
/** Типы сообщений */ | ||
export declare enum EventType { | ||
@@ -24,2 +25,6 @@ NEW_MESSAGE = "newMessage", | ||
} | ||
/** | ||
* Каждое событие имеет идентификатор eventId и type | ||
* В зависимости от type параметра будет разная полезная нагрузка payload. | ||
*/ | ||
export interface Event { | ||
@@ -26,0 +31,0 @@ eventId: number; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** Типы сообщений */ | ||
var EventType; | ||
@@ -4,0 +5,0 @@ (function (EventType) { |
import { ICQEvent } from "../class/ICQEvent"; | ||
export interface Filter { | ||
export interface Filters { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** Фильтр проверяет тип события и наличие текста в нём */ | ||
export declare class MessageFilter implements Filter { | ||
export declare class MessageFilter implements Filters { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** Фильтр проверяет наличие первого символа на равенство "/" или "." */ | ||
export declare class CommandFilter extends MessageFilter { | ||
@@ -13,2 +14,3 @@ COMMAND_PREFIXES: String[]; | ||
} | ||
/** Фильтр проверяет регулярным выражением текст сообщения и фильтрует по нему */ | ||
export declare class RegexpFilter extends MessageFilter { | ||
@@ -19,2 +21,5 @@ pattern: RegExp; | ||
} | ||
/** | ||
* Фильтрует сообщения конкретного пользователя | ||
*/ | ||
export declare class SenderFilter extends MessageFilter { | ||
@@ -25,17 +30,35 @@ private user_id; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа файл | ||
*/ | ||
export declare class FileFilter extends MessageFilter { | ||
filter(event: any): boolean; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа изображение | ||
*/ | ||
export declare class ImageFilter extends FileFilter { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа видел | ||
*/ | ||
export declare class VideoFilter extends FileFilter { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа Аудио | ||
*/ | ||
export declare class AudioFilter extends FileFilter { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа Стикер | ||
*/ | ||
export declare class StickerFilter extends MessageFilter { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** | ||
* Фильтрует события где был упомянут пользователь | ||
*/ | ||
export declare class MentionFilter extends MessageFilter { | ||
@@ -46,8 +69,17 @@ userId: Number; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типо FORWARD - Перенаправленное (Пересылаемое сообщение) | ||
*/ | ||
export declare class ForwardFilter extends MessageFilter { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типо Reply - Цитата сообщения | ||
*/ | ||
export declare class ReplyFilter extends MessageFilter { | ||
filter(event: ICQEvent): boolean; | ||
} | ||
/** | ||
* Фильтрует сообщения состоящии из одной URL ссылки. Допускаются пробелы в начале и конце сообщения. | ||
*/ | ||
export declare class URLFilter extends RegexpFilter { | ||
@@ -57,2 +89,3 @@ constructor(); | ||
} | ||
/** Типы операций над фильтрами */ | ||
export declare enum TypeFilterOperation { | ||
@@ -63,29 +96,91 @@ and = 1, | ||
} | ||
export declare class FilterComposite implements Filter { | ||
/** Создаёт композитный фильтр из двух, применяя к ним оператор сравнения. Рекомендую использовать статические методы and, or, not */ | ||
export declare class FilterComposite implements Filters { | ||
private type; | ||
private leftFilter; | ||
private rightFilter; | ||
constructor(type: TypeFilterOperation, leftFilter: Filter, rightFilter?: Filter); | ||
static and(leftFilter: Filter, rightFilter: Filter): FilterComposite; | ||
static or(leftFilter: Filter, rightFilter: Filter): FilterComposite; | ||
static not(filter: Filter): FilterComposite; | ||
constructor(type: TypeFilterOperation, leftFilter: Filters, rightFilter?: Filters); | ||
static and(leftFilter: Filters, rightFilter: Filters): FilterComposite; | ||
static or(leftFilter: Filters, rightFilter: Filters): FilterComposite; | ||
static not(filter: Filters): FilterComposite; | ||
filter(event: ICQEvent): boolean; | ||
} | ||
export declare class Filter { | ||
/** | ||
* Фильтр проверяет тип события | ||
* и наличие текста в нём | ||
*/ | ||
static message: MessageFilter; | ||
/** | ||
* Фильтр проверяет наличие первого | ||
* символа на равенство "/" или "." | ||
*/ | ||
static command: CommandFilter; | ||
/** Фильтрует сообщения конкретного пользователя */ | ||
static file: FileFilter; | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа изображение | ||
*/ | ||
static image: ImageFilter; | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Видео | ||
*/ | ||
static video: VideoFilter; | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Аудио | ||
*/ | ||
static audio: AudioFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типа Аудио, Видео, Изображение | ||
*/ | ||
static media: FilterComposite; | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Аудио, | ||
* Видео, Изображение, Файл | ||
*/ | ||
static data: FilterComposite; | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Стикер | ||
*/ | ||
static sticker: StickerFilter; | ||
/** | ||
* Фильтрует сообщения состоящии из одной URL ссылки. | ||
* Допускаются пробелы в начале и конце сообщения. | ||
*/ | ||
static url: URLFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типа Аудио, Видео, | ||
* Изображение, Файл, Стикер, Ссылка | ||
* | ||
* Все сообщения у которых может быть текст. | ||
*/ | ||
static text: FilterComposite; | ||
/** | ||
* Фильтр проверяет регулярным выражением | ||
* текст сообщения и фильтрует по нему | ||
*/ | ||
static regexp: typeof RegexpFilter; | ||
/** | ||
* Фильтрует события где был упомянут пользователь | ||
*/ | ||
static mention: typeof MentionFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типо FORWARD - | ||
* Перенаправленное (Пересылаемое сообщение) */ | ||
static forward: ForwardFilter; | ||
/** Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типо Reply - Цитата сообщения */ | ||
static reply: ReplyFilter; | ||
/** | ||
* Фильтрует сообщения отпраленные конкретным пользователем | ||
*/ | ||
static sender: typeof SenderFilter; | ||
} |
@@ -24,2 +24,3 @@ "use strict"; | ||
exports.MessageFilter = MessageFilter; | ||
/** Фильтр проверяет наличие первого символа на равенство "/" или "." */ | ||
var CommandFilter = (function (_super) { | ||
@@ -38,2 +39,3 @@ __extends(CommandFilter, _super); | ||
exports.CommandFilter = CommandFilter; | ||
/** Фильтр проверяет регулярным выражением текст сообщения и фильтрует по нему */ | ||
var RegexpFilter = (function (_super) { | ||
@@ -52,2 +54,5 @@ __extends(RegexpFilter, _super); | ||
exports.RegexpFilter = RegexpFilter; | ||
/** | ||
* Фильтрует сообщения конкретного пользователя | ||
*/ | ||
var SenderFilter = (function (_super) { | ||
@@ -66,2 +71,5 @@ __extends(SenderFilter, _super); | ||
exports.SenderFilter = SenderFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа файл | ||
*/ | ||
var FileFilter = (function (_super) { | ||
@@ -79,2 +87,5 @@ __extends(FileFilter, _super); | ||
exports.FileFilter = FileFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа изображение | ||
*/ | ||
var ImageFilter = (function (_super) { | ||
@@ -92,2 +103,5 @@ __extends(ImageFilter, _super); | ||
exports.ImageFilter = ImageFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа видел | ||
*/ | ||
var VideoFilter = (function (_super) { | ||
@@ -105,2 +119,5 @@ __extends(VideoFilter, _super); | ||
exports.VideoFilter = VideoFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа Аудио | ||
*/ | ||
var AudioFilter = (function (_super) { | ||
@@ -118,2 +135,5 @@ __extends(AudioFilter, _super); | ||
exports.AudioFilter = AudioFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа Стикер | ||
*/ | ||
var StickerFilter = (function (_super) { | ||
@@ -131,2 +151,5 @@ __extends(StickerFilter, _super); | ||
exports.StickerFilter = StickerFilter; | ||
/** | ||
* Фильтрует события где был упомянут пользователь | ||
*/ | ||
var MentionFilter = (function (_super) { | ||
@@ -147,2 +170,5 @@ __extends(MentionFilter, _super); | ||
exports.MentionFilter = MentionFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типо FORWARD - Перенаправленное (Пересылаемое сообщение) | ||
*/ | ||
var ForwardFilter = (function (_super) { | ||
@@ -159,2 +185,5 @@ __extends(ForwardFilter, _super); | ||
exports.ForwardFilter = ForwardFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типо Reply - Цитата сообщения | ||
*/ | ||
var ReplyFilter = (function (_super) { | ||
@@ -172,2 +201,5 @@ __extends(ReplyFilter, _super); | ||
exports.ReplyFilter = ReplyFilter; | ||
/** | ||
* Фильтрует сообщения состоящии из одной URL ссылки. Допускаются пробелы в начале и конце сообщения. | ||
*/ | ||
var URLFilter = (function (_super) { | ||
@@ -184,2 +216,3 @@ __extends(URLFilter, _super); | ||
exports.URLFilter = URLFilter; | ||
/** Типы операций над фильтрами */ | ||
var TypeFilterOperation; | ||
@@ -191,2 +224,3 @@ (function (TypeFilterOperation) { | ||
})(TypeFilterOperation = exports.TypeFilterOperation || (exports.TypeFilterOperation = {})); | ||
/** Создаёт композитный фильтр из двух, применяя к ним оператор сравнения. Рекомендую использовать статические методы and, or, not */ | ||
var FilterComposite = (function () { | ||
@@ -224,17 +258,78 @@ function FilterComposite(type, leftFilter, rightFilter) { | ||
} | ||
/** | ||
* Фильтр проверяет тип события | ||
* и наличие текста в нём | ||
*/ | ||
Filter.message = new MessageFilter(); | ||
/** | ||
* Фильтр проверяет наличие первого | ||
* символа на равенство "/" или "." | ||
*/ | ||
Filter.command = new CommandFilter(); | ||
/** Фильтрует сообщения конкретного пользователя */ | ||
Filter.file = new FileFilter(); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа изображение | ||
*/ | ||
Filter.image = new ImageFilter(); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Видео | ||
*/ | ||
Filter.video = new VideoFilter(); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Аудио | ||
*/ | ||
Filter.audio = new AudioFilter(); | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типа Аудио, Видео, Изображение | ||
*/ | ||
Filter.media = FilterComposite.or(FilterComposite.or(Filter.image, Filter.video), Filter.audio); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Аудио, | ||
* Видео, Изображение, Файл | ||
*/ | ||
Filter.data = FilterComposite.and(Filter.file, FilterComposite.not(Filter.media)); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Стикер | ||
*/ | ||
Filter.sticker = new StickerFilter(); | ||
/** | ||
* Фильтрует сообщения состоящии из одной URL ссылки. | ||
* Допускаются пробелы в начале и конце сообщения. | ||
*/ | ||
Filter.url = new URLFilter(); | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типа Аудио, Видео, | ||
* Изображение, Файл, Стикер, Ссылка | ||
* | ||
* Все сообщения у которых может быть текст. | ||
*/ | ||
Filter.text = FilterComposite.and(Filter.message, FilterComposite.not(FilterComposite.or(FilterComposite.or(FilterComposite.or(Filter.command, Filter.sticker), Filter.file), Filter.url))); | ||
/** | ||
* Фильтр проверяет регулярным выражением | ||
* текст сообщения и фильтрует по нему | ||
*/ | ||
Filter.regexp = RegexpFilter; | ||
/** | ||
* Фильтрует события где был упомянут пользователь | ||
*/ | ||
Filter.mention = MentionFilter; | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типо FORWARD - | ||
* Перенаправленное (Пересылаемое сообщение) */ | ||
Filter.forward = new ForwardFilter(); | ||
/** Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типо Reply - Цитата сообщения */ | ||
Filter.reply = new ReplyFilter(); | ||
/** | ||
* Фильтрует сообщения отпраленные конкретным пользователем | ||
*/ | ||
Filter.sender = SenderFilter; | ||
@@ -241,0 +336,0 @@ return Filter; |
@@ -1,4 +0,3 @@ | ||
import { Filter } from "./Filter"; | ||
import { Filters } from "./Filter"; | ||
import { Dispatcher } from "./Dispatcher"; | ||
import { Bot } from "../class/Bot"; | ||
import { ICQBot } from "./ICQBot"; | ||
@@ -14,9 +13,28 @@ import { ICQEvent } from "../class/ICQEvent"; | ||
} | ||
/** | ||
* Базовый обработчик. | ||
* | ||
* Срабатывает на все события если не установлен фильтр | ||
* или на события отфильтрованные установленным фильтром | ||
*/ | ||
export declare class HandlerBase implements Handler { | ||
protected filters: Filter; | ||
protected filters: Filters; | ||
protected callback: (bot: ICQBot, event: ICQEvent) => void; | ||
constructor(filters: Filter, callback: (bot: ICQBot, event: ICQEvent) => void); | ||
/** | ||
* Параметр filters может быть равен null. | ||
* В таком случае вызов callback будет происходить | ||
* каждый раз, когда приходит событие | ||
* | ||
* @param filters Фильтр | ||
* @param callback Функция обратного вызова | ||
*/ | ||
constructor(filters: Filters, callback: (bot: ICQBot, event: ICQEvent) => void); | ||
check(event: ICQEvent, dispatcher: Dispatcher): boolean; | ||
handle(event: ICQEvent, dispatcher: Dispatcher): void; | ||
} | ||
/** | ||
* Обработчик для всех событий | ||
* | ||
* Срабатывает всегда, когда приходит событие из пуллинга | ||
*/ | ||
export declare class DefaultHandler extends HandlerBase { | ||
@@ -28,23 +46,55 @@ constructor(callback?: any); | ||
} | ||
/** | ||
* Обработчик новых участников группового чата | ||
* | ||
* Срабатывает когда в группу вступает новый пользователь | ||
*/ | ||
export declare class NewChatMembersHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик выхода из группы участника | ||
*/ | ||
export declare class LeftChatMembersHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик закрепа сообщения в чате | ||
*/ | ||
export declare class PinnedMessageHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик открепления сообщения в чате | ||
*/ | ||
export declare class UnPinnedMessageHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик текстовых сообщений | ||
*/ | ||
export declare class MessageHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик событий редактирования сообщений | ||
*/ | ||
export declare class EditedMessageHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик событий удаления сообщений | ||
*/ | ||
export declare class DeletedMessageHandler extends HandlerBase { | ||
check(event: any, dispatcher: any): boolean; | ||
} | ||
/** | ||
* Обработчик комманд | ||
* | ||
* new CommandHandler("test", null, (bot, event) => {}) | ||
* | ||
* new CommandHandler(["test"], null, (bot, event) => {}) | ||
* | ||
* Пример комманд .test или /test | ||
*/ | ||
export declare class CommandHandler extends MessageHandler { | ||
@@ -70,3 +120,4 @@ protected command: any; | ||
constructor(target: string, message?: string, reply?: string, error_reply?: any, command?: string, filters?: any); | ||
message_cb(bot: Bot, event: ICQEvent): Promise<void>; | ||
check(event: any, dispatcher: any): boolean; | ||
private message_cb(bot, event); | ||
} | ||
@@ -73,0 +124,0 @@ export declare class UnknownCommandHandler extends CommandHandler { |
@@ -48,4 +48,19 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var Filter_1 = require("./Filter"); | ||
var Event_1 = require("./Events/Event"); | ||
/** | ||
* Базовый обработчик. | ||
* | ||
* Срабатывает на все события если не установлен фильтр | ||
* или на события отфильтрованные установленным фильтром | ||
*/ | ||
var HandlerBase = (function () { | ||
/** | ||
* Параметр filters может быть равен null. | ||
* В таком случае вызов callback будет происходить | ||
* каждый раз, когда приходит событие | ||
* | ||
* @param filters Фильтр | ||
* @param callback Функция обратного вызова | ||
*/ | ||
function HandlerBase(filters, callback) { | ||
@@ -66,2 +81,7 @@ this.filters = filters; | ||
exports.HandlerBase = HandlerBase; | ||
/** | ||
* Обработчик для всех событий | ||
* | ||
* Срабатывает всегда, когда приходит событие из пуллинга | ||
*/ | ||
var DefaultHandler = (function (_super) { | ||
@@ -92,2 +112,7 @@ __extends(DefaultHandler, _super); | ||
exports.DefaultHandler = DefaultHandler; | ||
/** | ||
* Обработчик новых участников группового чата | ||
* | ||
* Срабатывает когда в группу вступает новый пользователь | ||
*/ | ||
var NewChatMembersHandler = (function (_super) { | ||
@@ -104,2 +129,5 @@ __extends(NewChatMembersHandler, _super); | ||
exports.NewChatMembersHandler = NewChatMembersHandler; | ||
/** | ||
* Обработчик выхода из группы участника | ||
*/ | ||
var LeftChatMembersHandler = (function (_super) { | ||
@@ -116,2 +144,5 @@ __extends(LeftChatMembersHandler, _super); | ||
exports.LeftChatMembersHandler = LeftChatMembersHandler; | ||
/** | ||
* Обработчик закрепа сообщения в чате | ||
*/ | ||
var PinnedMessageHandler = (function (_super) { | ||
@@ -128,2 +159,5 @@ __extends(PinnedMessageHandler, _super); | ||
exports.PinnedMessageHandler = PinnedMessageHandler; | ||
/** | ||
* Обработчик открепления сообщения в чате | ||
*/ | ||
var UnPinnedMessageHandler = (function (_super) { | ||
@@ -140,2 +174,5 @@ __extends(UnPinnedMessageHandler, _super); | ||
exports.UnPinnedMessageHandler = UnPinnedMessageHandler; | ||
/** | ||
* Обработчик текстовых сообщений | ||
*/ | ||
var MessageHandler = (function (_super) { | ||
@@ -152,2 +189,5 @@ __extends(MessageHandler, _super); | ||
exports.MessageHandler = MessageHandler; | ||
/** | ||
* Обработчик событий редактирования сообщений | ||
*/ | ||
var EditedMessageHandler = (function (_super) { | ||
@@ -165,2 +205,5 @@ __extends(EditedMessageHandler, _super); | ||
exports.EditedMessageHandler = EditedMessageHandler; | ||
/** | ||
* Обработчик событий удаления сообщений | ||
*/ | ||
var DeletedMessageHandler = (function (_super) { | ||
@@ -177,2 +220,11 @@ __extends(DeletedMessageHandler, _super); | ||
exports.DeletedMessageHandler = DeletedMessageHandler; | ||
/** | ||
* Обработчик комманд | ||
* | ||
* new CommandHandler("test", null, (bot, event) => {}) | ||
* | ||
* new CommandHandler(["test"], null, (bot, event) => {}) | ||
* | ||
* Пример комманд .test или /test | ||
*/ | ||
var CommandHandler = (function (_super) { | ||
@@ -185,3 +237,3 @@ __extends(CommandHandler, _super); | ||
var _this = _super.call(this, filters, callback) || this; | ||
_this.filters = (filters) ? filters : null; // Filter.command if filters is None else Filter.command & filters, | ||
_this.filters = (filters) ? filters : Filter_1.Filter.command; | ||
_this.callback = callback; | ||
@@ -195,3 +247,3 @@ _this.command = command; | ||
return true; | ||
var command_1 = event.data["text"].split(" ")[0].toLowerCase(); | ||
var command_1 = event.data.text.split(" ")[0].toLowerCase().replace(/^(.|\/)/, ''); | ||
if (Array.isArray(this.command)) | ||
@@ -201,2 +253,3 @@ return this.command.findIndex(function (c) { return c.toLowerCase() == command_1; }) >= 0; | ||
} | ||
return false; | ||
}; | ||
@@ -238,2 +291,5 @@ return CommandHandler; | ||
} | ||
FeedbackCommandHandler.prototype.check = function (event, dispatcher) { | ||
return (_super.prototype.check.call(this, event, dispatcher)); | ||
}; | ||
FeedbackCommandHandler.prototype.message_cb = function (bot, event) { | ||
@@ -240,0 +296,0 @@ return __awaiter(this, void 0, void 0, function () { |
@@ -57,3 +57,3 @@ { | ||
}, | ||
"version": "2.1.22" | ||
"version": "2.1.23" | ||
} |
@@ -166,26 +166,51 @@ # icq-bot | ||
Файл index.js | ||
Команды в терминале bash | ||
```bash | ||
# Создаём директорию | ||
mkdir testBot | ||
# Переходим в неё | ||
cd ./testBot | ||
# Создаём npm проект по умолчанию | ||
npm init --force | ||
# Устанавливаем зависимость icq-bot | ||
npm i icq-bot -s | ||
``` | ||
Далее создаём и вставляем в index.js код ниже со своим токеном. | ||
- Файл index.js | ||
```javascript | ||
// Импортируем бота | ||
const ICQ = require('icq-bot').default; | ||
// Создаём фасад пакета ICQ | ||
const bot = new ICQ.Bot(ВАШ_ТОКЕН_БОТА); | ||
let handlerNewMessage = new ICQ.Handler.Message(null, (bot, event) => { | ||
console.log(`New Message event.fromChatID = ${event.fromChatId}`); | ||
const chatId = event.data.chat.chatId; | ||
// Создаём обработчик для новых сообщений | ||
const handlerNewMessage = new ICQ.Handler.Message(null, (bot, event) => { | ||
// Получаем номер чата из объекта event | ||
const chatId = event.fromChatId; | ||
// Выводим в консоль тип события и номер чата | ||
console.log(`New Message event.fromChatID = ${chatId}`); | ||
// Отправляем сообщение в чат отправителя | ||
bot.sendText(chatId, "Привет!"); | ||
}); | ||
let handlerDeleteMessage = new ICQ.Handler.DeletedMessage(null, (bot, event) => { | ||
console.log(event); | ||
console.log(`Deleted Message event.fromChatID = ${event.fromChatId}`); | ||
const chatId = event.data.chat.chatId; | ||
// Создаём обработчик для удалённых сообщений | ||
const handlerDeleteMessage = new ICQ.Handler.DeletedMessage(null, (bot, event) => { | ||
// Получаем номер чата из объекта event | ||
const chatId = event.fromChatId; | ||
// Выводим в консоль тип события и номер чата | ||
console.log(`Deleted Message event.fromChatID = ${chatId}`); | ||
// Отправляем сообщение в чат отправителя | ||
bot.sendText(chatId, "Зачем!"); | ||
}); | ||
// Получаем диспетчер бота и добавляем в него обработчики | ||
bot.getDispatcher().addHandler(handlerNewMessage); | ||
bot.getDispatcher().addHandler(handlerDeleteMessage); | ||
// Запускаем пулинг для получения команд обработчикам | ||
bot.startPolling(); | ||
@@ -195,14 +220,6 @@ | ||
Команды в терминале bash | ||
Далее остаётся запустить нашего бота | ||
```bash | ||
mkdir testBot | ||
cd ./testBot | ||
npm init --force | ||
npm i icq-bot -s | ||
``` | ||
Создаём и вставляем в index.js код выше со своим токеном бота | ||
``` | ||
# Запускаем проект | ||
node index.js | ||
@@ -209,0 +226,0 @@ ``` |
@@ -38,4 +38,3 @@ import { EventType } from "../interfaces/Events/Event"; | ||
if (this.type == EventType.NEW_MESSAGE || this.type == EventType.EDITED_MESSAGE || this.type == EventType.PINNED_MESSAGE) { | ||
this.text = (this.data as NewMessageEvent).text | ||
// this.fromChatId = (this.data as NewMessageEvent).chat.chatId | ||
this.text = (this.data as NewMessageEvent).text | ||
this.messageAuthor = (this.data as NewMessageEvent).from | ||
@@ -42,0 +41,0 @@ } |
@@ -23,3 +23,3 @@ import { MessageHandler } from "../interfaces/Handler"; | ||
for (let i in this.cache) { | ||
console.log(i,(event.data as NewMessageEvent).msgId, this.cache[i], event.text) | ||
// console.log(i,(event.data as NewMessageEvent).msgId, this.cache[i], event.text) | ||
if (i && i == (event.data as NewMessageEvent).msgId && this.cache[i] == event.text) { | ||
@@ -26,0 +26,0 @@ // return false; |
@@ -5,6 +5,28 @@ import { Bot } from "./class/Bot"; | ||
import { ICQButton } from "./class/ICQButton"; | ||
/** | ||
* Фасад ICQ | ||
*/ | ||
export default class ICQ { | ||
/** | ||
* Класс кнопки для сообщений | ||
*/ | ||
static Button = ICQButton; | ||
/** | ||
* Бот для вызова | ||
*/ | ||
static Bot = Bot; | ||
static Filter = new Filter(); | ||
/** | ||
* Базовые фильтры для обработчиков | ||
*/ | ||
static Filter = Filter; | ||
/** | ||
* Базовые обработчики. | ||
* | ||
* Обратите внимание, что если под одно событие | ||
* подходят несколько обработчиков, то будут вызваны оба. | ||
*/ | ||
static Handler = { | ||
@@ -24,2 +46,2 @@ HelpCommand: ICQHelpCommandHandler, | ||
}; | ||
} | ||
} |
@@ -10,2 +10,3 @@ import { NewMessageEvent } from "./NewMessageEvent"; | ||
/** Типы сообщений */ | ||
export enum EventType { | ||
@@ -23,2 +24,3 @@ NEW_MESSAGE = "newMessage", | ||
export interface ResponseEvent { | ||
@@ -28,2 +30,6 @@ events: Event[]; | ||
/** | ||
* Каждое событие имеет идентификатор eventId и type | ||
* В зависимости от type параметра будет разная полезная нагрузка payload. | ||
*/ | ||
export interface Event { | ||
@@ -30,0 +36,0 @@ eventId: number; |
@@ -7,3 +7,3 @@ import { PartsType, PartFile, PayLoadFileType } from "./Entities/Part"; | ||
export interface Filter { | ||
export interface Filters { | ||
filter(event: ICQEvent): boolean; | ||
@@ -13,3 +13,3 @@ } | ||
/** Фильтр проверяет тип события и наличие текста в нём */ | ||
export class MessageFilter implements Filter { | ||
export class MessageFilter implements Filters { | ||
filter(event: ICQEvent): boolean { | ||
@@ -20,9 +20,12 @@ return event.data["text"] && event["text"].length > 0; | ||
/** Фильтр проверяет наличие первого символа на равенство "/" или "." */ | ||
export class CommandFilter extends MessageFilter { | ||
COMMAND_PREFIXES: String[] = ["/", "."]; | ||
filter(event: ICQEvent) { | ||
filter(event: ICQEvent) { | ||
return (super.filter(event) && this.COMMAND_PREFIXES.findIndex(r => r === (event.data as NewMessageEvent).text.trim()[0]) >= 0) | ||
} | ||
} | ||
/** Фильтр проверяет регулярным выражением текст сообщения и фильтрует по нему */ | ||
export class RegexpFilter extends MessageFilter { | ||
@@ -40,3 +43,5 @@ pattern: RegExp; | ||
/** | ||
* Фильтрует сообщения конкретного пользователя | ||
*/ | ||
export class SenderFilter extends MessageFilter { | ||
@@ -51,2 +56,5 @@ constructor(private user_id: number) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа файл | ||
*/ | ||
export class FileFilter extends MessageFilter { | ||
@@ -59,3 +67,5 @@ filter(event) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа изображение | ||
*/ | ||
export class ImageFilter extends FileFilter { | ||
@@ -68,2 +78,5 @@ filter(event: ICQEvent) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа видел | ||
*/ | ||
export class VideoFilter extends FileFilter { | ||
@@ -76,2 +89,5 @@ filter(event: ICQEvent) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа Аудио | ||
*/ | ||
export class AudioFilter extends FileFilter { | ||
@@ -84,4 +100,7 @@ filter(event: ICQEvent) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типа Стикер | ||
*/ | ||
export class StickerFilter extends MessageFilter { | ||
filter(event: ICQEvent) { | ||
filter(event: ICQEvent) { | ||
return super.filter(event) && event.data['parts'] && | ||
@@ -92,2 +111,5 @@ event.data['parts'].findIndex(r => r && r.type == PartsType.STICKER) >= 0 | ||
/** | ||
* Фильтрует события где был упомянут пользователь | ||
*/ | ||
export class MentionFilter extends MessageFilter { | ||
@@ -103,3 +125,5 @@ constructor(public userId: Number) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типо FORWARD - Перенаправленное (Пересылаемое сообщение) | ||
*/ | ||
export class ForwardFilter extends MessageFilter { | ||
@@ -111,2 +135,5 @@ filter(event: ICQEvent) { | ||
/** | ||
* Фильтрует события и оставляет только сообщения с полезной нагрузкой типо Reply - Цитата сообщения | ||
*/ | ||
export class ReplyFilter extends MessageFilter { | ||
@@ -119,3 +146,5 @@ filter(event: ICQEvent) { | ||
/** | ||
* Фильтрует сообщения состоящии из одной URL ссылки. Допускаются пробелы в начале и конце сообщения. | ||
*/ | ||
export class URLFilter extends RegexpFilter { | ||
@@ -132,2 +161,3 @@ | ||
/** Типы операций над фильтрами */ | ||
export enum TypeFilterOperation { | ||
@@ -138,13 +168,15 @@ and = 1, | ||
} | ||
export class FilterComposite implements Filter { | ||
constructor(private type: TypeFilterOperation, private leftFilter: Filter, private rightFilter?: Filter) { | ||
/** Создаёт композитный фильтр из двух, применяя к ним оператор сравнения. Рекомендую использовать статические методы and, or, not */ | ||
export class FilterComposite implements Filters { | ||
constructor(private type: TypeFilterOperation, private leftFilter: Filters, private rightFilter?: Filters) { | ||
} | ||
static and(leftFilter: Filter, rightFilter: Filter) { | ||
static and(leftFilter: Filters, rightFilter: Filters) { | ||
return new FilterComposite(TypeFilterOperation.and, leftFilter, rightFilter); | ||
} | ||
static or(leftFilter: Filter, rightFilter: Filter) { | ||
static or(leftFilter: Filters, rightFilter: Filters) { | ||
return new FilterComposite(TypeFilterOperation.or, leftFilter, rightFilter); | ||
} | ||
static not(filter: Filter) { | ||
static not(filter: Filters) { | ||
return new FilterComposite(TypeFilterOperation.not, filter); | ||
@@ -168,18 +200,98 @@ | ||
export class Filter { | ||
/** | ||
* Фильтр проверяет тип события | ||
* и наличие текста в нём | ||
*/ | ||
static message = new MessageFilter() | ||
/** | ||
* Фильтр проверяет наличие первого | ||
* символа на равенство "/" или "." | ||
*/ | ||
static command = new CommandFilter() | ||
/** Фильтрует сообщения конкретного пользователя */ | ||
static file = new FileFilter() | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа изображение | ||
*/ | ||
static image = new ImageFilter() | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Видео | ||
*/ | ||
static video = new VideoFilter() | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Аудио | ||
*/ | ||
static audio = new AudioFilter() | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типа Аудио, Видео, Изображение | ||
*/ | ||
static media = FilterComposite.or(FilterComposite.or(Filter.image, Filter.video), Filter.audio); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Аудио, | ||
* Видео, Изображение, Файл | ||
*/ | ||
static data = FilterComposite.and(Filter.file, FilterComposite.not(Filter.media)); | ||
/** | ||
* Фильтрует события и оставляет только | ||
* сообщения с полезной нагрузкой типа Стикер | ||
*/ | ||
static sticker = new StickerFilter() | ||
/** | ||
* Фильтрует сообщения состоящии из одной URL ссылки. | ||
* Допускаются пробелы в начале и конце сообщения. | ||
*/ | ||
static url = new URLFilter() | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типа Аудио, Видео, | ||
* Изображение, Файл, Стикер, Ссылка | ||
* | ||
* Все сообщения у которых может быть текст. | ||
*/ | ||
static text = FilterComposite.and(Filter.message, FilterComposite.not(FilterComposite.or(FilterComposite.or(FilterComposite.or(Filter.command, Filter.sticker), Filter.file), Filter.url))); | ||
/** | ||
* Фильтр проверяет регулярным выражением | ||
* текст сообщения и фильтрует по нему | ||
*/ | ||
static regexp = RegexpFilter | ||
/** | ||
* Фильтрует события где был упомянут пользователь | ||
*/ | ||
static mention = MentionFilter | ||
/** | ||
* Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типо FORWARD - | ||
* Перенаправленное (Пересылаемое сообщение) */ | ||
static forward = new ForwardFilter() | ||
/** Фильтрует события и оставляет только сообщения | ||
* с полезной нагрузкой типо Reply - Цитата сообщения */ | ||
static reply = new ReplyFilter() | ||
/** | ||
* Фильтрует сообщения отпраленные конкретным пользователем | ||
*/ | ||
static sender = SenderFilter | ||
} |
@@ -1,2 +0,2 @@ | ||
import { Filter } from "./Filter"; | ||
import { Filters, Filter } from "./Filter"; | ||
import { Dispatcher } from "./Dispatcher"; | ||
@@ -17,7 +17,22 @@ import { EventType } from "./Events/Event"; | ||
/** | ||
* Базовый обработчик. | ||
* | ||
* Срабатывает на все события если не установлен фильтр | ||
* или на события отфильтрованные установленным фильтром | ||
*/ | ||
export class HandlerBase implements Handler { | ||
constructor(protected filters: Filter, protected callback: (bot: ICQBot, event: ICQEvent) => void) { } | ||
/** | ||
* Параметр filters может быть равен null. | ||
* В таком случае вызов callback будет происходить | ||
* каждый раз, когда приходит событие | ||
* | ||
* @param filters Фильтр | ||
* @param callback Функция обратного вызова | ||
*/ | ||
constructor(protected filters: Filters, protected callback: (bot: ICQBot, event: ICQEvent) => void) { } | ||
check(event: ICQEvent, dispatcher: Dispatcher) { | ||
return (!this.filters || this.filters.filter(event)); | ||
return (!this.filters || this.filters.filter(event)); | ||
} | ||
@@ -31,2 +46,7 @@ handle(event: ICQEvent, dispatcher: Dispatcher) { | ||
/** | ||
* Обработчик для всех событий | ||
* | ||
* Срабатывает всегда, когда приходит событие из пуллинга | ||
*/ | ||
export class DefaultHandler extends HandlerBase { | ||
@@ -53,2 +73,8 @@ constructor(callback = null) { | ||
} | ||
/** | ||
* Обработчик новых участников группового чата | ||
* | ||
* Срабатывает когда в группу вступает новый пользователь | ||
*/ | ||
export class NewChatMembersHandler extends HandlerBase { | ||
@@ -59,2 +85,6 @@ public check(event, dispatcher) { | ||
} | ||
/** | ||
* Обработчик выхода из группы участника | ||
*/ | ||
export class LeftChatMembersHandler extends HandlerBase { | ||
@@ -66,2 +96,5 @@ public check(event, dispatcher) { | ||
/** | ||
* Обработчик закрепа сообщения в чате | ||
*/ | ||
export class PinnedMessageHandler extends HandlerBase { | ||
@@ -73,2 +106,5 @@ public check(event, dispatcher) { | ||
/** | ||
* Обработчик открепления сообщения в чате | ||
*/ | ||
export class UnPinnedMessageHandler extends HandlerBase { | ||
@@ -80,10 +116,14 @@ public check(event, dispatcher) { | ||
/** | ||
* Обработчик текстовых сообщений | ||
*/ | ||
export class MessageHandler extends HandlerBase { | ||
public check(event, dispatcher) { | ||
return (super.check(event, dispatcher) && event.type == EventType.NEW_MESSAGE) | ||
return (super.check(event, dispatcher) && event.type == EventType.NEW_MESSAGE) | ||
} | ||
} | ||
/** | ||
* Обработчик событий редактирования сообщений | ||
*/ | ||
export class EditedMessageHandler extends HandlerBase { | ||
@@ -98,2 +138,5 @@ public check(event, dispatcher) { | ||
/** | ||
* Обработчик событий удаления сообщений | ||
*/ | ||
export class DeletedMessageHandler extends HandlerBase { | ||
@@ -106,2 +149,11 @@ public check(event, dispatcher) { | ||
/** | ||
* Обработчик комманд | ||
* | ||
* new CommandHandler("test", null, (bot, event) => {}) | ||
* | ||
* new CommandHandler(["test"], null, (bot, event) => {}) | ||
* | ||
* Пример комманд .test или /test | ||
*/ | ||
export class CommandHandler extends MessageHandler { | ||
@@ -111,3 +163,3 @@ protected command; | ||
super(filters, callback); | ||
this.filters = (filters) ? filters : null; // Filter.command if filters is None else Filter.command & filters, | ||
this.filters = (filters) ? filters : Filter.command; | ||
this.callback = callback | ||
@@ -119,6 +171,7 @@ this.command = command | ||
if (!this.command) return true; | ||
let command = event.data["text"].split(" ")[0].toLowerCase() | ||
let command = event.data.text.split(" ")[0].toLowerCase().replace(/^(.|\/)/,'') | ||
if (Array.isArray(this.command)) return this.command.findIndex(c => c.toLowerCase() == command) >= 0 | ||
return this.command == command; | ||
} | ||
return false; | ||
} | ||
@@ -146,2 +199,3 @@ } | ||
private error_reply; | ||
constructor(target: string, message = "Feedback from {source}: {message}", reply = "Got it!", error_reply = null, | ||
@@ -157,4 +211,9 @@ command = "feedback", filters = null | ||
} | ||
public async message_cb(bot: Bot, event: ICQEvent) { | ||
public check(event, dispatcher) { | ||
return (super.check(event, dispatcher)) | ||
} | ||
private async message_cb(bot: Bot, event: ICQEvent) { | ||
let source = event.data['chat']['chatId']; | ||
@@ -171,3 +230,3 @@ let chunks = event.data["text"].split(" "); | ||
if (!result.ok) console.log("Не удалось отправить запрос sendText"); | ||
} | ||
} | ||
} else if (this.error_reply != "") { | ||
@@ -185,3 +244,4 @@ let result = await bot.sendText(source, this.error_reply) | ||
public check(event, dispatcher) { | ||
return super.check(event, dispatcher) && | ||
return super.check(event, dispatcher) && | ||
dispatcher.handlers.findIndex(h => h != this && h.check(event, dispatcher)) == -1 | ||
@@ -188,0 +248,0 @@ } |
@@ -20,9 +20,6 @@ | ||
params: params, | ||
then: (clback) => { | ||
return { | ||
url: url, | ||
header: header, | ||
params: params, | ||
clbk: clback | ||
}; | ||
clbk: null, | ||
then: function(clback) { | ||
this.clbk = clback; | ||
return this; | ||
} | ||
@@ -37,6 +34,7 @@ } | ||
header: header, | ||
then: (clback) => { | ||
clbk: null, | ||
then: function(clback) { | ||
this['clbk'] = clback | ||
return this; | ||
} | ||
@@ -106,9 +104,10 @@ } | ||
it(".url == https://api.icq.net/bot/v1/events/get", () => { | ||
assert(bot.eventsGet(10, 0).url == "https://api.icq.net/bot/v1/events/get"); | ||
assert( bot.eventsGet(10, 0).url === "https://api.icq.net/bot/v1/events/get" ) | ||
}) | ||
it(".header['user-agent'] == 'NodeBot/0.0.1 (uin=XX) bot-nodejs/2.0.0-beta'", () => { | ||
assert(bot.eventsGet(10, 0).header['user-agent'] == 'NodeBot/0.0.1 (uin=XX) bot-nodejs/2.0.0-beta'); | ||
assert( bot.eventsGet(10, 0).header['user-agent'] === "NodeBot/0.0.1 (uin=XX) bot-nodejs/2.0.0-beta" ) | ||
}) | ||
it(".params == .token", () => { | ||
assert(bot.eventsGet(10, 0).params.token == "X:XX"); | ||
it(".params == .token", () => { | ||
assert( bot.eventsGet(10, 0).params.token === "X:XX" ) | ||
}) | ||
@@ -115,0 +114,0 @@ }); |
@@ -18,3 +18,3 @@ | ||
"timestamp": 1546290000, | ||
"text": "feedback text more", | ||
"text": ".feedback text more", | ||
"parts": [ | ||
@@ -131,3 +131,3 @@ null | ||
"timestamp": 1546290000, | ||
"text": "sTart text more", | ||
"text": ".sTart text more", | ||
"parts": [ | ||
@@ -237,3 +237,3 @@ null | ||
"timestamp": 1546290000, | ||
"text": "help full text", | ||
"text": "/help full text", | ||
"parts": [ | ||
@@ -269,2 +269,26 @@ null | ||
const eventUnknow= { | ||
"eventId": 1, | ||
"type": "newMessage", | ||
"payload": { | ||
"msgId": "57883346846815032", | ||
"chat": { | ||
"chatId": "681869378@chat.agent", | ||
"type": "channel", | ||
"title": "The best channel" | ||
}, | ||
"from": { | ||
"userId": "1234567890", | ||
"firstName": "Name", | ||
"lastName": "SurName" | ||
}, | ||
"timestamp": 1546290000, | ||
"text": ".madCommand", | ||
"parts": [ | ||
null | ||
] | ||
} | ||
}; | ||
const eventEditMessage = { | ||
@@ -432,2 +456,3 @@ "eventId": 2, | ||
exports.eventMessage = eventMessage; | ||
exports.eventUnknow = eventUnknow; | ||
exports.eventEditMessage = eventEditMessage; | ||
@@ -434,0 +459,0 @@ exports.eventDeleteMessage = eventDeleteMessage; |
@@ -544,5 +544,5 @@ /** | ||
it("feedbackCommandMessage event text should by: Not good!", (done) => { | ||
let eventICQ = new ICQEvent(event.feedbackCommandMessage); | ||
eventICQ.data.text = "feedback "; | ||
it("UnknownCommandHandler event text should by: Not good!", (done) => { | ||
let eventICQ = new ICQEvent(event.eventUnknow); | ||
message.handle(eventICQ, | ||
@@ -590,34 +590,34 @@ { | ||
describe("UnknownCommandHandler.check(event)", () => { | ||
let message = new Handlers.UnknownCommandHandler(null, () => { }); | ||
let dispatcherProxy = { handlers: [message] , getBot : () => {return this}} | ||
it("feedbackCommandMessage event should by true", () => { | ||
assert(message.check(new ICQEvent(event.feedbackCommandMessage), dispatcherProxy)) | ||
let handler = new Handlers.UnknownCommandHandler(null, () => { }); | ||
let dispatcherProxy = { handlers: [handler] , getBot : () => {return this}} | ||
it("feedbackCommandMessage event should by true", () => { | ||
assert(handler.check(new ICQEvent(event.feedbackCommandMessage), dispatcherProxy)) | ||
}) | ||
it("helpCommandMessage event should by true", () => { | ||
assert(message.check(new ICQEvent(event.helpCommandMessage), dispatcherProxy)) | ||
assert(handler.check(new ICQEvent(event.helpCommandMessage), dispatcherProxy)) | ||
}) | ||
it("NewMessage event should by true", () => { | ||
assert(message.check(new ICQEvent(event.eventMessage), dispatcherProxy)) | ||
it("Unknow message event should by true", () => { | ||
assert(handler.check(new ICQEvent(event.eventUnknow), dispatcherProxy)) | ||
}) | ||
it("EditMessage event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventEditMessage), dispatcherProxy)) | ||
assert(!handler.check(new ICQEvent(event.eventEditMessage), dispatcherProxy)) | ||
}) | ||
it("DeleteMessage event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventDeleteMessage), dispatcherProxy)) | ||
assert(!handler.check(new ICQEvent(event.eventDeleteMessage), dispatcherProxy)) | ||
}) | ||
it("PinedMessage event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventPinnedMessage), dispatcherProxy)) | ||
assert(!handler.check(new ICQEvent(event.eventPinnedMessage), dispatcherProxy)) | ||
}) | ||
it("UnpinnedMessage event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventUnpunnedMessage), dispatcherProxy)) | ||
assert(!handler.check(new ICQEvent(event.eventUnpunnedMessage), dispatcherProxy)) | ||
}) | ||
it("NewChatMembers event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventNewChatMembers), dispatcherProxy)) | ||
assert(!handler.check(new ICQEvent(event.eventNewChatMembers), dispatcherProxy)) | ||
}) | ||
it("LeftChatMembers event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventLeftChatMembers), dispatcherProxy)) | ||
assert(!handler.check(new ICQEvent(event.eventLeftChatMembers), dispatcherProxy)) | ||
}) | ||
@@ -628,3 +628,3 @@ | ||
try { | ||
message.handle(new ICQEvent(event.helpCommandMessage), dispatcherProxy); | ||
handler.handle(new ICQEvent(event.helpCommandMessage), dispatcherProxy); | ||
} catch(ex) { | ||
@@ -648,4 +648,4 @@ assert(ex.message == "UnknownCommandHandler"); | ||
}) | ||
it("NewMessage event should by true", () => { | ||
assert(message.check(new ICQEvent(event.eventMessage), dispatcherProxy)) | ||
it("NewMessage event should by false", () => { | ||
assert(!message.check(new ICQEvent(event.eventMessage), dispatcherProxy)) | ||
}) | ||
@@ -652,0 +652,0 @@ it("EditMessage event should by false", () => { |
@@ -44,4 +44,3 @@ let ICQ = require("../dist/index").default; | ||
bot.sendFile(chatId, null, filePath).then(r => { | ||
if (r.ok) done(); | ||
console.log("sendFile", r) | ||
if (r.ok) done(); | ||
bot.deleteMessages(chatId, r.msgId).then(r => { }); | ||
@@ -48,0 +47,0 @@ }); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
325552
6256
231