- Create context of app
enum Menus {
Main = 'main',
Settings = 'settings',
}
interface User {
name: string;
selectedMenu: Menus;
}
export interface BotContext {
user: User;
}
- Create actions you will use
const gotoMenuAction = createParametarizedAction<BotContext, Menus>(
'goto menu',
async (menu, {send}, {user}) => {
user.selectedMenu = menu;
await send(`Welcome to ${menu}`);
}
);
const setRandomUsername = createAction<BotContext>(
'set random username',
async ({send}, {user}) => {
const getRandomInt = (max: number) => Math.floor(Math.random() * max);
const randomName = ['Fish', 'Sticks', 'Kanye West', 'Toivo', 'SunBoy'];
user.name = randomName[getRandomInt(4)];
await send(`Your name is ${user.name}`);
}
);
- Create menu constructors
const SettingsMenu: R1IO.FC<BotContext> = async () => (
<menu>
<row>
<button label={`Get random username`} onClick={setRandomUsername()} />
</row>
<row>
<button onClick={gotoMenuAction(Menus.Settings)}>Goto main menu</button>
</row>
</menu>
);
const MainMenu: R1IO.FC<BotContext> = ({user}) => (
<menu>
<row>
<button label={`Hello ${user.name}`} />
</row>
<row>
<button onClick={gotoMenuAction(Menus.Settings)}>
Goto settings menu
</button>
</row>
</menu>
);
- Create router & your context filler (middleware)
const user: User = {
name: 'Dmitriy',
selectedMenu: Menus.Main,
};
const router = createRouter<BotContext, Menus>(
{
[Menus.Main]: {build: MainMenu},
[Menus.Settings]: {build: SettingsMenu},
},
({user}) => user.selectedMenu
);
export const RootMiddleware = createMiddleware(router, async () => ({user}));
- Add package to your project
yarn add r1-io
or
npm i r1-io
- Add vk-io to your project (only 4.4.0 tested)
yarn add [email protected]
or
npm i [email protected]
- Add this lines to your
tsconfig.json
{
"compilerOptions": {
"jsx": "react",
"jsxFactory": "R1IO.createElement",
"jsxFragmentFactory": "R1IO.Fragment"
}
}
- React components instead of keyboard builder
const MainMenu: R1IO.FC<BotContext> = ({user}) => (
<menu>
<row>
<button label={`Hello ${user.name}`} />
</row>
<row>
<button onClick={gotoMenuAction(Menus.Settings)}>
Goto settings menu
</button>
</row>
</menu>
);
- Async react components
const MainMenu: R1IO.FC<BotContext> = async ({user}) => {
await delay(2000);
<menu>
<row>
<button label={`Hello ${user.name}`} />
</row>
</menu>;
};
- User based actions