From 009dd0199715d7ebb45eeaeab1a9a00875707281 Mon Sep 17 00:00:00 2001 From: Ratmir Aitov Date: Mon, 29 Apr 2024 02:15:24 +0300 Subject: [PATCH] feat: add support random photos (#4) --- src/helpers/createKeyboard.ts | 1 + src/helpers/getPastvuRandomPhotos.ts | 24 ++++++++++++++++++++++++ src/helpers/sendPhotos.ts | 4 ++-- src/i18n/locales/en.json | 4 +++- src/i18n/locales/ru.json | 4 +++- src/index.ts | 8 ++++++++ src/scenes/pastvu.ts | 19 ++++++++++++------- 7 files changed, 53 insertions(+), 11 deletions(-) create mode 100644 src/helpers/getPastvuRandomPhotos.ts diff --git a/src/helpers/createKeyboard.ts b/src/helpers/createKeyboard.ts index fd1964f..0016db9 100644 --- a/src/helpers/createKeyboard.ts +++ b/src/helpers/createKeyboard.ts @@ -6,6 +6,7 @@ import { ContextBot } from '../index' export const createKeyboard = (ctx: ContextBot): Markup.Markup => Markup.keyboard([ Markup.button.locationRequest(ctx.i18n.t('buttons.location')), + Markup.button.callback(ctx.i18n.t('buttons.randomPhotos'), 'randomPhotos'), Markup.button.callback(ctx.i18n.t('buttons.morePhotos'), 'morePhotos'), Markup.button.callback(ctx.i18n.t('buttons.settings'), 'settings'), ]).resize() diff --git a/src/helpers/getPastvuRandomPhotos.ts b/src/helpers/getPastvuRandomPhotos.ts new file mode 100644 index 0000000..e6b9982 --- /dev/null +++ b/src/helpers/getPastvuRandomPhotos.ts @@ -0,0 +1,24 @@ +import fetch from 'node-fetch' + +import { PastvuItem } from './getPastvuPhotos' + +export type PastvuPhotos = { + result: { photos: PastvuItem[] } +} +export const getPastvuRandomPhotos = async (): Promise => { + const response = await fetch( + `https://pastvu.com/api2?method=photo.givePS¶ms={"cid":1,"random":true}`, + ) + + if (!response.ok) { + throw new Error(`Request failed: ${response.url}: ${response.status}`) + } + + const json = (await response.json()) as { error: { error_msg: string } } | PastvuPhotos + + if ('error' in json) { + throw new Error(`Request failed: ${response.url}: ${json.error.error_msg}`) + } + + return json +} diff --git a/src/helpers/sendPhotos.ts b/src/helpers/sendPhotos.ts index 8d7d8a7..af72fb3 100644 --- a/src/helpers/sendPhotos.ts +++ b/src/helpers/sendPhotos.ts @@ -9,12 +9,12 @@ export const sendPhotos = async ( await ctx.replyWithMediaGroup( pastvuData.map((item) => ({ media: { url: `https://pastvu.com/_p/d/${item.file}` }, - caption: `${item.year} ${item.title}`, + caption: `${item.year} ${item.title} https://pastvu.com/p/${item.cid}`, parse_mode: 'HTML', type: 'photo', })), ) } catch (error) { - throw new Error(ctx.i18n.t('errors.errorRequestPhotos')) + throw new Error(ctx.i18n.t('errors.errorSendPhotos')) } } diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 84214b5..9e445fc 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -9,10 +9,12 @@ "errorLetsTry": "Error, please try again.", "errorSave": "Error saving settings.", "errorSetPeriod": "Error, please enter a valid period.", - "errorParseURL": "Something with the link. Try choosing a specific location." + "errorParseURL": "Something with the link. Try choosing a specific location.", + "errorSendPhotos": "Error sending photos" }, "buttons": { "location": "🧭 Send location", + "randomPhotos": "🎲 Random photos", "morePhotos": "🔍 More photos", "settings": "⚙️ Settings" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index cd3fa81..fb39f92 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -9,10 +9,12 @@ "errorLetsTry": "Ошибка, попробуйте еще раз.", "errorSave": "Ошибка сохранения настроек.", "errorSetPeriod": "Ошибка, введите корректный период.", - "errorParseURL": "Что то с ссылкой. Попробуйте выбрать конкретное местоположение." + "errorParseURL": "Что то с ссылкой. Попробуйте выбрать конкретное местоположение.", + "errorSendPhotos": "Ошибка отправки фотографий" }, "buttons": { "location": "🧭 Отправить местоположение", + "randomPhotos": "🎲 Случайные фотографии", "morePhotos": "🔍 Еще фотографий", "settings": "⚙️ Настройки" } diff --git a/src/index.ts b/src/index.ts index 464fa1b..5f77ee2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -36,6 +36,7 @@ export interface ContextBot extends Context { latitude: number longitude: number } + random: boolean } const bot = new Telegraf(process.env.BOT_TOKEN) @@ -86,6 +87,13 @@ async function main() { .then(() => ctx.scene.enter('pastvu')) }) + bot.hears(new RegExp('🎲'), (ctx: ContextBot) => { + return ctx + .reply(ctx.i18n.t('buttons.randomPhotos'), createKeyboard(ctx)) + .then(() => (ctx.random = true)) + .then(() => ctx.scene.enter('pastvu')) + }) + bot.hears( new RegExp('https://maps.app.goo.gl|https://www.google.com/maps/place'), (ctx) => { diff --git a/src/scenes/pastvu.ts b/src/scenes/pastvu.ts index 740f270..3dd7fcf 100644 --- a/src/scenes/pastvu.ts +++ b/src/scenes/pastvu.ts @@ -3,24 +3,27 @@ import isEmpty from 'lodash/isEmpty' import { Scenes } from 'telegraf' import { getPastvuPhotos } from '../helpers/getPastvuPhotos' +import { getPastvuRandomPhotos } from '../helpers/getPastvuRandomPhotos' import { sendPhotos } from '../helpers/sendPhotos' import { ContextBot } from '../index' export const pastvu = new Scenes.BaseScene('pastvu') pastvu.enter(async (ctx: ContextBot) => { - if (ctx.geo) { + if (ctx.geo || ctx.random) { ctx.scene.session.pastvuData = undefined const startYear = ctx.data.startYear || 1839 const endYear = ctx.data.endYear || 2000 try { - const { result } = await getPastvuPhotos({ - latitude: ctx.geo.latitude, - longitude: ctx.geo.longitude, - startYear, - endYear, - }) + const { result } = ctx.random + ? await getPastvuRandomPhotos() + : await getPastvuPhotos({ + latitude: ctx.geo.latitude, + longitude: ctx.geo.longitude, + startYear, + endYear, + }) if (result.photos.length === 0) { await ctx.scene.leave() @@ -32,10 +35,12 @@ pastvu.enter(async (ctx: ContextBot) => { await sendPhotos(ctx, firstChunk) if (isEmpty(otherChunks)) { + ctx.random = false await ctx.scene.leave() } ctx.scene.session.pastvuData = otherChunks ctx.scene.session.counterData = 0 + ctx.random = false } catch (err) { if (err instanceof Error) { return await ctx.reply(`${ctx.i18n.t('errors.error')} ${err.message}`)