tggateway

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2025 License: MIT Imports: 12 Imported by: 0

README

Golang Telegram Gateway API

Zero-dependencies Go package for Telegram Gateway API.

Key features:

  • Full support of Telegram Gateway API.
  • 100% documented.
  • Context support.
  • Type-safe error handling.
  • Immutable response structs.
  • No external dependencies.

Installation

go get github.com/skewb1k/tg-gateway-go

Usage

Basic example:

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	tggateway "github.com/skewb1k/tg-gateway-go"
)

func main() {
	token := "XXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

	client := tggateway.NewClient(token)

	ctx := context.Background()

	sendVerificationMessageResp, err := client.SendVerificationMessage(ctx, &tggateway.SendVerificationMessageParams{
		PhoneNumber: "11111111111",
		CodeLength:  4,
		// or set your generated code.
		// Code: "1234",
	})
	if err != nil {
		// check error type.
		if errors.Is(err, tggateway.ErrPhoneNumberInvalid) {
			// ...handle error
			log.Fatal("phone number is invalid")
		}

		log.Fatalf("send verification message error: %s", err.Error())
	}

	// store recieved request id.
	requestId := sendVerificationMessageResp.RequestId()

	// get code from some user input.
	enteredCode := userInput.Code

	checkVerificationStatusResp, err := client.CheckVerificationStatus(ctx, &tggateway.CheckVerificationStatusParams{
		RequestId: requestId,
		Code:      enteredCode,
	})
	if err != nil {
		log.Fatalf("check verification status error: %s", err.Error())
	}

	switch *checkVerificationStatusResp.VerificationStatus() {
	case tggateway.CODE_VALID:
		fmt.Println("code is valid")
	case tggateway.CODE_INVALID:
		fmt.Println("code is invalid")
	case tggateway.CODE_MAX_ATTEMPTS_EXCEEDED:
		fmt.Println("code max attempts exceeded")
	case tggateway.CODE_EXPIRED:
		fmt.Println("code is expired")
	}
}

Todo list

  • Add example for every method.
  • Add support for custom loggers.
  • Cover with tests.

Contributing

No contributing guidelines yet.

Documentation

Index

Constants

View Source
const (
	CODE_VALID                 string = "code_valid"
	CODE_INVALID                      = "code_invalid"
	CODE_MAX_ATTEMPTS_EXCEEDED        = "code_max_attempts_exceeded"
	CODE_EXPIRED                      = "expired"
	MESSAGE_SENT                      = "sent"
	MESSAGE_READ                      = "read"
	MESSAGE_REVOKED                   = "revoked"
)

Variables

View Source
var (
	ErrCodeInvalid             = errors.New("CODE_INVALID")
	ErrCodeExpired             = errors.New("CODE_EXPIRED")
	ErrCodeLengthRequired      = errors.New("CODE_LENGTH_REQUIRED")
	ErrCodeLengthInvalid       = errors.New("CODE_LENGTH_INVALID")
	ErrCodeMaxAttemptsExceeded = errors.New("CODE_MAX_ATTEMPTS_EXCEEDED")
	ErrPhoneNumberInvalid      = errors.New("PHONE_NUMBER_INVALID")
	ErrPhoneNumberNotFound     = errors.New("PHONE_NUMBER_NOT_FOUND")
	ErrPhoneNumberNotAvailable = errors.New("PHONE_NUMBER_NOT_AVAILABLE")
	ErrPhoneNumberMismatch     = errors.New("PHONE_NUMBER_MISMATCH")
	ErrRequestIdInvalid        = errors.New("REQUEST_ID_INVALID")
	ErrRequestIdRequired       = errors.New("REQUEST_ID_REQUIRED")
	ErrPayloadInvalid          = errors.New("PAYLOAD_INVALID")
	ErrSenderUsernameInvalid   = errors.New("SENDER_USERNAME_INVALID")
	ErrSenderNotVerified       = errors.New("SENDER_NOT_VERIFIED")
	ErrSenderNotOwned          = errors.New("SENDER_NOT_OWNED")
	ErrCallbackUrlInvalid      = errors.New("CALLBACK_URL_INVALID")
	ErrTtlInvalid              = errors.New("TTL_INVALID")
	ErrAccessTokenInvalid      = errors.New("ACCESS_TOKEN_INVALID")
	ErrAccessTokenRequired     = errors.New("ACCESS_TOKEN_REQUIRED")
	ErrMessageAlreadySent      = errors.New("MESSAGE_ALREADY_SENT")
	ErrBalanceNotEnough        = errors.New("BALANCE_NOT_ENOUGH")
	ErrFloodWait               = errors.New("FLOOD_WAIT")
	ErrUnknownMethod           = errors.New("UNKNOWN_METHOD")
)

Functions

This section is empty.

Types

type CheckSendAbilityParams

type CheckSendAbilityParams struct {
	// The phone number for which you want to check our ability to send a verification message, in the E.164 format.
	PhoneNumber string `json:"phone_number"`
}

type CheckVerificationStatusParams

type CheckVerificationStatusParams struct {
	// The unique identifier of the verification request whose status you want to check.
	RequestId string `json:"request_id"`
	// The code entered by the user.
	// If provided, the method checks if the code is valid for the relevant request.
	Code string `json:"code,omitempty"`
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(token string) Client

func (Client) CheckSendAbility

func (c Client) CheckSendAbility(ctx context.Context, params *CheckSendAbilityParams) (*RequestStatus, error)

Use this method to check the ability to send a verification message to the specified phone number. If the ability to send is confirmed, a fee will apply according to the pricing plan. After checking, you can send a verification message using the sendVerificationMessage method, providing the request_id from this response. Within the scope of a request_id, only one fee can be charged. Calling sendVerificationMessage once with the returned request_id will be free of charge, while repeated calls will result in an error. Conversely, calls that don't include a request_id will spawn new requests and incur the respective fees accordingly. Note that this method is always free of charge when used to send codes to your own phone number.

func (Client) CheckVerificationStatus

func (c Client) CheckVerificationStatus(ctx context.Context, params *CheckVerificationStatusParams) (*RequestStatus, error)

Use this method to check the status of a verification message that was sent previously. If the code was generated by Telegram for you, you can also verify the correctness of the code entered by the user using this method. Even if you set the code yourself, it is recommended to call this method after the user has successfully entered the code, passing the correct code in the code parameter, so that we can track the conversion rate of your verifications.

func (Client) RevokeVerificationMessage

func (c Client) RevokeVerificationMessage(ctx context.Context, params *RevokeVerificationMessageParams) (*bool, error)

Use this method to revoke a verification message that was sent previously. Returns True if the revocation request was received. However, this does not guarantee that the message will be deleted. For example, it will not be removed if the recipient has already read it.

func (Client) SendVerificationMessage

func (c Client) SendVerificationMessage(ctx context.Context, params *SendVerificationMessageParams) (*RequestStatus, error)

Use this method to send a verification message. Charges will apply according to the pricing plan for each successful message delivery. Note that this method is always free of charge when used to send codes to your own phone number.

func (Client) VerifyReportIntegrity

func (c Client) VerifyReportIntegrity(r *http.Request) (bool, error)

Use this method to verify the integrity of the delivery report from callback(callback_url). The function retrieves the 'X-Request-Timestamp' and 'X-Request-Signature' headers from the request, reads the body of the HTTP POST request, and forms a data-check-string by concatenating the timestamp and body with a newline character. It then hashes the API token with SHA256, creates an HMAC using the token hash, and compares the computed HMAC signature with the received signature to verify authenticity.

type RequestStatus

type RequestStatus struct {
	// contains filtered or unexported fields
}

func (RequestStatus) DeliveryStatus

func (r RequestStatus) DeliveryStatus() *string

The current status of the message.

func (RequestStatus) DeliveryUpdatedAt

func (r RequestStatus) DeliveryUpdatedAt() *int

The timestamp when the status was last updated.

func (RequestStatus) DeliveryUpdatedAtUTC

func (r RequestStatus) DeliveryUpdatedAtUTC() *time.Time

Delivery status updated at in UTC format.

func (RequestStatus) IsCodeExpired

func (r RequestStatus) IsCodeExpired() bool

True if the code has expired and can no longer be used for verification.

func (RequestStatus) IsCodeInvalid

func (r RequestStatus) IsCodeInvalid() bool

True if the code entered by the user is incorrect.

func (RequestStatus) IsCodeMaxAttemptsExceeded

func (r RequestStatus) IsCodeMaxAttemptsExceeded() bool

True if the maximum number of attempts to enter the code has been exceeded.

func (RequestStatus) IsCodeValid

func (r RequestStatus) IsCodeValid() bool

True if the code entered by the user is correct.

func (RequestStatus) IsMessageRead

func (r RequestStatus) IsMessageRead() bool

True if the message has been read by the recipient.

func (RequestStatus) IsMessageRevoked

func (r RequestStatus) IsMessageRevoked() bool

True if the message has been revoked.

func (RequestStatus) IsMessageSent

func (r RequestStatus) IsMessageSent() bool

True if the message has been sent to the recipient's device(s).

func (RequestStatus) Payload

func (r RequestStatus) Payload() *string

Custom payload if it was provided in the request, 0-256 bytes.

func (RequestStatus) PhoneNumber

func (r RequestStatus) PhoneNumber() string

The phone number to which the verification code was sent, in the E.164 format.

func (RequestStatus) RawJson

func (r RequestStatus) RawJson() []byte

Raw JSON data returned by the API.

func (RequestStatus) RemainingBalance

func (r RequestStatus) RemainingBalance() *float32

Remaining balance in credits. Returned only in response to a request that incurs a charge.

func (RequestStatus) RequestCost

func (r RequestStatus) RequestCost() float32

Total request cost incurred by either checkSendAbility or sendVerificationMessage.

func (RequestStatus) RequestId

func (r RequestStatus) RequestId() string

Unique identifier of the verification request.

func (*RequestStatus) UnmarshalJSON

func (r *RequestStatus) UnmarshalJSON(data []byte) error

func (RequestStatus) VerificationCodeEntered

func (r RequestStatus) VerificationCodeEntered() *string

The code entered by the user.

func (RequestStatus) VerificationStatus

func (r RequestStatus) VerificationStatus() *string

The current status of the verification process.

func (RequestStatus) VerificationUpdatedAt

func (r RequestStatus) VerificationUpdatedAt() *int

The timestamp for this particular status. Represents the time when the status was last updated.

func (RequestStatus) VerificationUpdatedAtUTC

func (r RequestStatus) VerificationUpdatedAtUTC() *time.Time

Verification status updated at in UTC format.

type RevokeVerificationMessageParams

type RevokeVerificationMessageParams struct {
	// The unique identifier of the request whose verification message you want to revoke.
	RequestId string `json:"request_id"`
}

type SendVerificationMessageParams

type SendVerificationMessageParams struct {
	// The phone number to which the verification code was sent, in the E.164 format.
	PhoneNumber string `json:"phone_number"`
	// The unique identifier of a previous request from checkSendAbility.
	// If provided, this request will be free of charge.
	RequestId string `json:"request_id,omitempty"`
	// Username of the Telegram channel from which the code will be sent.
	// The specified channel, if any, must be verified and owned by the same account who owns the Gateway API token.
	SenderUsername string `json:"sender_username,omitempty"`
	// The verification code. Use this parameter if you want to set the verification code yourself.
	// Only fully numeric strings between 4 and 8 characters in length are supported.
	// If this parameter is set, code_length is ignored.
	Code string `json:"code,omitempty"`
	// The length of the verification code if Telegram needs to generate it for you.
	// Supported values are from 4 to 8.
	// This is only relevant if you are not using the code parameter to set your own code.
	// Use the checkVerificationStatus method with the code parameter to verify the code entered by the user.
	CodeLength int `json:"code_length,omitempty"`
	// An HTTPS URL where you want to receive delivery reports related to the sent message, 0-256 bytes.
	CallbackUrl string `json:"callback_url,omitempty"`
	// Custom payload, 0-128 bytes. This will not be displayed to the user, use it for your internal processes.
	Payload string `json:"payload,omitempty"`
	// Time-to-live (in seconds) before the message expires and is deleted.
	// The message will not be deleted if it has already been read.
	// If not specified, the message will not be deleted.
	// Supported values are from 60 to 86400.
	Ttl int `json:"ttl,omitempty"`
}

Jump to

Keyboard shortcuts

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