コンテンツにスキップ

CommunityFilter

CommunityFilter は、指定したコミュニティ ID に関連するイベントのみを内部のハンドラに渡す EventHandler ミドルウェアです。複数のコミュニティにインストールされた Plugin で、特定のコミュニティだけを処理したい場合に便利です。

追加インストールは不要です。mixi2-js に同梱されています。

// ESM
import { CommunityFilter } from 'mixi2-js/helpers';
// CJS
const { CommunityFilter } = require('mixi2-js/helpers');
  • コミュニティ ID を持つイベント(PostCreatedEventcommunityIdCommunityMemberChangedEventCommunityPluginManagedEvent)は、指定した ID と一致した場合のみ内部ハンドラに渡されます
  • PING など、コミュニティと無関係なイベントはそのまま通過します
import { EventType, StreamWatcher } from 'mixi2-js';
import { EventRouter, CommunityFilter } from 'mixi2-js/helpers';
const router = new EventRouter();
router.on(EventType.POST_CREATED, async (event) => {
// community-id-1 のポストのみここに到達する
console.log("コミュニティのポスト:", event.postCreatedEvent?.post?.text);
});
// 特定のコミュニティのみ処理する
const filter = new CommunityFilter(router, ['community-id-1']);
const watcher = new StreamWatcher({ client, handler: filter });
await watcher.watch();
// 複数のコミュニティ ID を指定できる
const filter = new CommunityFilter(router, [
'community-id-1',
'community-id-2',
]);
import { EventRouter, CommunityFilter, EventDeduplicator } from 'mixi2-js/helpers';
const router = new EventRouter();
const filter = new CommunityFilter(router, ['community-id-1']);
const dedup = new EventDeduplicator(filter);
// Webhook でも重複排除 + コミュニティフィルタが機能する
const server = new WebhookServer({ handler: dedup, secret: '...' });
new CommunityFilter(handler: EventHandler, communityIds: string[])
引数説明
handlerEventHandlerフィルタ通過後にイベントを渡すハンドラ
communityIdsstring[]通過を許可するコミュニティ ID の一覧
メソッド説明
handle(event)EventHandler インターフェースの実装。フィルタリングを行う