Tiny Telegra.ph API wrapper for Deno

Overview

Telegra.ph API wrapper for Deno 🦕

This is a tiny Telegra.ph API wrapper for Deno written in TypeScript. All methods as listed here are available. See Usage for usage examples for each methods.

See the Deno module here.

Table of Contents


What is Telegra.ph?

Telegra.ph is a minimalist publishing tool that allows you to create richly formatted posts and push them to the Web in just a click. Telegraph posts also get beautiful Instant View pages on Telegram.

It is recommended to read the official Telegra.ph API docs @https://telegra.ph/api

This module contains all methods in the official Telegra.ph API and a unofficial Telegra.ph file upload module (Only .jpg, .jpeg, .png, .gif and .mp4 files). See example usage.


Usage

Import to your project file and connect or create a Telegraph account:

// Import Telegraph class to your project.
import { Telegraph } from "https://deno.land/x/telegraph/mod.ts";

// Connect to an account.
const tphOldAccount = new Telegraph({
  access_token: "<your account access token>",
});

// Oh, don't have an access token? Create an account and use it.
// This will create an account with the given details.
const tphNew = new Telegraph({
  short_name: "Deno", // Short Name is required.
  author_name: "Deno.land", // Optional parameter.
  author_url: "https://deno.land/", // Optional parameter.
});

// You want to use an already existing account with an access token and edit some of the details?
const tphUpdatedOld = new Telegraph({
  access_token: "<the account access token>",
  short_name: "Ryan Dahl", // A little change. (Optional)
  author_url: "https://github.com/ry", // Change in URL (Optional)
});

Now you can use any methods. See the examples for each methods:

Account > createAccount

Creates a new Telegraph account, and returns the newly created account's details including auth_url and access_token.

Read more: https://telegra.ph/api#createAccount

Usage:

tph.createAccount({
  short_name: "Sandbox", // Required
  author_name: "Anonymous", // Optional
  author_url: "", // Optional
});

Outputs:

{
  "short_name": "Sandbox",
  "author_name": "Anonymous",
  "author_url": "",
  "access_token": "xxxxxxxx",
  "auth_url": "https://edit.telegra.ph/auth/xxxxxxx"
}

Account > editAccount

Edits the details of the connected Telegraph account, and returns the edited account details. Does not includes access_token or auth_url. Requires atleast one of the parameters.

Read more: https://telegra.ph/api#editAccountInfo

Usage:

tph.editAccount({
  short_name: "BoxSand",
  author_name: "Nonymous",
  author_url: "https://minecraft.net",
});

Outputs:

{
  "short_name": "BoxSand",
  "author_name": "Nonymous",
  "author_url": "https://minecraft.net/"
}

Account > revokeAccessToken

Revokes access_token of the connected Telegraph account, and returns the new access_token and auth_url.

Read more: https://telegra.ph/api#revokeAccessToken

Takes in one optional parameter,

  • save
    • Type: boolean.
    • Defaults to true.
    • If true, the new access_token will be set to the connected account.

Usage:

// Revokes the `access_token` and sets the
// new one to the connected account.
tph.revokeAccessToken();
// Only revokes the `access_token`.
// @param save - boolean. Defaults to true.
tph.revokeAccessToken(false);

Outputs:

{
  "access_token": "xxxxxxxx",
  "auth_url": "https://edit.telegra.ph/auth/xxxxxxx"
}

Account > getAccount

Returns the account details.

Read more: https://telegra.ph/api#getAccountInfo

Parameter:

  • fields: Fields to return.
    • Type: ("short_name" | "author_name" | "author_url" | "auth_url" | "page_count")[].
    • Defaults to [ "short_name", "author_name", "author_url", "auth_url", "page_count" ].

Usage:

// Returns all.
tph.getAccount();
// Returns specified.
tph.getAccount(["author_url"]); // --> { author_url: "https://minecraft.net/" }
tph.getAccount(["author_name", "author_url"]); // --> { author_url: "https://minecraft.net/", author_name: "Nonymous" }
tph.getAccount(["page_count"]);

Outputs (Or only specified fields):

{
  "short_name": "BoxSand",
  "author_name": "Nonymous",
  "author_url": "https://minecraft.net/"
}

Page > create

Creates a new Telegraph Page (Post), and returns the details of the created page.

Read more: https://telegra.ph/api#createPage

In parameter options, the property content can be a string or string[] or HTML or Markdown or an array of Node.

See Content Formatting for more.

Example for content:

"Telegraph is cool!" // Just string
["Foo", "Bar"]; // Array of strings.

Passing Markdown as content:

const content = parseMarkdown(
  "## Jurassic Deno\n\n" +
    `![image](${await Telegraph.upload("jurassicDeno.jpg")})`,
)!;

Or the same thing by using HTML as content:

const content = parseHtml(
  "<h3>Jurassic Deno</h3><br>" +
    `<img src="${await Telegraph.upload("jurassicDeno.jpg")}">`,
)!;

Passing Node as content:

[
  {
    tag: "a", // Tag.
    attrs: {
      href: "https://github.com", // Attributes supports `href` and `src`.
    },
    children: ["GitHub"],
  },
  {
    tag: "br",
  },
  // A paragraph
  {
    tag: "p",
    children: [
      "GitHub is where over 73 million developers shape the future of software, together.",
    ],
  },
  // An image
  {
    tag: "img",
    attrs: { // Attributes supports `href` and `src`.
      src:
        "https://github.githubassets.com/images/modules/site/social-cards/github-social.png",
    },
  },
  // A code block.
  {
    tag: "pre",
    children: [
      `const tph = new Telegraph({
  accessToken: ""
});

tph.getAccount();`,
    ],
  },
];

Usage:

tph.create({
  title: "Telegraph is cool!", // Required. 1 to 256 characters.
  content: "Telegraph is cool!", // Required. Upto 64KB.
  author_name: "Telegram", // Optional. 0 to 128 characters.
  author_url: "https://telegram.org", // Optional. 0 to 512 characters.
  return_content: true, // Optional. Defaults to `false`.
});

Outputs:

{
  "path": "Telegraph-is-cool-12-24",
  "url": "https://telegra.ph/Telegraph-is-cool-12-24",
  "title": "Telegraph is cool!",
  "description": "",
  "author_name": "Telegram",
  "author_url": "https://telegram.org/",
  "content": ["Telegraph is cool!"],
  "views": 0,
  "can_edit": true
}

Page > edit

Edits a Telegraph page (post), and on success, returns the edited page details.

See Content Formatting to know more about the values can be given to content parameter.

Read more: https://telegra.ph/api#editPage

Usage:

tph.edit("Telegraph-is-cool-12-24", {
  content: "Telegraph is simple!", // Required.
  title: "Telegraph is simple, but cool!", // Optional.
  author_name: "Telegram Team", // Optional.
  author_url: "https://telegram.org/", // Optional.
  return_content: false, // Optional.
});

Outputs:

{
  "path": "Telegraph-is-cool-12-24",
  "url": "https://telegra.ph/Telegraph-is-cool-12-24",
  "title": "Telegraph is simple, but cool!",
  "description": "",
  "author_name": "Telegram Team",
  "author_url": "https://telegram.org/",
  "views": 0,
  "can_edit": true
}

Page > get

Returns the details of a Telegraph page (post).

Read more: https://telegra.ph/api#getPage

Parameters

  • path (string): Path of the page.
  • returnContent (boolean): Optional. If true, the page content will also be returned. Defaults to false.

Usage:

tph.get("Telegraph-is-cool-12-24");

Outputs:

{
  "path": "Telegraph-is-cool-12-24",
  "url": "https://telegra.ph/Telegraph-is-cool-12-24",
  "title": "Telegraph is simple, but cool!",
  "description": "",
  "author_name": "Telegram Team",
  "author_url": "https://telegram.org/",
  "views": 0
}

Page > getPages

Returns a list of pages belonging to the connected Telegraph account.

Read more: https://telegra.ph/api#getPageList

Usage:

tph.getPages(); // -> Gets all pages belonging to the connected account.
// Or, if you want some of them,
tph.getPages({
  offset: 1, // Optional. Sequential number of the first page to be returned
  limit: 2, // Optional. Number of pages to be returned.
});
// ^ This will return you the details of 2nd and 3rd last created pages.

Outputs:

{
  "total_count": 14,
  "pages": [
    {
      "path": "GitHub-12-24-7",
      "url": "https://telegra.ph/GitHub-12-24-7",
      "title": "GitHub",
      "description": "GitHub is where over 73 million developers shape the future of software, together.\nconst tph = new T...",
      "author_name": "GitHub",
      "author_url": "https://github.com/",
      "views": 0,
      "can_edit": true
    },
    {
      "path": "Telegraph-is-cool-12-24",
      "url": "https://telegra.ph/Telegraph-is-cool-12-24",
      "title": "Telegraph is simple, but cool!",
      "description": "",
      "author_name": "Telegram Team",
      "author_url": "https://telegram.org/",
      "views": 0,
      "can_edit": true
    }
  ]
}

Page > getPageViews

Returns the number of views of the specified page. You can pass in some optional date options to get the views of that time.

Read more: https://telegra.ph/api#getViews

Usage:

tph.getPageViews("Telegraph-is-cool-12-24"); // -> { views: 0 }
// Maybe only the views of the year 2021?
tph.getPageViews({
  year: 2021,
});
// Just views of 3PM of December 24th of year 2021.
tph.getPageViews({
  hour: 15, // Optional. 0 to 24.
  day: 24, // Required if `hour` is passed. 1 to 31.
  month: 12, // Required if `day` is passed. 1 to 12.
  year: 2021, // Required if `month` is passed. 2000 to 2100.
});

Outputs:

{ "views": 0 }

Upload

This is not a part of the official Telegra.ph API. This function helps you to upload .jpg, .jpeg, .png, .gif and .mp4 files upto ~6MB (I think so) to Telegra.ph.

import { parseMarkdown, Telegraph } from "https://deno.land/x/telegraph/mod.ts";
// Local File
const localFile = await Telegraph.upload("video.mp4");
// From URL, you actually don't have to do this, you can pass this URL as src if you want to.
// But, it might become useful for temporary links.
const url = await Telegraph.upload(
  "https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_640_3MG.mp4",
);
// Or URL | Blob | Uint8Array | BufferSource?

// Use while creating a page.
const tph = new Telegraph({
  access_token: "<your access token>",
});

// What about markdown?
// https://telegra.ph/Jurassic-Deno-01-10
const content = parseMarkdown(
  "Jurassic Deno\n\n" +
    `![image](${await Telegraph.upload("jurassicDeno.jpg")})`,
)!;

await tph
  .create({
    title: "Jurassic Deno",
    content,
  })
  .then((page) => console.log(page.url));

// Or the same exact thing in Node.
// https://telegra.ph/Jurassic-Deno-12-25
await tph.create({
  title: "Jurassic Deno",
  content: [
    "Jurassic Deno:",
    {
      tag: "img",
      attrs: {
        src: await Telegraph.upload("jurassicDeno.jpg"),
      },
    },
  ],
});

// https://telegra.ph/Denoland-12-25
await tph.create({
  title: "Deno.land",
  content: [
    // Local file
    {
      tag: "img",
      attrs: {
        src: await Telegraph.upload("jurassicDeno.jpg"),
      },
    },
    // You actually don't have to do this.
    // You can just give that URL as value of src.
    {
      tag: "img",
      attrs: {
        src: await Telegraph.upload("https://deno.land/images/deno_logo.png"),
      },
    },
    {
      tag: "img",
      attrs: {
        src: await Telegraph.upload(
          "https://github.com/denolib/animated-deno-logo/raw/master/deno-rect-24fps.gif",
        ),
      },
    },
    "Example video:",
    {
      tag: "video",
      attrs: {
        src: await Telegraph.upload(
          "https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_640_3MG.mp4",
        ),
      },
    },
  ],
});

Content Formatting

Content can be Markdown, HTML, or just String or Array of strings or Node or an Array of both strings and Nodes. To use HTML and Markdown you need to import two parser functions from the module.

import { parseHtml, parseMarkdown } from "https://deno.land/x/telegraph/mod.ts";

Here are basic examples for each type. See the README of the official Repository to find more of them.

const content = "With just a string";
const content = ["Array of strings.", " I am number one."];

HTML, parseHtml(htmlContent) will convert the HTML string to Node.

// Import the HTML parser.
import { parseHtml } from "https://deno.land/x/telegraph/mod.ts";
const content = parseHtml(`<h1>Pure HTML, boys</h1><br>
<p><b>Be bold</b></p>`);

Markdown, parseMarkdown(mdContent) will parse the Markdown down to Node for the content.

// Import the markdown parser.
import { parseMarkdown } from "https://deno.land/x/telegraph/mod.ts";
const content = parseMarkdown(`## Heading 2\n\nThis is so **cool**!`);

Node, a bit complicated one to create (That's why MD and HTML methods exists), if there is a lot of formatting and all. And you have to do this in

const content = [
  {
    tag: "a", // Specifies the tag.
    attrs: {
      href: "https://github.com", // Attributes supports `href` and `src`.
    },
    children: ["GitHub"], // Children can be another Node, parsed HTML, parsed MD, strings.
  },
  { tag: "br" },
  {
    tag: "p", // Paragraph
    children: [
      "GitHub is where over 73 million developers shape the future of software, together.",
    ],
  },
  {
    tag: "img", // Image
    attrs: { // Attributes supports `href` and `src`.
      src:
        "https://github.githubassets.com/images/modules/site/social-cards/github-social.png",
    },
  },
];

If you are having issues with this library, or if you like to suggest something that can make this library better, please open a issue here. Or if you'd like to contribute, please open a pull request.

MIT License. Copyright (c) 2022 dcdunkan.

Comments
  • Library not working

    Library not working

    @dcdunkan

    Problem

    The library is not working for me as i tried to just simply create a new telegraph account through the api , code for which is provided below and following that the error that was thrown on my system.

    Code

    import { Telegraph } from "https://deno.land/x/telegraph/mod.ts";
    
    //create new telegraph account
    const tp = new Telegraph({
        short_name: "Ashish",
        author_name: "Ashish Bhushan Kumar",
    })
    
    await tp.setupAccount();
    
    console.log(tp.token);
    

    Error

    error: TS2339 [ERROR]: Property 'href' does not exist on type 'NamedNodeMap'.
      if ("href" in el.attributes) nodeElement.attrs = { href: el.attributes.href };
                                                                             ~~~~
        at https://deno.land/x/[email protected]/src/parse.ts:121:74
    
    TS2339 [ERROR]: Property 'src' does not exist on type 'NamedNodeMap'.
        let src = el.attributes.src;
                                ~~~
        at https://deno.land/x/[email protected]/src/parse.ts:123:29
    
    Found 2 errors.
    

    Steps taken

    I tried to look into the library and locating where this type error is coming from and i traced it back to this part here in https://github.com/dcdunkan/telegraph/blob/e6771ac6a9262933136914c9b2908f487ac48531/src/parse.ts#L121

    the typescript compiler shows that

     TS2339 [ERROR]: Property 'href' does not exist on type 'NamedNodeMap'.
    

    and i could not find any other solution.

    Possible error

    I think that the deno modules imported in deps.ts are implicitly using the latest version and that might not play well with the existing code which might have been written on a previous version, so i suspect something broke on the new update in any of the dependencies.

    https://github.com/dcdunkan/telegraph/blob/e6771ac6a9262933136914c9b2908f487ac48531/deps.ts#L1-L4

    That's just my opinion though!!!

    opened by code-withAshish 1
  • Telegram Markdown support + Updated content parsing

    Telegram Markdown support + Updated content parsing

    Changelog

    Telegram Flavored Markdown support

    Closes #1

    • Removed parseMarkdown.
    • Not exporting parseHtml anymore.
    • Added a common parse function which takes in content and parseMode as arguments, and returns a Telegra.ph compatible content. A full example (You may have to change the imports since it's not released yet)
    const mdContent = parse("**bold**", "Markdown");
    const tgMdContent = parse("*bold*", "TGMarkdown"); // MarkdownV2
    const htmlContent = parse("<b>bold</b>", "HTML");
    

    Other

    • Formatted comments for better readability (Max 80 characters per line).

    I have tried my best on Telegram Markdown support. There could be bugs.

    TODO

    • As mentioned in #2, need to update docs. Only releasing after updating both JSDocs and README Docs. And it is currently being updated.
    documentation enhancement 
    opened by dcdunkan 0
  • Node.js Support

    Node.js Support

    It is good to have Node.js support. Should use deno2node. As mentioned in #1, if the library is going to be used as the dependency of the grammY plugin, we need Node.js support.

    opened by dcdunkan 0
  • Better Documentation

    Better Documentation

    The current documentation (both JSDocs and README) is pretty bad. Of course, I have documented everything. But they are not too good. So we should have some better docs.

    • [ ] Better JSDocs.
    • [ ] Better and minimal README.
    • [ ] ~Move the complete docs to GitHub pages(, maybe?).~
    • [ ] Include argument types of methods to Docs.
    documentation 
    opened by dcdunkan 2
  • Support for Telegram Flavored Markdown

    Support for Telegram Flavored Markdown

    Currently, the library uses [email protected] for the purpose of parsing the markdown to HTML and which seems to be using GFM spec. But, I originally created this library as an dependency for a future plugin of grammY (docs) -- an amazing Telegram Bot Framework for Deno and Node.js -- called grammy-telegraph. So, since this library is supposed to be used in a Telegram Bot framework, it is necessary to have support for the Markdown syntax that Telegram supports. Also, if you didn't knew, Telegra.ph is created by the Telegram Team - https://telegram.org/blog/instant-view#telegraph. So, really need it.

    TODO

    • [x] Add custom parsers for both MarkdownV2 ~and Markdown~ as described here.
    • [x] Merge all content parsing helper functions to one: parse. With an option to specify the parseMode of the content provided. So it should look like,
    parse("**Bold (GFM)**", "HTML"); // Marky default.
    
    // Telegram MarkdownV2 and V1 uses the exact spec.
    // Main difference are the escaping and nesting. I think it's okay to
    // only have one version.
    // parse("*Bold (TFM)*", "TGMarkdown"); // https://core.telegram.org/bots/api#markdown-style
    
    parse("*Bold \*(TFM)*", "TGMarkdownV2"); // https://core.telegram.org/bots/api#markdownv2-style
    parse("<b>HTML Bold</b>", "HTML"); // Normal HTML.
    

    If anybody reading this, you can contribute if you want to.

    enhancement 
    opened by dcdunkan 1
Owner
Dunkan
console.log(3446)
Dunkan
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
🛣️ A tiny and fast http request router designed for use with deno and deno deploy

Rutt Rutt is a tiny http router designed for use with deno and deno deploy. It is written in about 200 lines of code and is pretty fast, using an exte

Denosaurs 26 Dec 10, 2022
A Roblox OpenCloud API wrapper for Deno (and NodeJS) written in TypeScript.

Active Development This module is currently in active development. Nothing is going to stay consistent as it reaches a stable release. Dynablox Docs |

null 12 Oct 28, 2022
TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy

Atlas SDK atlas_sdk is a TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy Links Docs Import Replace LATEST_VERSION with current latest versi

Erfan Safari 20 Dec 26, 2022
This is a simple boilerplate for a Deno website, deployed with Deno Deploy.

Simple Deno Website Boilerplate This is a simple website boilerplate built using Deno and deployed using Deno Deploy. Demo at simple-deno-website-boil

Bruno Bernardino 15 Dec 3, 2022
Deno bindings for yoga, using Deno FFI.

deno_yoga Deno bindings for yoga, using Deno FFI. Usage flags: --allow-ffi: Requires ffi access to "yogacore.dll", "libyogacore.so", "libyogacore.dyli

迷渡 6 Feb 11, 2022
Convenient wrapper for launching CLI applications for Deno.

deno_cliwrap Convenient wrapper for launching CLI applications in Deno. Module link: https://deno.land/x/cliwrap Usage In the following examples, we'l

null 2 Jul 2, 2022
A small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity

Wren Wren is a small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity. convenient aliases for HTTP responses au

Jakub Neander 69 Dec 12, 2022
deno-ja (Deno Japanese community) showcase

Showcase Deno本家よりも気軽に作ったものを公開できるようなShowcaseです。 スクリーンショットの撮影方法 短めのidを決めていただいて、下記のようにスクリプトを実行してください。 deno task screenshot [url] [id] ※エラーが出る場合は、下記を実行してみ

deno-ja 17 Oct 28, 2022
A command-line tool to manage Deno scripts installed via deno install

??️ nublar nublar is a command-line tool to manage your scripts installed via deno install. ??️ Installation deno install --allow-read --allow-write -

Shun Ueda 16 Dec 26, 2022
A tiny spawn wrapper for Node.js

tinysh A tiny spawn wrapper for Node.js. const {ls, curl} = require('tinysh') const list = ls('-la').trim().split('\n') const resp = curl('https://m

Anton Medvedev 50 Dec 8, 2022
An open source API wrapper for TechHost API.

TechHost API Wrapper An open source API wrapper for TechHost API. Badges Installation Install techhost-api-wrapper with npm. npm install techhost-api-

Eight∞ 4 Jun 23, 2022
News API Wrapper for Violetics API News

News API Wrapper for Violetics API News

Violetics 3 Mar 23, 2022
A wrapper for valorant-api, a third-party API for getting data within Valorant. Available on npm

valorant-wrapper A wrapper for the third-party valorant-api How to Use All endpoints can be accessed off the ValAPI class. import { ValAPI } from 'val

Aircraft Overviewer 5 Nov 7, 2022
[WIP] WebGL API implementation for Deno, built on GLFW using FFI.

Note I'm no longer working on this project because I have just realized macOS does not support OpenGL ES API, and adding Desktop GL backend to this mo

DjDeveloper 14 Jun 11, 2022
Programmers House api official wrapper

programmershouse-wrapper Programmers House api official wrapper Install: npm install programmershouse-wrapper Example of using: With .then //importing

Raid 2 Mar 23, 2022
Proposal(s) for a stable Deno FFI API

Proposal(s) for a stable API for Deno FFI In this repository I propose a possible stable APIs for Deno FFI. The proposals are split into folders by to

Aapo Alasuutari 6 Dec 5, 2022