npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

better-telegraph

v2.1.1

Published

Node version of https://deno.land/x/telegraph

Downloads

40

Readme

Telegra.ph API wrapper for NodeJS

Forked from Deno version

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

See the Npm module and the Deno module.

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

Install the module

npm install better-telegraph

or

yarn add better-telegraph

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

// Import Telegraph class to your project.
import { Telegraph } from "better-telegraph";

// 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:

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"
}

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/"
}

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"
}

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/"
}

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!"[("Foo", "Bar")]; // Just string // 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
}

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
}

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
}

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
		}
	]
}

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 "better-telegraph";
// 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 "better-telegraph";

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 "better-telegraph";
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 "better-telegraph";
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.