LoginSignup
0
0

Bot Framework(Node.js)でstate管理をAzure Blobに設定する

Last updated at Posted at 2024-05-16

目的

Bot Framework(Node.js)でstate管理する方法を記載します。(公式ドキュメントがメモリ管理の開発環境が前提になった記事ばかりで本番環境のstate管理の仕方が分からなかった・・)

基本的なボットを作成する - Bot Service | Microsoft Learn

動作確認をしたのは上記の yo コマンド(と yo-teams コマンドなど)で作成したBot Framework V4環境です。

すること

ライブラリのインストール

$ npm install botbuilder-azure-blobs

botbuilder-azure-blobs をインストールします。

ソース改修

stateをメモリ管理する開発環境で使用する botbuilderMemoryStorage に利用可能なメソッドが3つ( read , write , delete )提供されていますが、botbuilder-azure-blobsBlobsStorage でも同じ名称のメソッド3つが利用できるようになっていることが分かります。

なので、ソースコードの MemoryStorage() をストレージを利用する BlobsStorage に置き換えてあげれば良さそうです。
BotDeclaration デコレータの部分に storage を使ってあげるだけで state 管理がメモリではなくストレージ上で行われるようになりました。

XXXbot.ts
let storage = new BlobsStorage(
    process.env.STORAGE_CONNECTION_STRING as string, // 接続文字列
    'state管理したいコンテナ名'
)

/**
 * Implementation for XXX Bot
 */
  @BotDeclaration(
      '/api/messages',
      storage, // ここをMemoryStorage()から置き換えた
      // eslint-disable-next-line no-undef
      process.env.MICROSOFT_APP_ID,
      // eslint-disable-next-line no-undef
      process.env.MICROSOFT_APP_PASSWORD)

export class XXXBot extends DialogBot {
    constructor(conversationState: ConversationState, userState: UserState) {
        super(conversationState, userState, new MainDialog());

        this.onMembersAdded(async (context, next) => {
            const membersAdded = context.activity.membersAdded;
            if (membersAdded && membersAdded.length > 0) {
                for (let cnt = 0; cnt < membersAdded.length; cnt++) {
                    if (membersAdded[cnt].id !== context.activity.recipient.id) {
                        await this.sendWelcomeCard( context );
                    }
                }
            }
            await next();
        });
    }

    public async sendWelcomeCard( context: TurnContext ): Promise<void> {
        const welcomeCard = CardFactory.adaptiveCard(adaptiveCards.WelcomeCard);
        await context.sendActivity({ attachments: [welcomeCard] });
    }

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0