telegraph

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2020 License: MIT Imports: 10 Imported by: 10

README

GoLang bindings for the Telegraph API discord

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

All methods and types available and this library (possibly) is ready for use in production. Yaay!

Start using telegraph

Download and install it: $ go get -u gitlab.com/toby3d/telegraph

Import it in your code: import "gitlab.com/toby3d/telegraph"

Examples

See GoDoc examples section or check example_test.go.

Need help?

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 (FastStart)
package main

import (
	"log"

	"gitlab.com/toby3d/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
	}
	account, err = telegraph.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 = telegraph.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 = account.CreatePage(pageData, false)
	errCheck(err)

	// Show link from response on created page.
	log.Println("Kaboom! Page created, look what happened:", page.URL)
}
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")
)

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.

func CreateAccount

func CreateAccount(account Account) (*Account, error)

CreateAccount create a new Telegraph account. Most users only need one account, but this can be useful for channel administrators who would like to keep individual author names and profile links for each of their channels. On success, returns an Account object with the regular fields and an additional access_token field.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var account *telegraph.Account //nolint:gochecknoglobals

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

func main() {
	var err error
	account, err = telegraph.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:

func (*Account) CreatePage

func (a *Account) CreatePage(page Page, returnContent bool) (*Page, error)

CreatePage create a new Telegraph page. On success, returns a Page object.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var (
	account *telegraph.Account //nolint:gochecknoglobals
	page    *telegraph.Page    //nolint:gochecknoglobals
	content []telegraph.Node   //nolint:gochecknoglobals
)

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

func main() {
	var err error
	page, err = account.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:

func (*Account) EditAccountInfo

func (a *Account) EditAccountInfo(update Account) (*Account, error)

EditAccountInfo update information about a Telegraph account. Pass only the parameters that you want to edit. On success, returns an Account object with the default fields.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var account *telegraph.Account //nolint:gochecknoglobals

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

func main() {
	var err error
	account, err = account.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:

func (*Account) EditPage

func (a *Account) EditPage(update Page, returnContent bool) (*Page, error)

EditPage edit an existing Telegraph page. On success, returns a Page object.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var (
	account *telegraph.Account //nolint:gochecknoglobals
	page    *telegraph.Page    //nolint:gochecknoglobals
	content []telegraph.Node   //nolint:gochecknoglobals
)

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

func main() {
	var err error
	page, err = account.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:

func (*Account) GetAccountInfo

func (a *Account) GetAccountInfo(fields ...string) (*Account, error)

GetAccountInfo get information about a Telegraph account. Returns an Account object on success.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var account *telegraph.Account //nolint:gochecknoglobals

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

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

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

func (*Account) GetPageList

func (a *Account) GetPageList(offset, limit int) (*PageList, error)

GetPageList get a list of pages belonging to a Telegraph account. Returns a PageList object, sorted by most recently created pages first.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var account *telegraph.Account //nolint:gochecknoglobals

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

func main() {
	list, err := account.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:

func (*Account) RevokeAccessToken

func (a *Account) RevokeAccessToken() (*Account, error)

RevokeAccessToken revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns an Account object with new access_token and auth_url fields.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var account *telegraph.Account

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

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

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

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.

func ContentFormat

func ContentFormat(data interface{}) (n []Node, err error)

ContentFormat transforms data to a DOM-based format to represent the content of the page.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

var content []telegraph.Node //nolint:gochecknoglobals

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
	content, err = telegraph.ContentFormat(data)
	errCheck(err)

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

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.

func GetPage

func GetPage(path string, returnContent bool) (*Page, error)

GetPage get a Telegraph page. Returns a Page object on success.

Example
package main

import (
	"log"

	"gitlab.com/toby3d/telegraph"
)

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

func main() {
	info, err := telegraph.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:

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.

func GetViews

func GetViews(path string, date time.Time) (*PageViews, error)

GetViews get the number of views for a Telegraph article. By default, the total number of page views will be returned. Returns a PageViews object on success.

Example
package main

import (
	"log"
	"time"

	"gitlab.com/toby3d/telegraph"
)

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

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

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

type Response added in v1.1.0

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