Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions tbh/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tbh/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"homepage": "https://github.com/atundra/bots#readme",
"dependencies": {
"express": "^4.17.1",
"fp-ts": "^2.7.0",
"fp-ts": "^2.9.0",
"telegraf": "^3.38.0"
},
"devDependencies": {
Expand Down
83 changes: 25 additions & 58 deletions tbh/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1,38 @@
import { pipe } from 'fp-ts/lib/function';
import * as TE from 'fp-ts/lib/TaskEither';
import * as T from 'fp-ts/lib/Task';
import * as RTE from 'fp-ts/lib/ReaderTaskEither';
import * as RT from 'fp-ts/lib/ReaderTask';
import * as RTE from 'fp-ts/lib/ReaderTaskEither';
import * as Console from 'fp-ts/lib/Console';
import * as O from 'fp-ts/lib/Option';
import Telegraf, { Middleware } from 'telegraf';

import { getConfig } from './utils/config';
import { startTunnel } from './utils/dev';
import { setWebhook, startWebhook, reply } from './telegram';
import { TelegrafContext } from 'telegraf/typings/context';

const getMiddleware = (
a: RT.ReaderTask<TelegrafContext, unknown>
): Middleware<TelegrafContext> => ctx => RT.run(a, ctx);
import Telegraf, { Telegram } from 'telegraf';

const echoHandler = getMiddleware(
pipe(
RTE.ask<TelegrafContext>(),
RTE.chain(ctx =>
pipe(
O.fromNullable(ctx.message),
O.chain(message => O.fromNullable(message.text)),
RTE.fromOption(() => new Error('Message text not found')),
RTE.chain(text => RTE.fromTaskEither(reply(ctx, text)))
)
)
)
);
import { getPopulatedConfig } from './utils/config';
import { setWebhook, startWebhook, getMe } from './telegram';
import { newChatMembersHandler } from './telegram/handlers';
import { getMiddleware } from './telegram';

const app = pipe(
getConfig(process.env),
TE.fromEither,
TE.chain(config =>
pipe(
O.fromNullable(config.DEV),
O.fold(
() => TE.of(config),
() =>
pipe(
startTunnel(Number(config.PORT)),
TE.map(tunnel => ({
...config,
HOSTNAME: tunnel.url
})),
TE.chainFirst(config =>
TE.fromIO<unknown, void>(Console.log(`Localtunnel url is ${config.HOSTNAME}`))
)
)
)
)
),
TE.chain(config => {
const telegraf = new Telegraf(config.BOT_TOKEN);
getPopulatedConfig,
RTE.chainW(config => {
return pipe(
getMe(new Telegram(config.BOT_TOKEN)),
RTE.fromTaskEither,
RTE.chain(user => {
const telegraf = new Telegraf(config.BOT_TOKEN, {
username: user.username
});

telegraf.on('text', echoHandler);
telegraf.on('new_chat_members', getMiddleware(newChatMembersHandler));

return pipe(
TE.fromIO(startWebhook(telegraf, `/${config.BOT_TOKEN}`, Number(config.PORT))),
TE.map(() => ({ telegraf, config }))
return pipe(
RTE.fromIO(startWebhook(telegraf, `/${config.BOT_TOKEN}`, Number(config.PORT))),
RTE.map(() => ({ telegraf, config }))
);
})
);
}),
TE.chain(({ telegraf, config }) =>
setWebhook(telegraf.telegram, `${config.HOSTNAME}/${config.BOT_TOKEN}`)
RTE.chainW(({ telegraf, config }) =>
RTE.fromTaskEither(setWebhook(telegraf.telegram, `${config.HOSTNAME}/${config.BOT_TOKEN}`))
),
TE.fold(T.fromIOK(Console.error), () => T.of(undefined))
RTE.fold(RT.fromIOK(Console.error), () => RT.of(undefined))
);

app();
app(process.env)();
1 change: 1 addition & 0 deletions tbh/src/telegram/handlers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './newChatMembers';
18 changes: 18 additions & 0 deletions tbh/src/telegram/handlers/newChatMembers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as RTE from 'fp-ts/lib/ReaderTaskEither';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import * as RTE from 'fp-ts/lib/ReaderTaskEither';
import { pipe } from 'fp-ts/lib/function';
import * as O from 'fp-ts/lib/Option';
import * as E from 'fp-ts/lib/Either';
import { TelegrafContext } from 'telegraf/typings/context';
import { User } from 'telegraf/typings/telegram-types';

export const newChatMembersHandler = (): RTE.ReaderTaskEither<TelegrafContext, Error, User[]> =>
  pipe(
    RTE.ask<TelegrafContext>(),
    RTE.chainEitherK(ctx =>
      pipe(
        ctx.message,
        O.fromNullable,
        O.mapNullable(m => m.new_chat_members),
        E.fromOption(() => new Error('asdf'))
      )
    ),
    RTE.chain(users => RTE.of(users))
  );

import { pipe } from 'fp-ts/lib/function';
import * as O from 'fp-ts/lib/Option';
import * as E from 'fp-ts/lib/Either';
import { TelegrafContext } from 'telegraf/typings/context';

export const newChatMembersHandler = pipe(
RTE.ask<TelegrafContext>(),
RTE.chainEitherK(ctx =>
pipe(
ctx.message,
O.fromNullable,
O.chainNullableK(m => m.new_chat_members),
E.fromOption(() => new Error('Chat members not found'))
)
),
RTE.chain(users => RTE.of(users))
);
30 changes: 24 additions & 6 deletions tbh/src/telegram/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import Telegraf, { Telegram } from 'telegraf';
import { ExtraReplyMessage } from 'telegraf/typings/telegram-types';
import Telegraf, { Telegram, Middleware } from 'telegraf';
import { ExtraReplyMessage, User } from 'telegraf/typings/telegram-types';
import * as TE from 'fp-ts/lib/TaskEither';
import * as IO from 'fp-ts/lib/IO';
import { identity } from 'fp-ts/lib/function';
import * as RT from 'fp-ts/lib/ReaderTask';
import { TelegrafContext } from 'telegraf/typings/context';

export const setWebhook = (telegram: Telegram, url: string): TE.TaskEither<unknown, boolean> =>
TE.tryCatch(() => telegram.setWebhook(url), identity);
export class TelegramError extends Error {}

export const setWebhook = (
telegram: Telegram,
url: string
): TE.TaskEither<TelegramError, boolean> =>
TE.tryCatch(
() => telegram.setWebhook(url),
e => new TelegramError(String(e))
);

export const getMe = (telegram: Telegram): TE.TaskEither<TelegramError, User> =>
TE.tryCatch(
() => telegram.getMe(),
e => new TelegramError(String(e))
);

export const startWebhook = (
telegraf: Telegraf<TelegrafContext>,
Expand All @@ -16,5 +30,9 @@ export const startWebhook = (

export const reply = TE.tryCatchK(
(ctx: TelegrafContext, text: string, extra?: ExtraReplyMessage) => ctx.reply(text, extra),
identity
e => new TelegramError(String(e))
);

export const getMiddleware = (
a: RT.ReaderTask<TelegrafContext, unknown>
): Middleware<TelegrafContext> => ctx => RT.run(a, ctx);
31 changes: 31 additions & 0 deletions tbh/src/utils/config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import * as E from 'fp-ts/lib/Either';
import * as RR from 'fp-ts/lib/ReadonlyRecord';
import * as RE from 'fp-ts/lib/ReaderEither';
import * as RTE from 'fp-ts/lib/ReaderTaskEither';
import * as O from 'fp-ts/lib/Option';
import { pipe, flow } from 'fp-ts/lib/function';
import { sequenceS } from 'fp-ts/lib/Apply';
import * as Console from 'fp-ts/lib/Console';

import { startTunnel, TunnelError } from '../utils/dev';

const isString = (a: unknown): a is string => typeof a === 'string';

Expand Down Expand Up @@ -36,3 +40,30 @@ export const getConfig = pipe(
},
sequenceS(RE.readerEither)
);

type Config = typeof getConfig extends RE.ReaderEither<any, any, infer A> ? A : never;

export const getPopulatedConfig = pipe(
getConfig,
RTE.fromReaderEither,
RTE.chainW(config =>
pipe(
O.fromNullable(config.DEV),
O.fold(
() => RTE.of<NodeJS.ProcessEnv, TunnelError, Config>(config),
() =>
pipe(
startTunnel(Number(config.PORT)),
RTE.fromTaskEither,
RTE.map(tunnel => ({
...config,
HOSTNAME: tunnel.url
})),
RTE.chainFirst(config =>
RTE.fromIO(Console.log(`Localtunnel url is ${config.HOSTNAME}`))
)
)
)
)
)
);
10 changes: 7 additions & 3 deletions tbh/src/utils/dev.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import * as TE from 'fp-ts/lib/TaskEither';
import localtunnel from 'localtunnel';
import { identity } from 'fp-ts/lib/function';

export const startTunnel = (port: number): TE.TaskEither<unknown, localtunnel.Tunnel> =>
TE.tryCatch(() => localtunnel({ port }), identity);
export class TunnelError extends Error {}

export const startTunnel = (port: number): TE.TaskEither<TunnelError, localtunnel.Tunnel> =>
TE.tryCatch(
() => localtunnel({ port }),
e => new TunnelError(String(e))
);