grammyjs / conversations

Conversational interfaces for grammY.
https://grammy.dev/plugins/conversations
MIT License
52 stars 17 forks source link

`otherwise` executed immeditely #115

Closed matmilbury closed 2 months ago

matmilbury commented 2 months ago

I want to exit the conversation if a user does something else other than answering my inline keyboard.

This works as expected

try {
  await conversation.waitForCallbackQuery(
    ['yes', 'no'],
    () => { throw new Error('exit') }
  )
} catch {
  return
}

but this does not because otherwise function is executed as soon as the conversation is entered, exiting immediately:


try {
  await conversation.waitForCallbackQuery(
    ['yes', 'no'],
    { otherwise: () => { throw new Error('exit') }}
  )
} catch {
  return
}
KnorpelSenf commented 2 months ago

Can you show more code? I cannot reproduce this using the following code.

import {
  Bot,
  Context,
  InlineKeyboard,
  session,
} from "https://deno.land/x/grammy@v1.29.0/mod.ts";
import {
  type Conversation,
  type ConversationFlavor,
  conversations,
  createConversation,
} from "https://deno.land/x/grammy_conversations@v1.2.0/mod.ts";

type MyContext = Context & ConversationFlavor;
type MyConversation = Conversation<MyContext>;

const bot = new Bot<MyContext>("");

bot.use(session({ initial: () => ({}) }));
bot.use(conversations());

/** Defines the conversation */
async function greeting(conversation: MyConversation, ctx: MyContext) {
  conversation.log("enter");
  await ctx.reply("test", {
    reply_markup: new InlineKeyboard().text("yes").text("no"),
  });
  try {
    await conversation.waitForCallbackQuery(
      ["yes", "no"],
      {
        otherwise: () => {
          console.log("otherwise");
          throw new Error("exit");
        },
      },
    );
  } catch {
    conversation.log("leaving");
    return;
  }
  conversation.log("returning");
}

bot.use(createConversation(greeting));

bot.command("start", async (ctx) => {
  // enter the function "greeting" you declared
  await ctx.conversation.enter("greeting");
});

bot.start();
matmilbury commented 2 months ago

my code since changed and I can't reproduce anymore either. Sorry :grimacing: