Browse Source

- init adapter-potato

master
pimhwang 1 year ago
commit
e3c6a13936
  1. 9
      .editorconfig
  2. 7
      .gitattributes
  3. 17
      .gitignore
  4. 2
      .npmignore
  5. 25
      package.json
  6. 5
      readme.md
  7. 275
      src/bot.ts
  8. 29
      src/index.ts
  9. 133
      src/message.ts
  10. 93
      src/polling.ts
  11. 51
      src/server.ts
  12. 2
      src/types/.eslintrc.yml
  13. 112
      src/types/game.ts
  14. 2992
      src/types/index.ts
  15. 857
      src/types/inline.ts
  16. 37
      src/types/internal.ts
  17. 256
      src/types/passport.ts
  18. 304
      src/types/payment.ts
  19. 242
      src/types/sticker.ts
  20. 107
      src/types/update.ts
  21. 199
      src/utils.ts
  22. 19
      tsconfig.json

9
.editorconfig

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
root = true
[*]
insert_final_newline = true
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true

7
.gitattributes vendored

@ -0,0 +1,7 @@ @@ -0,0 +1,7 @@
* text eol=lf
*.png -text
*.jpg -text
*.ico -text
*.gif -text
*.webp -text

17
.gitignore vendored

@ -0,0 +1,17 @@ @@ -0,0 +1,17 @@
lib
dist
node_modules
npm-debug.log
yarn-debug.log
yarn-error.log
tsconfig.tsbuildinfo
.eslintcache
.DS_Store
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln

2
.npmignore

@ -0,0 +1,2 @@ @@ -0,0 +1,2 @@
.DS_Store
tsconfig.tsbuildinfo

25
package.json

@ -0,0 +1,25 @@ @@ -0,0 +1,25 @@
{
"name": "koishi-plugin-adapter-potato",
"description": "Potato 适配器",
"version": "0.0.1",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"files": [
"lib",
"dist"
],
"license": "MIT",
"scripts": {},
"keywords": [
"chatbot",
"koishi",
"plugin"
],
"peerDependencies": {
"koishi": "^4.15.0"
},
"dependencies": {
"file-type": "^16.5.4",
"form-data": "^4.0.0"
}
}

5
readme.md

@ -0,0 +1,5 @@ @@ -0,0 +1,5 @@
# koishi-plugin-adapter-potato
[![npm](https://img.shields.io/npm/v/koishi-plugin-adapter-potato?style=flat-square)](https://www.npmjs.com/package/koishi-plugin-adapter-potato)
Potato 适配器

275
src/bot.ts

@ -0,0 +1,275 @@ @@ -0,0 +1,275 @@
import { arrayBufferToBase64, Bot, Context, Dict, h, Logger, Quester, Schema, Time, Universal } from '@satorijs/satori'
import * as Potato from './types'
import { decodeGuildMember, decodeUser } from './utils'
import { PotatoMessageEncoder } from './message'
import { HttpServer } from './server'
import { HttpPolling } from './polling'
import FileType from 'file-type'
const logger = new Logger('potato')
export class SenderError extends Error {
constructor(args: Dict<any>, url: string, retcode: number, selfId: string) {
super(`Error when trying to send to ${url}, args: ${JSON.stringify(args)}, retcode: ${retcode}`)
Object.defineProperties(this, {
name: { value: 'SenderError' },
selfId: { value: selfId },
code: { value: retcode },
args: { value: args },
url: { value: url },
})
}
}
export interface PotatoResponse {
ok: boolean
result: any
}
export class PotatoBot<T extends PotatoBot.Config = PotatoBot.Config> extends Bot<T> {
static MessageEncoder = PotatoMessageEncoder
http: Quester
file: Quester
internal: Potato.Internal
local?: boolean
server?: string
constructor(ctx: Context, config: T) {
super(ctx, config)
this.platform = 'potato'
this.selfId = config.token.split(':')[0]
this.local = config.files.local
this.http = this.ctx.http.extend({
...config,
endpoint: `${config.endpoint}/${config.token}`,
})
this.file = this.ctx.http.extend({
...config,
endpoint: `${config.files.endpoint || config.endpoint}/files/${config.token}`,
})
this.internal = new Potato.Internal(this.http)
if (config.protocol === 'server') {
ctx.plugin(HttpServer, this)
} else if (config.protocol === 'polling') {
ctx.plugin(HttpPolling, this)
}
const selfUrl: string = config['selfUrl'] || ctx.root.config.selfUrl
if (config.files.server ?? selfUrl) {
const route = `/potato/${this.selfId}`
this.server = selfUrl + route
ctx.router.get(route + '/:file+', async ctx => {
const { data, mime } = await this.$getFile(ctx.params.file)
ctx.set('content-type', mime)
ctx.body = data
})
}
}
async initialize(callback: (bot: this) => Promise<void>) {
const user = await this.getLoginInfo()
Object.assign(this, user)
await callback(this)
logger.debug('connected to %c', 'potato:' + this.selfId)
this.online()
}
async deleteMessage(chat_id: string, message_id: string | number) {
message_id = +message_id
await this.internal.deleteMessage({ chat_id, message_id })
}
async editMessage(chat_id: string, message_id: string | number, content: h.Fragment): Promise<void> {
message_id = +message_id
const payload: Potato.EditMessageTextPayload = {
chat_id,
message_id,
parse_mode: 'html',
}
payload.text = h.normalize(content).join('')
await this.internal.editMessageText(payload)
}
static adaptGroup(data: Potato.Chat): Universal.Guild {
data['guildId'] = data.id + ''
data['guildName'] = data.title
return data as any
}
async getGuild(chat_id: string): Promise<Universal.Guild> {
const data = await this.internal.getChat({ chat_id })
return PotatoBot.adaptGroup(data)
}
async getGuildMember(chat_id: string, user_id: string | number) {
user_id = +user_id
if (Number.isNaN(user_id)) return null
const data = await this.internal.getChatMember({ chat_id, user_id })
const member = decodeGuildMember(data)
await this.setAvatarUrl(member.user)
return member
}
async getGuildMemberList(chat_id: string) {
const data = await this.internal.getChatAdministrators({ chat_id })
const members = data.map(decodeGuildMember)
return { data: members }
}
async kickGuildMember(chat_id: string, user_id: string | number, permanent?: boolean) {
user_id = +user_id
await this.internal.banChatMember({
chat_id,
user_id,
until_date: Date.now() + (permanent ? 0 : Time.minute),
revoke_messages: true,
})
}
setGroupLeave(chat_id: string) {
return this.internal.leaveChat({ chat_id })
}
async handleGuildMemberRequest(messageId: string, approve: boolean, comment?: string) {
const [chat_id, user_id] = messageId.split('@')
const method = approve ? 'approveChatJoinRequest' : 'declineChatJoinRequest'
const success = await this.internal[method]({ chat_id, user_id: +user_id })
if (!success) throw new Error(`handel guild member request field ${success}`)
}
async getLoginInfo() {
const data = await this.internal.getMe()
const user = decodeUser(data)
//await this.setAvatarUrl(user)
return user
}
async $getFile(filePath: string) {
if (this.local) {
return await this.ctx.http.file(filePath)
} else {
return await this.file.file(`/${filePath}`)
}
}
async $getFileFromId(file_id: string) {
try {
const file = await this.internal.getFile({ file_id })
return await this.$getFileFromPath(file.file_path)
} catch (e) {
logger.warn('get file error', e)
}
}
async $getFileFromPath(filePath: string) {
if (this.server) {
return { url: `${this.server}/${filePath}` }
}
let { mime, data } = await this.$getFile(filePath)
if (mime === 'application/octet-stream') {
mime = (await FileType.fromBuffer(data))?.mime
}
const base64 = `data:${mime};base64,` + arrayBufferToBase64(data)
return { url: base64 }
}
private async setAvatarUrl(user: Universal.User) {
const { photos: [avatar] } = await this.internal.getUserProfilePhoto({ user_id: +user.id })
if (!avatar) return
const { file_id } = avatar[avatar.length - 1]
const file = await this.internal.getFile({ file_id })
if (this.server) {
user.avatar = `${this.server}/${file.file_path}`
} else {
const { endpoint } = this.file.config
user.avatar = `${endpoint}/${file.file_path}`
}
}
async getUser(userId: string, guildId?: string) {
const data = await this.internal.getChat({ chat_id: userId })
if (!data.photo?.big_file_id && !data.photo?.small_file_id) return decodeUser(data)
const { url } = await this.$getFileFromId(data.photo?.big_file_id || data.photo?.small_file_id)
return {
...decodeUser(data),
avatar: url,
}
}
async createDirectChannel(id: string) {
return { id, type: Universal.Channel.Type.DIRECT }
}
async updateCommands(commands: Universal.Command[]) {
if (!this.config.slash) return
const result = {} as Record<string, Potato.BotCommand[]>
for (const cmd of commands) {
const { name, description } = cmd
const languages = {} as Record<string, string>
for (const locale in description) {
if (!locale || !description[locale]) continue
const lang = locale.slice(0, 2)
languages[lang] ||= description[locale]
}
for (const lang in languages) {
result[lang] ??= []
result[lang].push({ command: name, description: languages[lang] })
}
}
for (const lang in result) {
await this.internal.setMyCommands({
commands: result[lang],
language_code: lang,
})
}
await this.internal.setMyCommands({
commands: commands.map(({ name, description }) => ({
command: name,
description: description[''] || name,
})),
})
}
}
export namespace PotatoBot {
export interface BaseConfig extends Quester.Config {
protocol: 'server' | 'polling'
token: string
files?: Config.Files
slash?: boolean
}
export type Config = BaseConfig & (HttpServer.Config | HttpPolling.Config)
export namespace Config {
export interface Files {
endpoint?: string
local?: boolean
server?: boolean
}
}
export const Config: Schema<Config> = Schema.intersect([
Schema.object({
token: Schema.string().description('机器人的用户令牌。').role('secret').required(),
protocol: process.env.KOISHI_ENV === 'browser'
? Schema.const('polling').default('polling')
: Schema.union(['server', 'polling']).description('选择要使用的协议。').required(),
}),
Schema.union([
HttpServer.Config,
HttpPolling.Config,
]).description('推送设置'),
Schema.object({
slash: Schema.boolean().description('是否启用斜线指令。').default(true),
}).description('功能设置'),
Quester.createConfig('https://api.rct2008.com:8443'),
Schema.object({
files: Schema.object({
endpoint: Schema.string().description('文件请求的终结点。'),
local: Schema.boolean().description('是否启用 [Potato Bot API](https://github.com/tdlib/potato-bot-api) 本地模式。'),
server: Schema.boolean().description('是否启用文件代理。若开启将会使用 `selfUrl` 进行反代,否则会下载所有资源文件 (包括图片、视频等)。当配置了 `selfUrl` 时将默认开启。'),
}),
}).hidden(process.env.KOISHI_ENV === 'browser').description('文件设置'),
] as const)
}

29
src/index.ts

@ -0,0 +1,29 @@ @@ -0,0 +1,29 @@
import { PotatoBot } from './bot'
import * as Potato from './types'
export { Potato }
export * from './bot'
export * from './polling'
export * from './message'
export * from './server'
export * from './utils'
export default PotatoBot
type ParamCase<S extends string> =
| S extends `${infer L}${infer R}`
? `${L extends '_' ? '-' : Lowercase<L>}${ParamCase<R>}`
: S
type PotatoEvents = {
[T in Exclude<keyof Potato.Update, 'update_id'> as `potato/${ParamCase<T>}`]: (input: Potato.Update[T]) => void
}
declare module '@satorijs/core' {
interface Session {
potato?: Potato.Update & Potato.Internal
}
interface Events extends PotatoEvents {}
}

133
src/message.ts

@ -0,0 +1,133 @@ @@ -0,0 +1,133 @@
import { Dict, h, MessageEncoder, Universal } from '@satorijs/satori'
import FormData from 'form-data'
import { PotatoBot } from './bot'
import * as Potato from './utils'
type RenderMode = 'default' | 'figure'
type AssetMethod = 'sendPhoto' | 'sendAudio' | 'sendDocument' | 'sendVideo' | 'sendAnimation' | 'sendVoice'
async function appendAsset(bot: PotatoBot, form: FormData, element: h): Promise<AssetMethod> {
let method: AssetMethod
const { filename, data, mime } = await bot.ctx.http.file(element.attrs.url, element.attrs)
if (element.type === 'image') {
method = mime === 'image/gif' ? 'sendAnimation' : 'sendPhoto'
} else if (element.type === 'file') {
method = 'sendDocument'
} else if (element.type === 'video') {
method = 'sendVideo'
} else if (element.type === 'audio') {
method = element.attrs.type === 'voice' ? 'sendVoice' : 'sendAudio'
}
// https://github.com/form-data/form-data/issues/468
const value = process.env.KOISHI_ENV === 'browser'
? new Blob([data], { type: mime })
: Buffer.from(data)
form.append(method.slice(4).toLowerCase(), value, filename)
return method
}
const supportedElements = ['b', 'strong', 'i', 'em', 'u', 'ins', 's', 'del', 'a']
export class PotatoMessageEncoder extends MessageEncoder<PotatoBot> {
private asset: h = null
private payload: Dict
private mode: RenderMode = 'default'
constructor(bot: PotatoBot, channelId: string, guildId?: string, options?: Universal.SendOptions) {
super(bot, channelId, guildId, options)
const chat_id = guildId || channelId
this.payload = { chat_id, parse_mode: 'html', caption: '' }
if (guildId && channelId !== guildId) this.payload.message_thread_id = +channelId
}
async addResult(result: Potato.Message) {
const session = this.bot.session()
await Potato.decodeMessage(this.bot, result, session.event.message = {}, session.event)
this.results.push(session.event.message)
session.app.emit(session, 'send', session)
}
async sendAsset() {
const form = new FormData()
for (const key in this.payload) {
form.append(key, this.payload[key].toString())
}
const method = await appendAsset(this.bot, form, this.asset)
const result = await this.bot.internal[method](form as any)
await this.addResult(result)
delete this.payload.reply_to_message_id
this.asset = null
this.payload.caption = ''
}
async flush() {
if (this.asset) {
// send previous asset if there is any
await this.sendAsset()
} else if (this.payload.caption) {
const result = await this.bot.internal.sendMessage({
chat_id: this.payload.chat_id,
text: this.payload.caption,
parse_mode: this.payload.parse_mode,
reply_to_message_id: this.payload.reply_to_message_id,
message_thread_id: this.payload.message_thread_id,
disable_web_page_preview: !this.options.linkPreview,
})
await this.addResult(result)
delete this.payload.reply_to_message_id
this.payload.caption = ''
}
}
async visit(element: h) {
const { type, attrs, children } = element
if (type === 'text') {
this.payload.caption += h.escape(attrs.content)
} else if (type === 'br') {
this.payload.caption += '\n'
} else if (type === 'p') {
if (!this.payload.caption.endsWith('\n')) this.payload.caption += '\n'
await this.render(children)
if (!this.payload.caption.endsWith('\n')) this.payload.caption += '\n'
} else if (supportedElements.includes(type)) {
this.payload.caption += element.toString()
} else if (type === 'spl') {
this.payload.caption += '<tg-spoiler>'
await this.render(children)
this.payload.caption += '</tg-spoiler>'
} else if (type === 'code') {
const { lang } = attrs
this.payload.caption += `<code${lang ? ` class="language-${lang}"` : ''}>${h.escape(attrs.content)}</code>`
} else if (type === 'at') {
if (attrs.id) {
this.payload.caption += `<a href="tg://user?id=${attrs.id}">@${attrs.name || attrs.id}</a>`
}
} else if (['image', 'audio', 'video', 'file'].includes(type)) {
if (this.mode === 'default') {
await this.flush()
}
this.asset = element
} else if (type === 'figure') {
await this.flush()
this.mode = 'figure'
await this.render(children)
await this.flush()
this.mode = 'default'
} else if (type === 'quote') {
await this.flush()
this.payload.reply_to_message_id = attrs.id
} else if (type === 'message') {
if (this.mode === 'figure') {
await this.render(children)
this.payload.caption += '\n'
} else {
await this.flush()
await this.render(children)
await this.flush()
}
} else {
await this.render(children)
}
}
}

93
src/polling.ts

@ -0,0 +1,93 @@ @@ -0,0 +1,93 @@
import { Adapter, Logger, Quester, Schema, Time, Universal } from '@satorijs/satori'
import { PotatoBot } from './bot'
import { handleUpdate } from './utils'
const logger = new Logger('potato')
export class HttpPolling extends Adapter<PotatoBot> {
static reusable = true
private offset = 0
private timeout: NodeJS.Timeout
async connect(bot: PotatoBot<PotatoBot.BaseConfig & HttpPolling.Config>) {
bot.initialize(async () => {
let _retryCount = 0
let _initial = true
const { retryTimes, retryInterval } = bot.config
const { url } = await bot.internal.getWebhookInfo()
if (url) {
logger.warn('Bot currently has a webhook set up, trying to remove it...')
await bot.internal.setWebhook({ url: '' })
}
// Test connection / init offset with 0 timeout polling
const previousUpdates = await bot.internal.getUpdates({
allowed_updates: [],
timeout: 0,
})
previousUpdates.forEach((e) => {
this.offset = Math.max(this.offset, e.update_id)
})
const polling = async () => {
try {
const updates = await bot.internal.getUpdates({
offset: this.offset + 1,
timeout: Math.ceil(bot.config.pollingTimeout / 1000), // in seconds
})
if (!bot.isActive) return
bot.online()
_retryCount = 0
_initial = false
for (const e of updates) {
this.offset = Math.max(this.offset, e.update_id)
handleUpdate(e, bot)
}
this.timeout = setTimeout(polling, 0)
} catch (e) {
if (!Quester.isAxiosError(e) || !e.response?.data) {
// Other error
logger.warn('failed to get updates. reason: %s', e.message)
} else {
// Telegram error
const { error_code, description } = e.response.data as any
logger.warn('failed to get updates: %c %s', error_code, description)
}
if (_initial && _retryCount > retryTimes) {
bot.error = e
return bot.status = Universal.Status.OFFLINE
}
if (!bot.isActive) return
_retryCount++
bot.status = Universal.Status.RECONNECT
this.timeout = setTimeout(polling, retryInterval)
}
}
polling()
logger.debug('listening updates %c', 'potato: ' + bot.selfId)
})
}
async disconnect() {
clearTimeout(this.timeout)
}
}
export namespace HttpPolling {
export interface Config {
protocol: 'polling'
pollingTimeout?: number
retryTimes?: number
retryInterval?: number
}
export const Config: Schema<Config> = Schema.object({
protocol: Schema.const('polling').required(process.env.KOISHI_ENV !== 'browser'),
pollingTimeout: Schema.natural().role('ms').default(Time.second * 25).description('通过长轮询获取更新时请求的超时 (单位为毫秒)。'),
retryTimes: Schema.natural().description('初次连接时的最大重试次数。').default(6),
retryInterval: Schema.natural().role('ms').default(Time.second * 5).description('长轮询断开后的重试时间间隔 (单位为毫秒)。'),
})
}

51
src/server.ts

@ -0,0 +1,51 @@ @@ -0,0 +1,51 @@
import { Adapter, Logger, sanitize, Schema, trimSlash } from '@satorijs/satori'
import { PotatoBot } from './bot'
import { handleUpdate } from './utils'
import * as Potato from './types'
const logger = new Logger('potato')
export class HttpServer extends Adapter<PotatoBot> {
async connect(bot: PotatoBot<PotatoBot.BaseConfig & HttpServer.Config>) {
let { token, path, selfUrl } = bot.config
path = sanitize(path || '/potato')
if (selfUrl) {
selfUrl = trimSlash(selfUrl)
} else {
selfUrl = bot.ctx.root.config.selfUrl
}
bot.ctx.router.post(path, async (ctx) => {
const payload: Potato.Update = ctx.request.body
const token = ctx.request.query.token as string
const [selfId] = token.split(':')
const bot = this.bots.find(bot => bot.selfId === selfId)
if (!(bot?.config?.token === token)) return ctx.status = 403
ctx.body = 'OK'
await handleUpdate(payload, bot)
})
bot.initialize(async (bot) => {
const info = await bot.internal.setWebhook({
url: selfUrl + path + '?token=' + token,
drop_pending_updates: true,
})
//if (!info) throw new Error('Set webhook failed')
logger.debug('listening updates %c', 'potato: ' + bot.selfId)
})
}
}
export namespace HttpServer {
export interface Config {
protocol: 'server'
path?: string
selfUrl?: string
}
export const Config: Schema<Config> = Schema.object({
protocol: Schema.const('server').required(),
path: Schema.string().description('服务器监听的路径。').default('/potato'),
selfUrl: Schema.string().role('link').description('服务器暴露在公网的地址。缺省时将使用全局配置。'),
})
}

2
src/types/.eslintrc.yml

@ -0,0 +1,2 @@ @@ -0,0 +1,2 @@
rules:
max-len: off

112
src/types/game.ts

@ -0,0 +1,112 @@ @@ -0,0 +1,112 @@
import { InlineKeyboardMarkup, Integer, Internal, Message, MessageEntity, PhotoSize, User } from '.'
export interface SendGamePayload {
/** Unique identifier for the target chat */
chat_id?: Integer
/** Unique identifier for the target message thread (topic) of the forum; for forum supergroups only */
message_thread_id?: number
/** Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. */
game_short_name?: string
/** Sends the message silently. Users will receive a notification with no sound. */
disable_notification?: boolean
/** Protects the contents of the sent message from forwarding and saving */
protect_content?: boolean
/** If the message is a reply, ID of the original message */
reply_to_message_id?: Integer
/** Pass True, if the message should be sent even if the specified replied-to message is not found */
allow_sending_without_reply?: boolean
/** A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. */
reply_markup?: InlineKeyboardMarkup
}
/**
* This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers.
* @see https://potato.im/api#game
*/
export interface Game {
/** Title of the game */
title?: string
/** Description of the game */
description?: string
/** Photo that will be displayed in the game message in chats. */
photo?: PhotoSize[]
/** Optional. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls setGameScore, or manually edited using editMessageText. 0-4096 characters. */
text?: string
/** Optional. Special entities that appear in text, such as usernames, URLs, bot commands, etc. */
text_entities?: MessageEntity[]
/** Optional. Animation that will be displayed in the game message in chats. Upload via BotFather */
animation?: Animation
}
/**
* A placeholder, currently holds no information. Use BotFather to set up your game.
* @see https://potato.im/api#callbackgame
*/
export type CallbackGame = any
export interface SetGameScorePayload {
/** User identifier */
user_id?: Integer
/** New score, must be non-negative */
score?: Integer
/** Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters */
force?: boolean
/** Pass True, if the game message should not be automatically edited to include the current scoreboard */
disable_edit_message?: boolean
/** Required if inline_message_id is not specified. Unique identifier for the target chat */
chat_id?: Integer
/** Required if inline_message_id is not specified. Identifier of the sent message */
message_id?: Integer
/** Required if chat_id and message_id are not specified. Identifier of the inline message */
inline_message_id?: string
}
export interface GetGameHighScoresPayload {
/** Target user id */
user_id?: Integer
/** Required if inline_message_id is not specified. Unique identifier for the target chat */
chat_id?: Integer
/** Required if inline_message_id is not specified. Identifier of the sent message */
message_id?: Integer
/** Required if chat_id and message_id are not specified. Identifier of the inline message */
inline_message_id?: string
}
/**
* This object represents one row of the high scores table for a game.
* @see https://potato.im/api#gamehighscore
*/
export interface GameHighScore {
/** Position in high score table for the game */
position?: Integer
/** User */
user?: User
/** Score */
score?: Integer
}
declare module './internal' {
interface Internal {
/**
* Use this method to send a game. On success, the sent Message is returned.
* @see https://potato.im/api#sendgame
*/
sendGame(payload: SendGamePayload): Promise<Message>
/**
* Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
* @see https://potato.im/api#setgamescore
*/
setGameScore(payload: SetGameScorePayload): Promise<Message | boolean>
/**
* Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. On success, returns an GameHighScore objects.
*
* This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
* @see https://potato.im/api#getgamehighscores
*/
getGameHighScores(payload: GetGameHighScoresPayload): Promise<GameHighScore>
}
}
Internal.define('sendGame')
Internal.define('setGameScore')
Internal.define('getGameHighScores')

2992
src/types/index.ts

File diff suppressed because it is too large Load Diff

857
src/types/inline.ts

@ -0,0 +1,857 @@ @@ -0,0 +1,857 @@
import { Float, InlineKeyboardMarkup, Integer, Internal, LabeledPrice, MessageEntity, User } from '.'
/**
* This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
* @see https://potato.im/api#inlinequery
*/
export interface InlineQuery {
/** Unique identifier for this query */
id?: string
/** Sender */
from?: User
/** Text of the query (up to 256 characters) */
query?: string
/** Offset of the results to be returned, can be controlled by the bot */
offset?: string
/** Optional. Type of the chat, from which the inline query was sent. Can be either "sender" for a private chat with the inline query sender, "private", "group", "supergroup", or "channel". The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat */
chat_type?: string
/** Optional. Sender location, only for bots that request user location */
location?: Location
}
export interface AnswerInlineQueryPayload {
/** Unique identifier for the answered query */
inline_query_id?: string
/** A JSON-serialized array of results for the inline query */
results?: InlineQueryResult[]
/** The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. */
cache_time?: Integer
/** Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query */
is_personal?: boolean
/** Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. */
next_offset?: string
/** If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter */
switch_pm_text?: string
/**
* Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.
*
* Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities.
*/
switch_pm_parameter?: string
}
/**
* This object represents one result of an inline query. Telegram clients currently support results of the following 20 types:
* - InlineQueryResultCachedAudio
* - InlineQueryResultCachedDocument
* - InlineQueryResultCachedGif
* - InlineQueryResultCachedMpeg4Gif
* - InlineQueryResultCachedPhoto
* - InlineQueryResultCachedSticker
* - InlineQueryResultCachedVideo
* - InlineQueryResultCachedVoice
* - InlineQueryResultArticle
* - InlineQueryResultAudio
* - InlineQueryResultContact
* - InlineQueryResultGame
* - InlineQueryResultDocument
* - InlineQueryResultGif
* - InlineQueryResultLocation
* - InlineQueryResultMpeg4Gif
* - InlineQueryResultPhoto
* - InlineQueryResultVenue
* - InlineQueryResultVideo
* - InlineQueryResultVoice
* Note: All URLs passed in inline query results will be available to end users and therefore must be assumed to be public.
* @see https://potato.im/api#inlinequeryresult
*/
export type InlineQueryResult =
| InlineQueryResultCachedAudio
| InlineQueryResultCachedDocument
| InlineQueryResultCachedGif
| InlineQueryResultCachedMpeg4Gif
| InlineQueryResultCachedPhoto
| InlineQueryResultCachedSticker
| InlineQueryResultCachedVideo
| InlineQueryResultCachedVoice
| InlineQueryResultArticle
| InlineQueryResultAudio
| InlineQueryResultContact
| InlineQueryResultGame
| InlineQueryResultDocument
| InlineQueryResultGif
| InlineQueryResultLocation
| InlineQueryResultMpeg4Gif
| InlineQueryResultPhoto
| InlineQueryResultVenue
| InlineQueryResultVideo
| InlineQueryResultVoice
/**
* Represents a link to an article or web page.
* @see https://potato.im/api#inlinequeryresultarticle
*/
export interface InlineQueryResultArticle {
/** Type of the result, must be article */
type?: string
/** Unique identifier for this result, 1-64 Bytes */
id?: string
/** Title of the result */
title?: string
/** Content of the message to be sent */
input_message_content?: InputMessageContent
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. URL of the result */
url?: string
/** Optional. Pass True, if you don't want the URL to be shown in the message */
hide_url?: boolean
/** Optional. Short description of the result */
description?: string
/** Optional. Url of the thumbnail for the result */
thumb_url?: string
/** Optional. Thumbnail width */
thumb_width?: Integer
/** Optional. Thumbnail height */
thumb_height?: Integer
}
/**
* Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.
* @see https://potato.im/api#inlinequeryresultphoto
*/
export interface InlineQueryResultPhoto {
/** Type of the result, must be photo */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB */
photo_url?: string
/** URL of the thumbnail for the photo */
thumb_url?: string
/** Optional. Width of the photo */
photo_width?: Integer
/** Optional. Height of the photo */
photo_height?: Integer
/** Optional. Title for the result */
title?: string
/** Optional. Short description of the result */
description?: string
/** Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the photo caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the photo */
input_message_content?: InputMessageContent
}
/**
* Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.
* @see https://potato.im/api#inlinequeryresultgif
*/
export interface InlineQueryResultGif {
/** Type of the result, must be gif */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid URL for the GIF file. File size must not exceed 1MB */
gif_url?: string
/** Optional. Width of the GIF */
gif_width?: Integer
/** Optional. Height of the GIF */
gif_height?: Integer
/** Optional. Duration of the GIF in seconds */
gif_duration?: Integer
/** URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result */
thumb_url?: string
/** Optional. MIME type of the thumbnail, must be one of "image/jpeg", "image/gif", or "video/mp4". Defaults to "image/jpeg" */
thumb_mime_type?: string
/** Optional. Title for the result */
title?: string
/** Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the GIF animation */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.
* @see https://potato.im/api#inlinequeryresultmpeg4gif
*/
export interface InlineQueryResultMpeg4Gif {
/** Type of the result, must be mpeg4_gif */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid URL for the MP4 file. File size must not exceed 1MB */
mpeg4_url?: string
/** Optional. Video width */
mpeg4_width?: Integer
/** Optional. Video height */
mpeg4_height?: Integer
/** Optional. Video duration in seconds */
mpeg4_duration?: Integer
/** URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result */
thumb_url?: string
/** Optional. MIME type of the thumbnail, must be one of "image/jpeg", "image/gif", or "video/mp4". Defaults to "image/jpeg" */
thumb_mime_type?: string
/** Optional. Title for the result */
title?: string
/** Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the video animation */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.
* If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you must replace its content using input_message_content.
* @see https://potato.im/api#inlinequeryresultvideo
*/
export interface InlineQueryResultVideo {
/** Type of the result, must be video */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid URL for the embedded video player or video file */
video_url?: string
/** Mime type of the content of video url, "text/html" or "video/mp4" */
mime_type?: string
/** URL of the thumbnail (JPEG only) for the video */
thumb_url?: string
/** Title for the result */
title?: string
/** Optional. Caption of the video to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the video caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Video width */
video_width?: Integer
/** Optional. Video height */
video_height?: Integer
/** Optional. Video duration in seconds */
video_duration?: Integer
/** Optional. Short description of the result */
description?: string
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the video. This field is required if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video). */
input_message_content?: InputMessageContent
}
/**
* Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
* @see https://potato.im/api#inlinequeryresultaudio
*/
export interface InlineQueryResultAudio {
/** Type of the result, must be audio */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid URL for the audio file */
audio_url?: string
/** Title */
title?: string
/** Optional. Caption, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the audio caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Performer */
performer?: string
/** Optional. Audio duration in seconds */
audio_duration?: Integer
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the audio */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the the voice message.
* @see https://potato.im/api#inlinequeryresultvoice
*/
export interface InlineQueryResultVoice {
/** Type of the result, must be voice */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid URL for the voice recording */
voice_url?: string
/** Recording title */
title?: string
/** Optional. Caption, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the voice message caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Recording duration in seconds */
voice_duration?: Integer
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the voice recording */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Currently, only .PDF and .ZIP files can be sent using this method.
* @see https://potato.im/api#inlinequeryresultdocument
*/
export interface InlineQueryResultDocument {
/** Type of the result, must be document */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** Title for the result */
title?: string
/** Optional. Caption of the document to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the document caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** A valid URL for the file */
document_url?: string
/** Mime type of the content of the file, either "application/pdf" or "application/zip" */
mime_type?: string
/** Optional. Short description of the result */
description?: string
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the file */
input_message_content?: InputMessageContent
/** Optional. URL of the thumbnail (JPEG only) for the file */
thumb_url?: string
/** Optional. Thumbnail width */
thumb_width?: Integer
/** Optional. Thumbnail height */
thumb_height?: Integer
}
/**
* Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the location.
* @see https://potato.im/api#inlinequeryresultlocation
*/
export interface InlineQueryResultLocation {
/** Type of the result, must be location */
type?: string
/** Unique identifier for this result, 1-64 Bytes */
id?: string
/** Location latitude in degrees */
latitude?: Float
/** Location longitude in degrees */
longitude?: Float
/** Location title */
title?: string
/** Optional. The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: Float
/** Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. */
live_period?: Integer
/** Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */
heading?: Integer
/** Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */
proximity_alert_radius?: Integer
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the location */
input_message_content?: InputMessageContent
/** Optional. Url of the thumbnail for the result */
thumb_url?: string
/** Optional. Thumbnail width */
thumb_width?: Integer
/** Optional. Thumbnail height */
thumb_height?: Integer
}
/**
* Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.
* @see https://potato.im/api#inlinequeryresultvenue
*/
export interface InlineQueryResultVenue {
/** Type of the result, must be venue */
type?: string
/** Unique identifier for this result, 1-64 Bytes */
id?: string
/** Latitude of the venue location in degrees */
latitude?: Float
/** Longitude of the venue location in degrees */
longitude?: Float
/** Title of the venue */
title?: string
/** Address of the venue */
address?: string
/** Optional. Foursquare identifier of the venue if known */
foursquare_id?: string
/** Optional. Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) */
foursquare_type?: string
/** Optional. Google Places identifier of the venue */
google_place_id?: string
/** Optional. Google Places type of the venue. (See supported types.) */
google_place_type?: string
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the venue */
input_message_content?: InputMessageContent
/** Optional. Url of the thumbnail for the result */
thumb_url?: string
/** Optional. Thumbnail width */
thumb_width?: Integer
/** Optional. Thumbnail height */
thumb_height?: Integer
}
/**
* Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the contact.
* @see https://potato.im/api#inlinequeryresultcontact
*/
export interface InlineQueryResultContact {
/** Type of the result, must be contact */
type?: string
/** Unique identifier for this result, 1-64 Bytes */
id?: string
/** Contact's phone number */
phone_number?: string
/** Contact's first name */
first_name?: string
/** Optional. Contact's last name */
last_name?: string
/** Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes */
vcard?: string
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the contact */
input_message_content?: InputMessageContent
/** Optional. Url of the thumbnail for the result */
thumb_url?: string
/** Optional. Thumbnail width */
thumb_width?: Integer
/** Optional. Thumbnail height */
thumb_height?: Integer
}
/**
* Represents a Game.
* @see https://potato.im/api#inlinequeryresultgame
*/
export interface InlineQueryResultGame {
/** Type of the result, must be game */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** Short name of the game */
game_short_name?: string
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
}
/**
* Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the photo.
* @see https://potato.im/api#inlinequeryresultcachedphoto
*/
export interface InlineQueryResultCachedPhoto {
/** Type of the result, must be photo */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier of the photo */
photo_file_id?: string
/** Optional. Title for the result */
title?: string
/** Optional. Short description of the result */
description?: string
/** Optional. Caption of the photo to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the photo caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the photo */
input_message_content?: InputMessageContent
}
/**
* Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with specified content instead of the animation.
* @see https://potato.im/api#inlinequeryresultcachedgif
*/
export interface InlineQueryResultCachedGif {
/** Type of the result, must be gif */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier for the GIF file */
gif_file_id?: string
/** Optional. Title for the result */
title?: string
/** Optional. Caption of the GIF file to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the GIF animation */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the animation.
* @see https://potato.im/api#inlinequeryresultcachedmpeg4gif
*/
export interface InlineQueryResultCachedMpeg4Gif {
/** Type of the result, must be mpeg4_gif */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier for the MP4 file */
mpeg4_file_id?: string
/** Optional. Title for the result */
title?: string
/** Optional. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the video animation */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the sticker.
* @see https://potato.im/api#inlinequeryresultcachedsticker
*/
export interface InlineQueryResultCachedSticker {
/** Type of the result, must be sticker */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier of the sticker */
sticker_file_id?: string
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the sticker */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file.
* @see https://potato.im/api#inlinequeryresultcacheddocument
*/
export interface InlineQueryResultCachedDocument {
/** Type of the result, must be document */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** Title for the result */
title?: string
/** A valid file identifier for the file */
document_file_id?: string
/** Optional. Short description of the result */
description?: string
/** Optional. Caption of the document to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the document caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the file */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the video.
* @see https://potato.im/api#inlinequeryresultcachedvideo
*/
export interface InlineQueryResultCachedVideo {
/** Type of the result, must be video */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier for the video file */
video_file_id?: string
/** Title for the result */
title?: string
/** Optional. Short description of the result */
description?: string
/** Optional. Caption of the video to be sent, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the video caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the video */
input_message_content?: InputMessageContent
}
/**
* Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the voice message.
* @see https://potato.im/api#inlinequeryresultcachedvoice
*/
export interface InlineQueryResultCachedVoice {
/** Type of the result, must be voice */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier for the voice message */
voice_file_id?: string
/** Voice message title */
title?: string
/** Optional. Caption, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the voice message caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the voice message */
input_message_content?: InputMessageContent
}
/**
* Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
* @see https://potato.im/api#inlinequeryresultcachedaudio
*/
export interface InlineQueryResultCachedAudio {
/** Type of the result, must be audio */
type?: string
/** Unique identifier for this result, 1-64 bytes */
id?: string
/** A valid file identifier for the audio file */
audio_file_id?: string
/** Optional. Caption, 0-1024 characters after entities parsing */
caption?: string
/** Optional. Mode for parsing entities in the audio caption. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode */
caption_entities?: MessageEntity[]
/** Optional. Inline keyboard attached to the message */
reply_markup?: InlineKeyboardMarkup
/** Optional. Content of the message to be sent instead of the audio */
input_message_content?: InputMessageContent
}
/**
* This object represents the content of a message to be sent as a result of an inline query.
* Telegram clients currently support the following 5 types:
* - InputTextMessageContent
* - InputLocationMessageContent
* - InputVenueMessageContent
* - InputContactMessageContent
* - InputInvoiceMessageContent
* @see https://potato.im/api#inputmessagecontent
*/
export type InputMessageContent =
| InputTextMessageContent
| InputLocationMessageContent
| InputVenueMessageContent
| InputContactMessageContent
| InputInvoiceMessageContent
/**
* Represents the content of a text message to be sent as the result of an inline query.
* @see https://potato.im/api#inputtextmessagecontent
*/
export interface InputTextMessageContent {
/** Text of the message to be sent, 1-4096 characters */
message_text?: string
/** Optional. Mode for parsing entities in the message text. See formatting options for more details. */
parse_mode?: string
/** Optional. List of special entities that appear in message text, which can be specified instead of parse_mode */
entities?: MessageEntity[]
/** Optional. Disables link previews for links in the sent message */
disable_web_page_preview?: boolean
}
/**
* Represents the content of a location message to be sent as the result of an inline query.
* @see https://potato.im/api#inputlocationmessagecontent
*/
export interface InputLocationMessageContent {
/** Latitude of the location in degrees */
latitude?: Float
/** Longitude of the location in degrees */
longitude?: Float
/** Optional. The radius of uncertainty for the location, measured in meters; 0-1500 */
horizontal_accuracy?: Float
/** Optional. Period in seconds for which the location can be updated, should be between 60 and 86400. */
live_period?: Integer
/** Optional. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. */
heading?: Integer
/** Optional. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. */
proximity_alert_radius?: Integer
}
/**
* Represents the content of a venue message to be sent as the result of an inline query.
* @see https://potato.im/api#inputvenuemessagecontent
*/
export interface InputVenueMessageContent {
/** Latitude of the venue in degrees */
latitude?: Float
/** Longitude of the venue in degrees */
longitude?: Float
/** Name of the venue */
title?: string
/** Address of the venue */
address?: string
/** Optional. Foursquare identifier of the venue, if known */
foursquare_id?: string
/** Optional. Foursquare type of the venue, if known. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".) */
foursquare_type?: string
/** Optional. Google Places identifier of the venue */
google_place_id?: string
/** Optional. Google Places type of the venue. (See supported types.) */
google_place_type?: string
}
/**
* Represents the content of a contact message to be sent as the result of an inline query.
* @see https://potato.im/api#inputcontactmessagecontent
*/
export interface InputContactMessageContent {
/** Contact's phone number */
phone_number?: string
/** Contact's first name */
first_name?: string
/** Optional. Contact's last name */
last_name?: string
/** Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes */
vcard?: string
}
/**
* Represents the content of an invoice message to be sent as the result of an inline query.
* @see https://potato.im/api#inputinvoicemessagecontent
*/
export interface InputInvoiceMessageContent {
/** Product name, 1-32 characters */
title?: string
/** Product description, 1-255 characters */
description?: string
/** Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. */
payload?: string
/** Payment provider token, obtained via Botfather */
provider_token?: string
/** Three-letter ISO 4217 currency code, see more on currencies */
currency?: string
/** Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) */
prices?: LabeledPrice[]
/** Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 */
max_tip_amount?: Integer
/** Optional. A JSON-serialized array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. */
suggested_tip_amounts?: Integer[]
/** Optional. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider. */
provider_data?: string
/** Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. */
photo_url?: string
/** Optional. Photo size */
photo_size?: Integer
/** Optional. Photo width */
photo_width?: Integer
/** Optional. Photo height */
photo_height?: Integer
/** Optional. Pass True, if you require the user's full name to complete the order */
need_name?: boolean
/** Optional. Pass True, if you require the user's phone number to complete the order */
need_phone_number?: boolean
/** Optional. Pass True, if you require the user's email address to complete the order */
need_email?: boolean
/** Optional. Pass True, if you require the user's shipping address to complete the order */
need_shipping_address?: boolean
/** Optional. Pass True, if user's phone number should be sent to provider */
send_phone_number_to_provider?: boolean
/** Optional. Pass True, if user's email address should be sent to provider */
send_email_to_provider?: boolean
/** Optional. Pass True, if the final price depends on the shipping method */
is_flexible?: boolean
}
/**
* Represents a result of an inline query that was chosen by the user and sent to their chat partner.
* @see https://potato.im/api#choseninlineresult
*/
export interface ChosenInlineResult {
/** The unique identifier for the result that was chosen */
result_id?: string
/** The user that chose the result */
from?: User
/** Optional. Sender location, only for bots that require user location */
location?: Location
/** Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. */
inline_message_id?: string
/** The query that was used to obtain the result */
query?: string
}
export interface AnswerWebAppQueryPayload {
/** Unique identifier for the query to be answered */
web_app_query_id: string
/** A JSON-serialized object describing the message to be sent */
result: InlineQueryResult
}
/**
* Describes an inline message sent by a Web App on behalf of a user.
* @see https://potato.im/api#sentwebappmessage
*/
export interface SentWebAppMessage {
/** Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. */
inline_message_id?: string
}
declare module './update' {
interface Update {
/** Optional. New incoming inline query */
inline_query?: InlineQuery
/** Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. */
chosen_inline_result?: ChosenInlineResult
}
}
declare module './internal' {
interface Internal {
/**
* Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.
* @see https://potato.im/api#answerinlinequery
*/
answerInlineQuery(payload: AnswerInlineQueryPayload): Promise<boolean>
/**
* Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
* @see https://potato.im/api#answerwebappquery
*/
answerWebAppQuery(payload: AnswerWebAppQueryPayload): Promise<SentWebAppMessage>
}
}
Internal.define('answerInlineQuery')
Internal.define('answerWebAppQuery')

37
src/types/internal.ts

@ -0,0 +1,37 @@ @@ -0,0 +1,37 @@
import FormData from 'form-data'
import { Quester } from '@satorijs/satori'
import Logger from 'reggol'
export interface Internal {}
const logger = new Logger('potato')
export class Internal {
constructor(public http: Quester) {}
static define(method: string) {
Internal.prototype[method] = async function (this: Internal, data = {}) {
logger.debug('[request] %s %o', method, data)
try {
let response: any
if (data instanceof FormData) {
response = await this.http.post('/' + method, data, {
headers: data.getHeaders(),
})
} else {
response = await this.http.post('/' + method, data)
}
logger.debug('[response] %o', response)
const { ok, result } = response
if (ok) return result
throw new Error(`Telegram API error ${response.data.error_code}. ${response.data.description}`)
} catch (err) {
if (err.response?.data?.error_code && err.response.data.description) {
throw new Error(`Telegram API error ${err.response.data.error_code}. ${err.response.data.description}`)
} else {
throw err
}
}
}
}
}

256
src/types/passport.ts

@ -0,0 +1,256 @@ @@ -0,0 +1,256 @@
import { Integer, Internal } from '.'
/**
* Contains information about Telegram Passport data shared with the bot by the user.
* @see https://potato.im/api#passportdata
*/
export interface PassportData {
/** Array with information about documents and other Telegram Passport elements that was shared with the bot */
data?: EncryptedPassportElement[]
/** Encrypted credentials required to decrypt the data */
credentials?: EncryptedCredentials
}
/**
* This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB.
* @see https://potato.im/api#passportfile
*/
export interface PassportFile {
/** Identifier for this file, which can be used to download or reuse the file */
file_id?: string
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id?: string
/** File size in bytes */
file_size?: Integer
/** Unix time when the file was uploaded */
file_date?: Integer
}
/**
* Contains information about documents or other Telegram Passport elements shared with the bot by the user.
* @see https://potato.im/api#encryptedpassportelement
*/
export interface EncryptedPassportElement {
/** Element type. One of "personal_details", "passport", "driver_license", "identity_card", "internal_passport", "address", "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration", "phone_number", "email". */
type?: string
/** Optional. Base64-encoded encrypted Telegram Passport element data provided by the user, available for "personal_details", "passport", "driver_license", "identity_card", "internal_passport" and "address" types. Can be decrypted and verified using the accompanying EncryptedCredentials. */
data?: string
/** Optional. User's verified phone number, available only for "phone_number" type */
phone_number?: string
/** Optional. User's verified email address, available only for "email" type */
email?: string
/** Optional. encrypted files with documents provided by the user, available for "utility_bill", "bank_statement", "rental_agreement", "passport_registration" and "temporary_registration" types. Files can be decrypted and verified using the accompanying EncryptedCredentials. */
files?: PassportFile[]
/** Optional. Encrypted file with the front side of the document, provided by the user. Available for "passport", "driver_license", "identity_card" and "internal_passport". The file can be decrypted and verified using the accompanying EncryptedCredentials. */
front_side?: PassportFile
/** Optional. Encrypted file with the reverse side of the document, provided by the user. Available for "driver_license" and "identity_card". The file can be decrypted and verified using the accompanying EncryptedCredentials. */
reverse_side?: PassportFile
/** Optional. Encrypted file with the selfie of the user holding a document, provided by the user; available for "passport", "driver_license", "identity_card" and "internal_passport". The file can be decrypted and verified using the accompanying EncryptedCredentials. */
selfie?: PassportFile
/** Optional. encrypted files with translated versions of documents provided by the user. Available if requested for "passport", "driver_license", "identity_card", "internal_passport", "utility_bill", "bank_statement", "rental_agreement", "passport_registration" and "temporary_registration" types. Files can be decrypted and verified using the accompanying EncryptedCredentials. */
translation?: PassportFile[]
/** Base64-encoded element hash for using in PassportElementErrorUnspecified */
hash?: string
}
/**
* Contains data required for decrypting and authenticating EncryptedPassportElement. See the Telegram Passport Documentation for a complete description of the data decryption and authentication processes.
* @see https://potato.im/api#encryptedcredentials
*/
export interface EncryptedCredentials {
/** Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for EncryptedPassportElement decryption and authentication */
data?: string
/** Base64-encoded data hash for data authentication */
hash?: string
/** Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption */
secret?: string
}
export interface SetPassportDataErrorsPayload {
/** User identifier */
user_id?: Integer
/** A JSON-serialized array describing the errors */
errors?: PassportElementError[]
}
/**
* This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of:
* - PassportElementErrorDataField
* - PassportElementErrorFrontSide
* - PassportElementErrorReverseSide
* - PassportElementErrorSelfie
* - PassportElementErrorFile
* - PassportElementErrorFiles
* - PassportElementErrorTranslationFile
* - PassportElementErrorTranslationFiles
* - PassportElementErrorUnspecified
* @see https://potato.im/api#passportelementerror
*/
export type PassportElementError =
| PassportElementErrorDataField
| PassportElementErrorFrontSide
| PassportElementErrorReverseSide
| PassportElementErrorSelfie
| PassportElementErrorFile
| PassportElementErrorFiles
| PassportElementErrorTranslationFile
| PassportElementErrorTranslationFiles
| PassportElementErrorUnspecified
/**
* Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes.
* @see https://potato.im/api#passportelementerrordatafield
*/
export interface PassportElementErrorDataField {
/** Error source, must be data */
source?: string
/** The section of the user's Telegram Passport which has the error, one of "personal_details", "passport", "driver_license", "identity_card", "internal_passport", "address" */
type?: string
/** Name of the data field which has the error */
field_name?: string
/** Base64-encoded data hash */
data_hash?: string
/** Error message */
message?: string
}
/**
* Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes.
* @see https://potato.im/api#passportelementerrorfrontside
*/
export interface PassportElementErrorFrontSide {
/** Error source, must be front_side */
source?: string
/** The section of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport" */
type?: string
/** Base64-encoded hash of the file with the front side of the document */
file_hash?: string
/** Error message */
message?: string
}
/**
* Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes.
* @see https://potato.im/api#passportelementerrorreverseside
*/
export interface PassportElementErrorReverseSide {
/** Error source, must be reverse_side */
source?: string
/** The section of the user's Telegram Passport which has the issue, one of "driver_license", "identity_card" */
type?: string
/** Base64-encoded hash of the file with the reverse side of the document */
file_hash?: string
/** Error message */
message?: string
}
/**
* Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes.
* @see https://potato.im/api#passportelementerrorselfie
*/
export interface PassportElementErrorSelfie {
/** Error source, must be selfie */
source?: string
/** The section of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport" */
type?: string
/** Base64-encoded hash of the file with the selfie */
file_hash?: string
/** Error message */
message?: string
}
/**
* Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes.
* @see https://potato.im/api#passportelementerrorfile
*/
export interface PassportElementErrorFile {
/** Error source, must be file */
source?: string
/** The section of the user's Telegram Passport which has the issue, one of "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" */
type?: string
/** Base64-encoded file hash */
file_hash?: string
/** Error message */
message?: string
}
/**
* Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes.
* @see https://potato.im/api#passportelementerrorfiles
*/
export interface PassportElementErrorFiles {
/** Error source, must be files */
source?: string
/** The section of the user's Telegram Passport which has the issue, one of "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" */
type?: string
/** List of base64-encoded file hashes */
file_hashes?: string[]
/** Error message */
message?: string
}
/**
* Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes.
* @see https://potato.im/api#passportelementerrortranslationfile
*/
export interface PassportElementErrorTranslationFile {
/** Error source, must be translation_file */
source?: string
/** Type of element of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport", "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" */
type?: string
/** Base64-encoded file hash */
file_hash?: string
/** Error message */
message?: string
}
/**
* Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change.
* @see https://potato.im/api#passportelementerrortranslationfiles
*/
export interface PassportElementErrorTranslationFiles {
/** Error source, must be translation_files */
source?: string
/** Type of element of the user's Telegram Passport which has the issue, one of "passport", "driver_license", "identity_card", "internal_passport", "utility_bill", "bank_statement", "rental_agreement", "passport_registration", "temporary_registration" */
type?: string
/** List of base64-encoded file hashes */
file_hashes?: string[]
/** Error message */
message?: string
}
/**
* Represents an issue in an unspecified place. The error is considered resolved when new data is added.
* @see https://potato.im/api#passportelementerrorunspecified
*/
export interface PassportElementErrorUnspecified {
/** Error source, must be unspecified */
source?: string
/** Type of element of the user's Telegram Passport which has the issue */
type?: string
/** Base64-encoded element hash */
element_hash?: string
/** Error message */
message?: string
}
declare module '.' {
interface Message {
/** Optional. Telegram Passport data */
passport_data?: PassportData
}
}
declare module './internal' {
interface Internal {
/**
* Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
*
* Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
* @see https://potato.im/api#setpassportdataerrors
*/
setPassportDataErrors(payload: SetPassportDataErrorsPayload): Promise<boolean>
}
}
Internal.define('setPassportDataErrors')

304
src/types/payment.ts

@ -0,0 +1,304 @@ @@ -0,0 +1,304 @@
import { InlineKeyboardMarkup, Integer, Internal, Message, User } from '.'
export interface SendInvoicePayload {
/** Unique identifier for the target chat or username of the target channel (in the format @channelusername) */
chat_id?: Integer | string
/** Unique identifier for the target message thread (topic) of the forum; for forum supergroups only */
message_thread_id?: number
/** Product name, 1-32 characters */
title?: string
/** Product description, 1-255 characters */
description?: string
/** Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. */
payload?: string
/** Payments provider token, obtained via Botfather */
provider_token?: string
/** Three-letter ISO 4217 currency code, see more on currencies */
currency?: string
/** Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) */
prices?: LabeledPrice[]
/** The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 */
max_tip_amount?: Integer
/** A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. */
suggested_tip_amounts?: Integer[]
/** Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter */
start_parameter?: string
/** A JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. */
provider_data?: string
/** URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. */
photo_url?: string
/** Photo size */
photo_size?: Integer
/** Photo width */
photo_width?: Integer
/** Photo height */
photo_height?: Integer
/** Pass True, if you require the user's full name to complete the order */
need_name?: boolean
/** Pass True, if you require the user's phone number to complete the order */
need_phone_number?: boolean
/** Pass True, if you require the user's email address to complete the order */
need_email?: boolean
/** Pass True, if you require the user's shipping address to complete the order */
need_shipping_address?: boolean
/** Pass True, if user's phone number should be sent to provider */
send_phone_number_to_provider?: boolean
/** Pass True, if user's email address should be sent to provider */
send_email_to_provider?: boolean
/** Pass True, if the final price depends on the shipping method */
is_flexible?: boolean
/** Sends the message silently. Users will receive a notification with no sound. */
disable_notification?: boolean
/** Protects the contents of the sent message from forwarding and saving */
protect_content?: boolean
/** If the message is a reply, ID of the original message */
reply_to_message_id?: Integer
/** Pass True, if the message should be sent even if the specified replied-to message is not found */
allow_sending_without_reply?: boolean
/** A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. */
reply_markup?: InlineKeyboardMarkup
}
export interface CreateInvoiceLinkPayload {
/** Product name, 1-32 characters */
title: string
/** Product description, 1-255 characters */
description: string
/** Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. */
payload: string
/** Payment provider token, obtained via BotFather */
provider_token: string
/** Three-letter ISO 4217 currency code, see more on currencies */
currency: string
/** Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) */
prices: LabeledPrice[]
/** The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 */
max_tip_amount?: number
/** A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. */
suggested_tip_amounts?: number[]
/** JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. */
provider_data?: string
/** URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. */
photo_url?: string
/** Photo size in bytes */
photo_size?: number
/** Photo width */
photo_width?: number
/** Photo height */
photo_height?: number
/** Pass True if you require the user's full name to complete the order */
need_name?: boolean
/** Pass True if you require the user's phone number to complete the order */
need_phone_number?: boolean
/** Pass True if you require the user's email address to complete the order */
need_email?: boolean
/** Pass True if you require the user's shipping address to complete the order */
need_shipping_address?: boolean
/** Pass True if the user's phone number should be sent to the provider */
send_phone_number_to_provider?: boolean
/** Pass True if the user's email address should be sent to the provider */
send_email_to_provider?: boolean
/** Pass True if the final price depends on the shipping method */
is_flexible?: boolean
}
export interface AnswerShippingQueryPayload {
/** Unique identifier for the query to be answered */
shipping_query_id?: string
/** Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) */
ok?: boolean
/** Required if ok is True. A JSON-serialized array of available shipping options. */
shipping_options?: ShippingOption[]
/** Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. */
error_message?: string
}
export interface AnswerPreCheckoutQueryPayload {
/** Unique identifier for the query to be answered */
pre_checkout_query_id?: string
/** Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. */
ok?: boolean
/** Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. */
error_message?: string
}
/**
* This object represents a portion of the price for goods or services.
* @see https://potato.im/api#labeledprice
*/
export interface LabeledPrice {
/** Portion label */
label?: string
/** Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
amount?: Integer
}
/**
* This object contains basic information about an invoice.
* @see https://potato.im/api#invoice
*/
export interface Invoice {
/** Product name */
title?: string
/** Product description */
description?: string
/** Unique bot deep-linking parameter that can be used to generate this invoice */
start_parameter?: string
/** Three-letter ISO 4217 currency code */
currency?: string
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount?: Integer
}
/**
* This object represents a shipping address.
* @see https://potato.im/api#shippingaddress
*/
export interface ShippingAddress {
/** ISO 3166-1 alpha-2 country code */
country_code?: string
/** State, if applicable */
state?: string
/** City */
city?: string
/** First line for the address */
street_line1?: string
/** Second line for the address */
street_line2?: string
/** Address post code */
post_code?: string
}
/**
* This object represents information about an order.
* @see https://potato.im/api#orderinfo
*/
export interface OrderInfo {
/** Optional. User name */
name?: string
/** Optional. User's phone number */
phone_number?: string
/** Optional. User email */
email?: string
/** Optional. User shipping address */
shipping_address?: ShippingAddress
}
/**
* This object represents one shipping option.
* @see https://potato.im/api#shippingoption
*/
export interface ShippingOption {
/** Shipping option identifier */
id?: string
/** Option title */
title?: string
/** List of price portions */
prices?: LabeledPrice[]
}
/**
* This object contains basic information about a successful payment.
* @see https://potato.im/api#successfulpayment
*/
export interface SuccessfulPayment {
/** Three-letter ISO 4217 currency code */
currency?: string
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount?: Integer
/** Bot specified invoice payload */
invoice_payload?: string
/** Optional. Identifier of the shipping option chosen by the user */
shipping_option_id?: string
/** Optional. Order info provided by the user */
order_info?: OrderInfo
/** Telegram payment identifier */
telegram_payment_charge_id?: string
/** Provider payment identifier */
provider_payment_charge_id?: string
}
/**
* This object contains information about an incoming shipping query.
* @see https://potato.im/api#shippingquery
*/
export interface ShippingQuery {
/** Unique query identifier */
id?: string
/** User who sent the query */
from?: User
/** Bot specified invoice payload */
invoice_payload?: string
/** User specified shipping address */
shipping_address?: ShippingAddress
}
/**
* This object contains information about an incoming pre-checkout query.
* @see https://potato.im/api#precheckoutquery
*/
export interface PreCheckoutQuery {
/** Unique query identifier */
id?: string
/** User who sent the query */
from?: User
/** Three-letter ISO 4217 currency code */
currency?: string
/** Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). */
total_amount?: Integer
/** Bot specified invoice payload */
invoice_payload?: string
/** Optional. Identifier of the shipping option chosen by the user */
shipping_option_id?: string
/** Optional. Order info provided by the user */
order_info?: OrderInfo
}
declare module '.' {
interface Message {
/** Optional. Message is an invoice for a payment, information about the invoice. More about payments » */
invoice?: Invoice
/** Optional. Message is a service message about a successful payment, information about the payment. More about payments » */
successful_payment?: SuccessfulPayment
}
}
declare module './update' {
interface Update {
/** Optional. New incoming shipping query. Only for invoices with flexible price */
shipping_query?: ShippingQuery
/** Optional. New incoming pre-checkout query. Contains full information about checkout */
pre_checkout_query?: PreCheckoutQuery
}
}
declare module './internal' {
interface Internal {
/**
* Use this method to send invoices. On success, the sent Message is returned.
* @see https://potato.im/api#sendinvoice
*/
sendInvoice(payload: SendInvoicePayload): Promise<Message>
/**
* Use this method to create a link for an invoice. Returns the created invoice link as String on success.
* @see https://potato.im/api#createinvoicelink
*/
createInvoiceLink(payload: CreateInvoiceLinkPayload): Promise<string>
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
* @see https://potato.im/api#answershippingquery
*/
answerShippingQuery(payload: AnswerShippingQueryPayload): Promise<boolean>
/**
* Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned.
* Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
* @see https://potato.im/api#answerprecheckoutquery
*/
answerPreCheckoutQuery(payload: AnswerPreCheckoutQueryPayload): Promise<boolean>
}
}
Internal.define('sendInvoice')
Internal.define('createInvoiceLink')
Internal.define('answerShippingQuery')
Internal.define('answerPreCheckoutQuery')

242
src/types/sticker.ts

@ -0,0 +1,242 @@ @@ -0,0 +1,242 @@
import { File, Float, ForceReply, InlineKeyboardMarkup, InputFile, Integer, Internal, Message, PhotoSize, ReplyKeyboardMarkup, ReplyKeyboardRemove } from '.'
/**
* This object represents a sticker.
* @see https://potato.im/api#sticker
*/
export interface Sticker {
/** Identifier for this file, which can be used to download or reuse the file */
file_id?: string
/** Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. */
file_unique_id?: string
/** Sticker width */
width?: Integer
/** Sticker height */
height?: Integer
/** True, if the sticker is animated */
is_animated?: boolean
/** True, if the sticker is a video sticker */
is_video?: boolean
/** Optional. Sticker thumbnail in the .WEBP or .JPG format */
thumb?: PhotoSize
/** Optional. Emoji associated with the sticker */
emoji?: string
/** Optional. Name of the sticker set to which the sticker belongs */
set_name?: string
/** Optional. For premium regular stickers, premium animation for the sticker */
premium_animation?: File
/** Optional. For mask stickers, the position where the mask should be placed */
mask_position?: MaskPosition
/** Optional. For custom emoji stickers, unique identifier of the custom emoji */
custom_emoji_id?: string
/** Optional. File size in bytes */
file_size?: Integer
}
/**
* This object represents a sticker set.
* @see https://potato.im/api#stickerset
*/
export interface StickerSet {
/** Sticker set name */
name?: string
/** Sticker set title */
title?: string
/** Type of stickers in the set, currently one of “regular”, “mask”, “custom_emoji” */
sticker_type: string
/** True, if the sticker set contains animated stickers */
is_animated?: boolean
/** True, if the sticker set contains video stickers */
is_video?: boolean
/**
* True, if the sticker set contains masks
* @deprecated
*/
contains_masks?: boolean
/** List of all set stickers */
stickers?: Sticker[]
/** Optional. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format */
thumb?: PhotoSize
}
/**
* This object describes the position on faces where a mask should be placed by default.
* @see https://potato.im/api#maskposition
*/
export interface MaskPosition {
/** The part of the face relative to which the mask should be placed. One of "forehead", "eyes", "mouth", or "chin". */
point?: string
/** Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position. */
x_shift?: Float
/** Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position. */
y_shift?: Float
/** Mask scaling coefficient. For example, 2.0 means double size. */
scale?: Float
}
export interface SendStickerPayload {
/** Unique identifier for the target chat or username of the target channel (in the format @channelusername) */
chat_id?: Integer | string
/** Unique identifier for the target message thread (topic) of the forum; for forum supergroups only */
message_thread_id?: number
/** Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » */
sticker?: InputFile | string
/** Sends the message silently. Users will receive a notification with no sound. */
disable_notification?: boolean
/** Protects the contents of the sent message from forwarding and saving */
protect_content?: boolean
/** If the message is a reply, ID of the original message */
reply_to_message_id?: Integer
/** Pass True, if the message should be sent even if the specified replied-to message is not found */
allow_sending_without_reply?: boolean
/** Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. */
reply_markup?: InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply
}
export interface GetStickerSetPayload {
/** Name of the sticker set */
name?: string
}
export interface GetCustomEmojiStickersPayload {
/** List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. */
custom_emoji_ids: string[]
}
export interface UploadStickerFilePayload {
/** User identifier of sticker file owner */
user_id?: Integer
/** PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files » */
png_sticker?: InputFile
}
export interface CreateNewStickerSetPayload {
/** User identifier of created sticker set owner */
user_id?: Integer
/** Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in "by<bot username>". <bot_username> is case insensitive. 1-64 characters. */
name?: string
/** Sticker set title, 1-64 characters */
title?: string
/** PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » */
png_sticker?: InputFile | string
/** TGS animation with the sticker, uploaded using multipart/form-data. See https://core.potato.org/stickers#animated-sticker-requirements for technical requirements */
tgs_sticker?: InputFile
/** WEBM video with the sticker, uploaded using multipart/form-data. See https://core.potato.org/stickers#video-sticker-requirements for technical requirements */
webm_sticker?: InputFile
/** Type of stickers in the set, pass “regular” or “mask”. Custom emoji sticker sets can't be created via the Bot API at the moment. By default, a regular sticker set is created. */
sticker_type?: string
/** One or more emoji corresponding to the sticker */
emojis?: string
/**
* Pass True, if a set of mask stickers should be created
* @deprecated
*/
contains_masks?: boolean
/** A JSON-serialized object for position where the mask should be placed on faces */
mask_position?: MaskPosition
}
export interface AddStickerToSetPayload {
/** User identifier of sticker set owner */
user_id?: Integer
/** Sticker set name */
name?: string
/** PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » */
png_sticker?: InputFile | string
/** TGS animation with the sticker, uploaded using multipart/form-data. See https://core.potato.org/stickers#animated-sticker-requirements for technical requirements */
tgs_sticker?: InputFile
/** WEBM video with the sticker, uploaded using multipart/form-data. See https://core.potato.org/stickers#video-sticker-requirements for technical requirements */
webm_sticker?: InputFile
/** One or more emoji corresponding to the sticker */
emojis?: string
/** A JSON-serialized object for position where the mask should be placed on faces */
mask_position?: MaskPosition
}
export interface SetStickerPositionInSetPayload {
/** File identifier of the sticker */
sticker?: string
/** New sticker position in the set, zero-based */
position?: Integer
}
export interface DeleteStickerFromSetPayload {
/** File identifier of the sticker */
sticker?: string
}
export interface SetStickerSetThumbPayload {
/** Sticker set name */
name?: string
/** User identifier of the sticker set owner */
user_id?: Integer
/** A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core.potato.org/stickers#animated-sticker-requirements for animated sticker technical requirements, or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.potato.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files ». Animated sticker set thumbnails can't be uploaded via HTTP URL. */
thumb?: InputFile | string
}
declare module '.' {
interface Message {
/** Optional. Message is a sticker, information about the sticker */
sticker?: Sticker
}
}
declare module './internal' {
interface Internal {
/**
* Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
* @see https://potato.im/api#sendsticker
*/
sendSticker(payload: SendStickerPayload): Promise<Message>
/**
* Use this method to get a sticker set. On success, a StickerSet object is returned.
* @see https://potato.im/api#getstickerset
*/
getStickerSet(payload: GetStickerSetPayload): Promise<StickerSet>
/**
* Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
* @see https://potato.im/api#getcustomemojistickers
*/
getCustomEmojiStickers(payload: GetCustomEmojiStickersPayload): Promise<Sticker[]>
/**
* Use this method to upload a .PNG file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
* @see https://potato.im/api#uploadstickerfile
*/
uploadStickerFile(payload: UploadStickerFilePayload): Promise<File>
/**
* Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Returns True on success.
* @see https://potato.im/api#createnewstickerset
*/
createNewStickerSet(payload: CreateNewStickerSetPayload): Promise<boolean>
/**
* Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.
* @see https://potato.im/api#addstickertoset
*/
addStickerToSet(payload: AddStickerToSetPayload): Promise<boolean>
/**
* Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
* @see https://potato.im/api#setstickerpositioninset
*/
setStickerPositionInSet(payload: SetStickerPositionInSetPayload): Promise<boolean>
/**
* Use this method to delete a sticker from a set created by the bot. Returns True on success.
* @see https://potato.im/api#deletestickerfromset
*/
deleteStickerFromSet(payload: DeleteStickerFromSetPayload): Promise<boolean>
/**
* Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only. Returns True on success.
* @see https://potato.im/api#setstickersetthumb
*/
setStickerSetThumb(payload: SetStickerSetThumbPayload): Promise<boolean>
}
}
Internal.define('sendSticker')
Internal.define('getStickerSet')
Internal.define('getCustomEmojiStickers')
Internal.define('uploadStickerFile')
Internal.define('createNewStickerSet')
Internal.define('addStickerToSet')
Internal.define('setStickerPositionInSet')
Internal.define('deleteStickerFromSet')
Internal.define('setStickerSetThumb')

107
src/types/update.ts

@ -0,0 +1,107 @@ @@ -0,0 +1,107 @@
import { InputFile, Integer, Internal } from '.'
/**
* This object represents an incoming update. At most one of the optional parameters can be present in any given update.
* @see https://potato.im/api#update
*/
export interface Update {
/** The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. */
update_id?: Integer
}
export interface GetUpdatesPayload {
/** Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten. */
offset?: Integer
/** Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. */
limit?: Integer
/** Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. */
timeout?: Integer
/**
* A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
* Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.
*/
allowed_updates?: string[]
}
export interface SetWebhookPayload {
/** HTTPS url to send updates to. Use an empty string to remove webhook integration */
url?: string
/** Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. */
certificate?: InputFile
/** The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS */
ip_address?: string
/** Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. */
max_connections?: Integer
/**
* A JSON-serialized list of the update types you want your bot to receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
*
* Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.
*/
allowed_updates?: string[]
/** Pass True to drop all pending updates */
drop_pending_updates?: boolean
/** A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. */
secret_token?: string
}
export interface DeleteWebhookPayload {
/** Pass True to drop all pending updates */
drop_pending_updates?: boolean
}
/**
* Contains information about the current status of a webhook.
* @see https://potato.im/api#webhookinfo
*/
export interface WebhookInfo {
/** Webhook URL, may be empty if webhook is not set up */
url?: string
/** True, if a custom certificate was provided for webhook certificate checks */
has_custom_certificate?: boolean
/** Number of updates awaiting delivery */
pending_update_count?: Integer
/** Optional. Currently used webhook IP address */
ip_address?: string
/** Optional. Unix time for the most recent error that happened when trying to deliver an update via webhook */
last_error_date?: Integer
/** Optional. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook */
last_error_message?: string
/** Optional. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters */
last_synchronization_error_date?: number
/** Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery */
max_connections?: Integer
/** Optional. A list of update types the bot is subscribed to. Defaults to all update types except chat_member */
allowed_updates?: string[]
}
declare module './internal' {
interface Internal {
/**
* Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
* @see https://potato.im/api#getupdates
*/
getUpdates(payload: GetUpdatesPayload): Promise<Update[]>
/**
* Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
*
* If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot's token, you can be pretty sure it's us.
* @see https://potato.im/api#setwebhook
*/
setWebhook(payload: SetWebhookPayload): Promise<boolean>
/**
* Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
* @see https://potato.im/api#deletewebhook
*/
deleteWebhook(payload: DeleteWebhookPayload): Promise<boolean>
/**
* Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
* @see https://potato.im/api#getwebhookinfo
*/
getWebhookInfo(): Promise<WebhookInfo>
}
}
Internal.define('getUpdates')
Internal.define('setWebhook')
Internal.define('deleteWebhook')
Internal.define('getWebhookInfo')

199
src/utils.ts

@ -0,0 +1,199 @@ @@ -0,0 +1,199 @@
import { Dict, h, Logger, Universal } from '@satorijs/satori'
import { PotatoBot } from './bot'
import * as Potato from './types'
export * from './types'
const logger = new Logger('potato')
export const decodeUser = (data: Potato.User): Universal.User => ({
id: data.id.toString(),
name: data.username,
nickname: data.first_name + (data.last_name ? ' ' + data.last_name : ''),
isBot: data.is_bot,
userId: data.id.toString(),
username: data.username,
})
export const decodeGuildMember = (data: Potato.ChatMember): Universal.GuildMember => ({
user: decodeUser(data.user),
title: data['custom_title'],
})
export async function handleUpdate(updates: Potato.Update, bot: PotatoBot) {
logger.debug('receive %s', JSON.stringify(updates))
// // Internal event: get update type from field name.
// const subtype = Object.keys(update).filter(v => v !== 'update_id')[0]
// if (subtype) {
// this.bot.dispatch(this.bot.session({
// type: 'internal',
// _type: `potato/${subtype.replace(/_/g, '-')}`,
// _data: update[subtype],
// }))
// }
let update = updates[0]
const session = bot.session()
session.setInternal('potato', update)
const message = update.message || update.edited_message || update.channel_post || update.edited_channel_post
const isBotCommand = update.message && update.message.entities?.[0].type === 'bot_command'
const code = update.lang// message?.from?.language_code
if (code) {
if (code === 'zh-hans') {
session.locales = ['zh-CN']
} else if (code === 'zh-hant') {
session.locales = ['zh-TW']
} else {
session.locales = [code.slice(0, 2)]
}
}
if (isBotCommand) {
session.type = 'interaction/command'
await decodeMessage(bot, message, session.event.message = {}, session.event)
session.content = session.content.slice(1)
} else if (message) {
session.type = update.message || update.channel_post ? 'message' : 'message-updated'
await decodeMessage(bot, message, session.event.message = {}, session.event)
} else if (update.chat_join_request) {
session.timestamp = update.chat_join_request.date * 1000
session.type = 'guild-member-request'
session.messageId = `${update.chat_join_request.chat.id}@${update.chat_join_request.from.id}`
// Potato join request does not have text
session.content = ''
session.channelId = update.chat_join_request.chat.id.toString()
session.guildId = session.channelId
} else if (update.my_chat_member) {
session.timestamp = update.my_chat_member.date * 1000
session.messageId = `${update.my_chat_member.chat.id}@${update.my_chat_member.from.id}`
session.content = ''
session.channelId = update.my_chat_member.chat.id.toString()
session.guildId = session.channelId
if (update.my_chat_member.old_chat_member.user.id.toString() === bot.selfId) {
if (update.my_chat_member.new_chat_member.status === 'left') {
session.type = 'group-deleted'
} else if (update.my_chat_member.old_chat_member.status === 'left') {
session.type = 'group-added'
}
}
}
bot.dispatch(session)
}
export async function decodeMessage(
bot: PotatoBot,
data: Potato.Message,
message: Universal.Message,
payload: Universal.MessageLike = message,
) {
const parseText = (text: string, entities: Potato.MessageEntity[]): h[] => {
let curr = 0
const segs: h[] = []
for (const e of entities) {
const eText = text.substr(e.offset, e.length)
if (e.type === 'mention') {
if (eText[0] !== '@') throw new Error('Potato mention does not start with @: ' + eText)
const atName = eText.slice(1)
if (eText === '@' + bot.user.name) {
segs.push(h('at', { id: bot.user.id, name: atName }))
} else {
// TODO handle @others
segs.push(h('text', { content: eText }))
}
} else if (e.type === 'text_mention') {
segs.push(h('at', { id: e.user.id }))
} else {
// TODO: bold, italic, underline, strikethrough, spoiler, code, pre,
// text_link, custom_emoji
segs.push(h('text', { content: eText }))
}
if (e.offset > curr) {
segs.splice(-1, 0, h('text', { content: text.slice(curr, e.offset) }))
}
curr = e.offset + e.length
}
if (curr < text?.length || 0) {
segs.push(h('text', { content: text.slice(curr) }))
}
return segs
}
const segments: h[] = []
// topic messages are reply chains, if a message is forum_topic_created, the session shoudn't have a quote.
if (data.reply_to_message && !(data.is_topic_message && data.reply_to_message.forum_topic_created)) {
await decodeMessage(bot, data.reply_to_message, message.quote = {}, null)
}
// make sure text comes first so that commands can be triggered
const msgText = data.text || data.caption
segments.push(...parseText(msgText, data.entities || []))
if (data.caption) {
// add a space to separate caption from media
segments.push(h('text', { content: ' ' }))
}
const addResource = async (type: string, data: Potato.Animation | Potato.Video | Potato.Document | Potato.Voice) => {
const attrs: Dict<string> = await bot.$getFileFromId(data.file_id)
if (data['file_name']) {
attrs.filename = data['file_name']
}
segments.push(h(type, attrs))
}
if (data.location) {
segments.push(h('location', { lat: data.location.latitude, lon: data.location.longitude }))
} else if (data.photo) {
const photo = data.photo.sort((s1, s2) => s2.file_size - s1.file_size)[0]
segments.push(h('image', await bot.$getFileFromId(photo.file_id)))
} else if (data.sticker) {
// TODO: Convert tgs to gif
// https://github.com/ed-asriyan/tgs-to-gif
// Currently use thumb only
try {
const file = await bot.internal.getFile({ file_id: data.sticker.file_id })
if (file.file_path.endsWith('.tgs')) {
throw new Error('tgs is not supported now')
}
segments.push(h('image', await bot.$getFileFromPath(file.file_path)))
} catch (e) {
logger.warn('get file error', e)
segments.push(h('text', { content: `[${data.sticker.set_name || 'sticker'} ${data.sticker.emoji || ''}]` }))
}
} else if (data.voice) {
await addResource('audio', data.voice)
} else if (data.animation) {
await addResource('image', data.animation)
} else if (data.video) {
await addResource('video', data.video)
} else if (data.document) {
await addResource('file', data.document)
}
message.elements = segments
message.content = segments.join('')
message.id = message.messageId = data.message_id.toString()
if (!payload) return
payload.timestamp = data.date * 1000
payload.user = decodeUser(data.from)
if (data.chat.type === 'private') {
payload.channel = {
id: data.chat.id.toString(),
type: Universal.Channel.Type.DIRECT,
}
} else {
payload.guild = {
id: data.chat.id.toString(),
name: data.chat.title,
}
payload.member = {}
payload.channel = {
id: data.is_topic_message
? data.message_thread_id.toString()
: data.chat.id.toString(),
type: Universal.Channel.Type.TEXT,
}
}
}

19
tsconfig.json

@ -0,0 +1,19 @@ @@ -0,0 +1,19 @@
{
"compilerOptions": {
"rootDir": "src",
"outDir": "lib",
"target": "es2022",
"module": "commonjs",
"declaration": true,
"composite": true,
"incremental": true,
"skipLibCheck": true,
"esModuleInterop": true,
"moduleResolution": "node",
"jsx": "react-jsx",
"jsxImportSource": "@satorijs/element",
},
"include": [
"src",
],
}
Loading…
Cancel
Save