Giter Club home page Giter Club logo

typegram's Introduction

Types for the Telegram Bot API

Please consider contributing to @grammyjs/types instead. typegram is legacy and will not be updated directly anymore. Instead, @grammyjs/types is maintained and kept in sync with the Bot API specification. Changes are backported to typegram periodically to keep older projects running.

This project provides TypeScript types for the entire Telegram Bot API in version 6.8.

It contains zero bytes of executable code.

Installation

npm install --save-dev typegram

Available Types

Generally, this package just exposes a huge load of interfaces that correspond to the types used throughout the Telegram Bot API.

Note that the API specification sometimes only has one name for multiple variants of a type, e.g. there are a number of different Updates you can receive, but they're all just called Update. This package represents such types as large unions of all possible options of what an Update could be, such that type narrowing can work as expected on your side. If you need to access the individual variants of an Update, refer to Update.MessageUpdate and its siblings.

In fact, this pattern is used for various types, namely:

  • CallbackQuery
  • Chat
  • ChatFromGetChat
  • InlineKeyboardButton
  • KeyboardButton
  • Message
  • MessageEntity
  • Location
  • Update

(Naturally, when the API specification is actually modelling types to be unions (e.g. InlineQueryResult), this is reflected here as a union type, too.)

Using API Response Objects

The Telegram Bot API does not return just the requested data in the body of the response objects.

Instead, they are wrapped inside an object that has an ok: boolean status flag, indicating success or failure of the preceding API request. This outer object is modelled in typegram by the ApiResponse type.

Customizing InputFile and accessing API methods

The Telegram Bot API lets bots send files in three different ways. Two of those ways are by specifying a string—either a file_id or a URL. The third option, however, is by uploading files to the server using multipart/form-data.

The first two means to send a file are already covered by the type annotations across the library. In all places where a file_id or a URL is permitted, the corresponding property allows a string.

We will now look at the type declarations that are relevant for uploading files directly. Depending on the code you're using the typegram types for, you may want to support different ways to specify the file to be uploaded. As an example, you may want to be able to make calls to sendDocument with an object that conforms to { path: string } in order to specify the location of a local file. (Your code is then assumed to able to translate calls to sendDocument and the like to multipart/form-data uploads when supplied with an object alike { path: '/tmp/file.txt' } in the document property of the argument object.)

typegram cannot possibly know what objects you want to support as InputFiles.

However, you can specify your own version of what an InputFile is throughout all affected methods and interfaces.

For instance, let's stick with our example and say that you want to support InputFiles of the following type.

interface MyInputFile {
  path: string;
}

You can then customize typegram to fit your needs by passing your custom InputFile to the ApiMethods type.

import * as Typegram from "typegram";

type API = Typegram.ApiMethods<MyInputFile>;

You can now access all types that must respect MyInputFile through the API type:

// The utility types `Opts` and `Ret`:
type Opts<M extends keyof API> = Typegram.Opts<MyInputFile>[M];
type Ret<M extends keyof API> = Typegram.Ret<MyInputFile>[M];

Each method takes just a single argument with a structure that corresponds to the object expected by Telegram. If you need to directly access that type, consider using Opts<M> where M is the method name (e.g. Opts<'getMe'>).

Each method returns the object that is specified by Telegram. If you directly need to access the return type of a method, consider using Ret<M> where M is the method name (e.g. Opts<'getMe'>).

// The adjusted `InputMedia*` types:
type InputMedia = Typegram.InputMedia<MyInputFile>;
type InputMediaPhoto = Typegram.InputMediaPhoto<MyInputFile>;
type InputMediaVideo = Typegram.InputMediaVideo<MyInputFile>;
type InputMediaAnimation = Typegram.InputMediaAnimation<MyInputFile>;
type InputMediaAudio = Typegram.InputMediaAudio<MyInputFile>;
type InputMediaDocument = Typegram.InputMediaDocument<MyInputFile>;

Note that interfaces other than the ones mentioned above are unaffected by the customization through MyInputFile. They can simply continue to be imported directly from typegram.

typegram's People

Contributors

knorpelsenf avatar kraftwerk28 avatar mkrhere avatar ni554n avatar ulrichb avatar wojpawlik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

typegram's Issues

InputFile does not reflect the Telegram API

The interface InputFile is a union of a number of other interfaces. However, these interfaces do not appear in the documentation at all, and neither do they describe object structures that are supported by Telegram this way.

The reason for this oddity is that it resembles a part of the telegraf library, but even this is not done properly: InputFileByURL.filename is for instance not a required property.

It is therefore necessary to remove the faulty types from typegram and make it accurately reflect the Telegram Bot API again. If other libraries like telegraf want to wrap certain API methods with their own argument structures, it makes sense to add the type annotations there.

Perhabs telegram has been changed types for ReplyMarkup

Perhabs telegram has been changed types for ReplyMarkup

Link to official documentation - https://core.telegram.org/type/ReplyMarkup

ReplyKeyboardRemove -> replyKeyboardHide

ForceReply -> replyKeyboardForceReply

InlineKeyboardMarkup -> replyInlineMarkup

replyKeyboardMarkup


example for replyKeyboardMarkup:

OLD:

{
  keyboard: KeyboardButton[][];
  is_persistent?: boolean;
  resize_keyboard?: boolean;
  one_time_keyboard?: boolean;
  input_field_placeholder?: string;
}

CURRENT:

{
  rows: KeyboardButton[];
  persistent?: boolean;
  resize?: boolean;
  single_use?: boolean;
  placeholder?: boolean;
}

I tried to make pull request, but permission is denied :)

Build typescript project error with "typegram" module

Description

I've got the below error message when build the project

node_modules/typegram/index.d.ts:10:1 - error TS2308: Module "./default" has already exported a member named 'Ret'. Consider explicitly re-exporting to resolve the ambiguity.

Environment information

  • node: v18.12.1
  • typescript: Version 4.9.3

Docs missing about JSON-serialized properties

Sometimes the Telegram Bot API expects objects that are serialized as JSON, most notably reply_markup. This is a bit strange and actually sometimes a caveat for some people.

typegram models this by simply ignoring the fact that the “objects” are supposed to be strings. This is a good thing: most wrapper libs actually do the serialization under the hood, and so we get a usable library with accurate typing.

However, this deviation from the API should be clearly stated in the docs. It may even make sense to indicate this in the jsdoc at all corresponding places, if it is possible to find a generic explanation of the issue.

Audio message not extending MediaMessage

Telegram supports audio media group messages, but telegraf type doesn't.

bot.on("channel_post", (ctx) => {
    if ("media_group_id" in ctx.channelPost) {
        if ("audio" in ctx.channelPost) {
            console.log(ctx.channelPost) // never type
        }
    }
})

Missing import of CommonMessageBundle [v3.5.0]

Thank you for providing this repo! I was not allowed to quickly provide a PR so I open this issue.

Problem:
In v3.5.0 the update.d.ts is missing an import of CommonMessageBundle from message.d.ts

Fix:
import { CommonMessageBundle, Message, Poll, PollAnswer } from "./message";

Chat Interface does not appear in vscode autocomplete

Hi, Thanks for your astonishing work. I, myself created a similar project but when I saw this repository, I chose to stick with this.
But there is a small issue that I have with it:

code api test

There is only 2 options in vscode autocomplete dropdown list but actual result is different.

...
"chat": {
  "id": 219759038,
  "first_name": "Mehdi",
  "last_name": "Khody",
  "username": "MehdiKhody",
  "type": "private"
},
...

In API.ts, method sendMessage is look like this:

import { ReadStream } from "fs"
import { Typegram } from "typegram"

type Telegram = Typegram<ReadStream>
type Methods = Telegram["Telegram"]
type Params<M extends keyof Methods> = Parameters<Methods[M]>[0]
type Response<M extends keyof Methods> = ReturnType<Methods[M]>


async sendMessage(props: Params<"sendMessage">): Promise<Response<"sendMessage">> {
    return this.send("sendMessage", props)
}

Is there any solution for this problem?

Can't access text property for message

In my simple function written as

//Function returns text from telegram update.
let parseUpdate = function (update: Update.MessageUpdate) {

    return update.message.text;
  }

I can't seem to be able to access the text property in message unless I change this snippet from


  export interface MessageUpdate extends AbstractUpdate {
    /** New incoming message of any kind — text, photo, sticker, etc. */
    message: New & NonChannel & Message;
  }

to

  export interface MessageUpdate extends AbstractUpdate {
    /** New incoming message of any kind — text, photo, sticker, etc. */
    message: New & NonChannel & Message & TextMessage;
  }

Is it my bad implementation?
(thanks for your time)

Type bug

Hi. I'm having this issue when I compile. I'm using: "telegraf": "^4.11.2".

node_modules/telegraf/typings/composer.d.ts:7:15 - error TS1005: ',' expected.

7 import { type CallbackQuery } from './core/types/typegram';
                ~~~~~~~~~~~~~

node_modules/typegram/index.d.ts:10:15 - error TS1005: ',' expected.

10 export { type Typegram } from "./proxied";
                 ~~~~~~~~

Distinguish between types and return types

Some properties are "returned only in getChat" or "...getMe". They should be moved from the base interfaces and put only in the return value they're present in.

Example:

interface User { /* ... */ } // e.g. used in interface ChatMember
interface GottenUser extends User { /* ... */ } // used exclusively in getMe

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.