telegraph

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 6, 2021 License: MIT Imports: 12 Imported by: 1

README

Golang library for Telegraph API

codecov

This project is just to provide a wrapper around the API without any additional features.

Caution! This library is under refactoring, interface may change.

Start using telegraph

Download and install it:

$ go get -u github.com/TechMinerApps/telegraph

Import it in your code:

import "github.com/TechMinerApps/telegraph"

Document

See GoDoc

QuickStart


// Content in a string format (for this example).
// Be sure to wrap every media in a <figure> tag, okay? Be easy.
const data = `
    <figure>
        <img src="/file/6a5b15e7eb4d7329ca7af.jpg"/>
    </figure>
    <p><i>Hello</i>, my name is <b>Page</b>, <u>look at me</u>!</p>
    <figure>
        <iframe src="https://youtu.be/fzQ6gRAEoy0"></iframe>
        <figcaption>
            Yes, you can embed youtube, vimeo and twitter widgets too!
        </figcaption>
    </figure>
`
func Example_fastStart() {
	var err error
	// Create new Telegraph account.
	requisites := telegraph.Account{
		ShortName: "toby3d", // required

		// Author name/link can be epmty. So secure. Much anonymously. Wow.
		AuthorName: "Maxim Lebedev",       // optional
		AuthorURL:  "https://t.me/toby3d", // optional
	}
	client := telegraph.NewClient()
	account, err = client.CreateAccount(requisites)
	if err != nil {
        // Do error check
    }

	// Make sure that you have saved acc.AuthToken for create new pages or make
	// other actions by this account in next time!

	// Format content to []telegraph.Node array. Input data can be string, []byte
	// or io.Reader.
	content, err = client.ContentFormat(data)
	if err != nil {
        // Do error check
    }

	// Boom!.. And your text will be understandable for Telegraph. MAGIC.

	// Create new Telegraph page
	pageData := telegraph.Page{
		Title:   "My super-awesome page", // required
		Content: content,                 // required

		// Not necessarily, but, hey, it's just an example.
		AuthorName: account.AuthorName, // optional
		AuthorURL:  account.AuthorURL,  // optional
	}
	page, err = client.CreatePage(pageData, false)
	if err != nil {
        // Do error check
    }

	// Show link from response on created page.
	log.Println("Kaboom! Page created, look what happened:", page.URL)
}

Credit

Original developer: @toby3d

License

This Project is licensed under MIT License

FOSSA Status

Documentation

Overview

Package telegraph has functions and types used for interacting with the Telegraph API.

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.

To maintain the purity of the basic interface, we launched the @Telegraph bot for those who require advanced features. This bot can help you manage your articles across any number of devices and get page view statistics for any Telegraph page.

Anyone can enjoy the simplicity of Telegraph publishing, not just Telegram users. For this reason, all developers are welcome to use this Telegraph API to create bots like @Telegraph for any other platform, or even standalone interfaces.

Example (ContentFormat)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

var content []telegraph.Node

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	const data = `<figure>
<img src="http://telegra.ph/file/6a5b15e7eb4d7329ca7af.jpg" /></figure>
<p><i>Hello</i>, my name is <b>Page</b>, <u>look at me</u>!</p>
<figure><iframe src="https://youtu.be/fzQ6gRAEoy0"></iframe>
<figcaption>Yes, you can embed youtube, vimeo and twitter widgets too!</figcaption>
</figure>`

	var err error
	client := telegraph.NewClient()
	content, err = client.ContentFormat(data)
	errCheck(err)

	log.Printf("Content: %#v", content)
}
Output:

Example (CreateAccount)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

var account *telegraph.Account

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	var err error
	client := telegraph.NewClient()
	account, err = client.CreateAccount(telegraph.Account{
		ShortName:  "Sandbox",
		AuthorName: "Anonymous",
	})
	errCheck(err)

	log.Println("AccessToken:", account.AccessToken)
	log.Println("AuthURL:", account.AuthorURL)
	log.Println("ShortName:", account.ShortName)
	log.Println("AuthorName:", account.AuthorName)
}
Output:

Example (CreatePage)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

var (
	account *telegraph.Account
	page    *telegraph.Page
	content []telegraph.Node
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	var err error
	client := telegraph.NewClient()
	page, err = client.CreatePage(telegraph.Page{
		Title:      "Sample Page",
		AuthorName: account.AuthorName,
		Content:    content,
	}, true)
	errCheck(err)

	log.Println(page.Title, "by", page.AuthorName, "has been created!")
	log.Println("PageURL:", page.URL)
}
Output:

Example (EditAccountInfo)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

var account *telegraph.Account

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	var err error
	client := telegraph.NewClient()
	account, err = client.EditAccountInfo(telegraph.Account{
		ShortName:  "Sandbox",
		AuthorName: "Anonymous",
	})
	errCheck(err)

	log.Println("AuthURL:", account.AuthorURL)
	log.Println("ShortName:", account.ShortName)
	log.Println("AuthorName:", account.AuthorName)
}
Output:

Example (EditPage)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

var (
	account *telegraph.Account
	page    *telegraph.Page
	content []telegraph.Node
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	var err error

	client := telegraph.NewClient()
	page, err = client.EditPage(telegraph.Page{
		Title:      "Sample Page",
		AuthorName: account.AuthorName,
		Content:    content,
	}, true)
	errCheck(err)

	log.Println("Page on", page.Path, "path has been updated!")
	log.Println("PageURL:", page.URL)
}
Output:

Example (GetAccountInfo)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	client := telegraph.NewClient()
	info, err := client.GetAccountInfo(
		telegraph.FieldShortName,
		telegraph.FieldPageCount,
	)
	errCheck(err)

	log.Println("ShortName:", info.ShortName)
	log.Println("PageCount:", info.PageCount, "pages")
}
Output:

Example (GetPage)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	client := telegraph.NewClient()
	info, err := client.GetPage("Sample-Page-12-15", true)
	errCheck(err)

	log.Println("Getted info about", info.Path, "page:")
	log.Println("Author:", info.AuthorName)
	log.Println("Views:", info.Views)
	log.Println("CanEdit:", info.CanEdit)
}
Output:

Example (GetPageList)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	client := telegraph.NewClient()
	list, err := client.GetPageList(0, 3)
	errCheck(err)

	log.Println("Getted", list.TotalCount, "pages")

	for i := range list.Pages {
		p := list.Pages[i]
		log.Printf("%s: %s\n~ %s\n\n", p.Title, p.URL, p.Description)
	}
}
Output:

Example (GetViews)
package main

import (
	"log"
	"time"

	"github.com/TechMinerApps/telegraph"
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	client := telegraph.NewClient()
	pagePath := "Sample-Page-12-15"
	dateTime := time.Date(2016, time.December, 0, 0, 0, 0, 0, time.UTC)
	views, err := client.GetViews(pagePath, dateTime)
	errCheck(err)

	log.Println(pagePath, "has been viewed", views.Views, "times")
}
Output:

Example (QuickStart)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

// Content in a string format (for this example).
// Be sure to wrap every media in a <figure> tag, okay? Be easy.
const data = `
    <figure>
        <img src="/file/6a5b15e7eb4d7329ca7af.jpg"/>
    </figure>
    <p><i>Hello</i>, my name is <b>Page</b>, <u>look at me</u>!</p>
    <figure>
        <iframe src="https://youtu.be/fzQ6gRAEoy0"></iframe>
        <figcaption>
            Yes, you can embed youtube, vimeo and twitter widgets too!
        </figcaption>
    </figure>
`

var (
	account *telegraph.Account
	page    *telegraph.Page
	content []telegraph.Node
)

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	var err error
	// Create new Telegraph account.
	requisites := telegraph.Account{
		ShortName: "toby3d", // required

		// Author name/link can be epmty. So secure. Much anonymously. Wow.
		AuthorName: "Maxim Lebedev",       // optional
		AuthorURL:  "https://t.me/toby3d", // optional
	}
	client := telegraph.NewClient()
	account, err = client.CreateAccount(requisites)
	errCheck(err)

	// Make sure that you have saved acc.AuthToken for create new pages or make
	// other actions by this account in next time!

	// Format content to []telegraph.Node array. Input data can be string, []byte
	// or io.Reader.
	content, err = client.ContentFormat(data)
	errCheck(err)

	// Boom!.. And your text will be understandable for Telegraph. MAGIC.

	// Create new Telegraph page
	pageData := telegraph.Page{
		Title:   "My super-awesome page", // required
		Content: content,                 // required

		// Not necessarily, but, hey, it's just an example.
		AuthorName: account.AuthorName, // optional
		AuthorURL:  account.AuthorURL,  // optional
	}
	page, err = client.CreatePage(pageData, false)
	errCheck(err)

	// Show link from response on created page.
	log.Println("Kaboom! Page created, look what happened:", page.URL)
}
Output:

Example (RevokeAccessToken)
package main

import (
	"log"

	"github.com/TechMinerApps/telegraph"
)

var account *telegraph.Account

func errCheck(err error) {
	if err != nil {
		log.Fatalln(err.Error())
	}
}

func main() {
	var err error
	client := telegraph.NewClient()
	// You must rewrite current variable with account structure for further usage.
	account, err = client.RevokeAccessToken()
	errCheck(err)

	log.Println("AccessToken:", account.AccessToken)
}
Output:

Index

Examples

Constants

View Source
const (
	// FieldShortName used as GetAccountInfo argument for getting account name.
	FieldShortName string = "short_name"

	// FieldAuthorName used as GetAccountInfo argument for getting author name.
	FieldAuthorName string = "author_name"

	// FieldAuthorURL used as GetAccountInfo argument for getting profile link.
	FieldAuthorURL string = "author_url"

	// FieldAuthURL used as GetAccountInfo argument for getting URL to authorize a browser on telegra.ph.
	FieldAuthURL string = "auth_url"

	// FieldPageCount used as GetAccountInfo argument for getting number of pages belonging to the Telegraph
	// account.
	FieldPageCount string = "page_count"
)

Variables

View Source
var (
	// ErrInvalidDataType is returned when ContentFormat function are passed a data argument of invalid type.
	ErrInvalidDataType = errors.New("invalid data type")

	// ErrNoInputData is returned when any method get nil argument.
	ErrNoInputData = errors.New("no input data")

	// ErrFloodWait is returned when recieving a flood error
	ErrFloodWait = errors.New("reaching telegraph flood limit")
)

Functions

This section is empty.

Types

type Account

type Account struct {
	// Only returned by the createAccount and revokeAccessToken method. Access token of the Telegraph
	// account.
	AccessToken string `json:"access_token"`

	// URL to authorize a browser on telegra.ph and connect it to a Telegraph account. This URL is valid
	// for only one use and for 5 minutes only.
	AuthURL string `json:"auth_url,omitempty"`

	// Account name, helps users with several accounts remember which they are currently using. Displayed
	// to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name.
	ShortName string `json:"short_name"`

	// Default author name used when creating new articles.
	AuthorName string `json:"author_name"`

	// Profile link, opened when users click on the author's name below the title. Can be any link, not
	// necessarily to a Telegram profile or channel.
	AuthorURL string `json:"author_url"`

	// Number of pages belonging to the Telegraph account.
	PageCount int `json:"page_count,omitempty"`
}

Account represents a Telegraph account.

type Client added in v0.1.0

type Client interface {

	// Account returns the account object client is using
	Account() *Account

	// Client return the http client using, not recommend using
	Client() *http.Client

	// ContentFormat format the input of string or byte to Node object
	ContentFormat(data interface{}) (n []Node, err error)

	// CreateAccount is used to create a new account using provided info
	// It alse set the account info stored in client
	CreateAccount(account Account) (*Account, error)

	// CreatePage use the account info stored within client to create a new page
	CreatePage(page Page, returnContent bool) (*Page, error)

	// EditAccountInfo update the account info according to input
	// It ignores the Token field in the input account object and use the one stored within client
	EditAccountInfo(update Account) (*Account, error)

	// EditPage update the Page provided
	EditPage(update Page, returnContent bool) (*Page, error)

	// GetAccountInfo get the account info from the token stored in client object
	// It does not update the account info in client object
	GetAccountInfo(fields ...string) (*Account, error)

	// GetPage get the page object from provided url
	GetPage(path string, returnContent bool) (*Page, error)

	// GetPageList
	GetPageList(offset, limit int) (*PageList, error)

	// GetViews get the views count of specific page
	GetViews(path string, date time.Time) (*PageViews, error)

	// RevokeAccessToken is used when accesstoken is compromises
	RevokeAccessToken() (*Account, error)

	// SetSocksProxy
	SetSocksProxy(proxy string)

	// SetHTTPProxy
	SetHTTPProxy(proxy string)
}

Client is the interface to act with telegraph API The 9 method is identical to the 9 method provided at https://telegra.ph/api

func NewClient added in v0.1.0

func NewClient() Client

NewClient return a empty client useful when creating new account or testing otherwise should use NewClientWithToken

func NewClientWithToken added in v0.1.0

func NewClientWithToken(token string, httpClientList ...*http.Client) (Client, error)

NewClientWithToken create a client from a valid token the client is already usable with account info set correctly

type Node

type Node interface{}

Node is abstract object represents a DOM Node. It can be a String which represents a DOM text node or a NodeElement object.

type NodeElement

type NodeElement struct {
	// Name of the DOM element. Available tags: a, aside, b, blockquote, br, code, em, figcaption, figure,
	// h3, h4, hr, i, iframe, img, li, ol, p, pre, s, strong, u, ul, video.
	Tag string `json:"tag"`

	// Attributes of the DOM element. Key of object represents name of attribute, value represents value
	// of attribute. Available attributes: href, src.
	Attrs map[string]string `json:"attrs,omitempty"`

	// List of child nodes for the DOM element.
	Children []Node `json:"children,omitempty"`
}

NodeElement represents a DOM element node.

type Page

type Page struct {
	// Path to the page.
	Path string `json:"path"`

	// URL of the page.
	URL string `json:"url"`

	// Title of the page.
	Title string `json:"title"`

	// Description of the page.
	Description string `json:"description"`

	// Name of the author, displayed below the title.
	AuthorName string `json:"author_name,omitempty"`

	// Profile link, opened when users click on the author's name below the title. Can be any link, not
	// necessarily to a Telegram profile or channel.
	AuthorURL string `json:"author_url,omitempty"`

	// Image URL of the page.
	ImageURL string `json:"image_url,omitempty"`

	// Content of the page.
	Content []Node `json:"content,omitempty"`

	// Number of page views for the page.
	Views int `json:"views"`

	// Only returned if access_token passed. True, if the target Telegraph account can edit the page.
	CanEdit bool `json:"can_edit,omitempty"`
}

Page represents a page on Telegraph.

type PageList

type PageList struct {
	// Total number of pages belonging to the target Telegraph account.
	TotalCount int `json:"total_count"`

	// Requested pages of the target Telegraph account.
	Pages []Page `json:"pages"`
}

PageList represents a list of Telegraph articles belonging to an account. Most recently created articles first.

type PageViews

type PageViews struct {
	// Number of page views for the target page.
	Views int `json:"views"`
}

PageViews represents the number of page views for a Telegraph article.

type Response

type Response struct {
	Ok     bool            `json:"ok"`
	Error  string          `json:"error,omitempty"`
	Result json.RawMessage `json:"result,omitempty"`
}

Response contains a JSON object, which always has a Boolean field ok. If ok equals true, the request was successful, and the result of the query can be found in the result field. In case of an unsuccessful request, ok equals false, and the error is explained in the error field (e.g. SHORT_NAME_REQUIRED).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL