Skip to content

Commit

Permalink
feat: add support random photos (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
ratmirslv authored Apr 28, 2024
1 parent 78c2ff1 commit 009dd01
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 11 deletions.
1 change: 1 addition & 0 deletions src/helpers/createKeyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ContextBot } from '../index'
export const createKeyboard = (ctx: ContextBot): Markup.Markup<ReplyKeyboardMarkup> =>
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()
24 changes: 24 additions & 0 deletions src/helpers/getPastvuRandomPhotos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import fetch from 'node-fetch'

import { PastvuItem } from './getPastvuPhotos'

export type PastvuPhotos = {
result: { photos: PastvuItem[] }
}
export const getPastvuRandomPhotos = async (): Promise<PastvuPhotos> => {
const response = await fetch(
`https://pastvu.com/api2?method=photo.givePS&params={"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
}
4 changes: 2 additions & 2 deletions src/helpers/sendPhotos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
}
}
4 changes: 3 additions & 1 deletion src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
4 changes: 3 additions & 1 deletion src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
"errorLetsTry": "Ошибка, попробуйте еще раз.",
"errorSave": "Ошибка сохранения настроек.",
"errorSetPeriod": "Ошибка, введите корректный период.",
"errorParseURL": "Что то с ссылкой. Попробуйте выбрать конкретное местоположение."
"errorParseURL": "Что то с ссылкой. Попробуйте выбрать конкретное местоположение.",
"errorSendPhotos": "Ошибка отправки фотографий"
},
"buttons": {
"location": "🧭 Отправить местоположение",
"randomPhotos": "🎲 Случайные фотографии",
"morePhotos": "🔍 Еще фотографий",
"settings": "⚙️ Настройки"
}
Expand Down
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface ContextBot extends Context {
latitude: number
longitude: number
}
random: boolean
}

const bot = new Telegraf<ContextBot>(process.env.BOT_TOKEN)
Expand Down Expand Up @@ -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) => {
Expand Down
19 changes: 12 additions & 7 deletions src/scenes/pastvu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ContextBot>('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()
Expand All @@ -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}`)
Expand Down

0 comments on commit 009dd01

Please sign in to comment.