Skip to content

Commit

Permalink
feat(telegram): allow receiving file/audio/video/image (#543)
Browse files Browse the repository at this point in the history
* feat(telegram): allow receiving file/audio/video/image

* Pr changes
  • Loading branch information
davidvitora committed Oct 14, 2022
1 parent 15205a0 commit ba628dd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
8 changes: 4 additions & 4 deletions packages/channels/src/telegram/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
| Postback || |
| Say Something || |
| Voice || |
| Image | | |
| File | | |
| Audio | | |
| Video | | |
| Image | | |
| File | | |
| Audio | | |
| Video | | |
| Location || |
44 changes: 43 additions & 1 deletion packages/channels/src/telegram/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Response } from 'express'
import _ from 'lodash'
import { Context, NarrowedContext } from 'telegraf'
import { Update } from 'telegraf/typings/core/types/typegram'
import { Update, Document, Video, Audio, Message } from 'telegraf/typings/core/types/typegram'
import yn from 'yn'
import { ChannelApi, ChannelApiManager, ChannelApiRequest } from '../base/api'
import { ChannelInitializeEvent, ChannelStartEvent, ChannelStopEvent } from '../base/service'
Expand Down Expand Up @@ -58,6 +59,36 @@ export class TelegramApi extends ChannelApi<TelegramService> {
private async handleTelegrafMessage(scope: string, ctx: NarrowedContext<Context<Update>, Update.MessageUpdate>) {
if ('text' in ctx.message) {
await this.service.receive(scope, this.extractEndpoint(ctx), { type: 'text', text: ctx.message.text })
} else if ('photo' in ctx.message) {
// Same photo in different sizes, get the last one since it
// has the best quality
const item = ctx.message.photo.pop()

if (!item) {
return
}

await this.service.receive(scope, this.extractEndpoint(ctx), {
type: this.mapTypeToStandardType('photo'),
url: await ctx.telegram.getFileLink(item.file_id),
title: ctx.message.caption
})
} else {
const message = ctx.message as Message.CaptionableMessage
const type = Object.keys(message).find((i) => ['document', 'video', 'audio'].includes(i))

if (!type) {
// Type not supported, swallow
return
}

const item = _.get(message, type) as Document | Video | Audio

await this.service.receive(scope, this.extractEndpoint(ctx), {
type: this.mapTypeToStandardType(type),
url: await ctx.telegram.getFileLink(item.file_id),
title: message.caption
})
}
}

Expand Down Expand Up @@ -103,4 +134,15 @@ export class TelegramApi extends ChannelApi<TelegramService> {
// TODO: remove this dependency on server env vars
return !yn(process.env.SPINNED) || yn(process.env.CLUSTER_ENABLED)
}

private mapTypeToStandardType(type: string) {
switch (type) {
case 'document':
return 'file'
case 'photo':
return 'image'
default:
return type
}
}
}

0 comments on commit ba628dd

Please sign in to comment.