tgo

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2024 License: MIT Imports: 34 Imported by: 1

README

tgo

Go Reference

Telegram Bot API for Go, with @nekomeowww's flavor, born from varies of Telegram Bot projects:

Features

  • 🎺 Wrapper for commands, callback queries, inline queries
  • 🎆 Any-length callback query data, no more 64-bytes fighting
  • 🎯 Battle-tested dispatcher for each supported updates
  • 👮 Middleware support (guard, permission check, etc.)
  • 🌍 Opt-in i18n support
  • 🚀 Easy to use, easy to extend
  • 🍱 Useful helpers for permission check, message handling, error handling
  • 📦 Dependency injection friendly
  • 📚 More examples and documentation
  • 🛜 Out of the box support for webhooks & polling

🤠 Spec & Documentation

GoDoc: https://godoc.org/github.com/nekomeowww/tgo

Usage

go get -u github.com/nekomeowww/tgo
package main

import (
	"context"
	"os"

	"github.com/nekomeowww/tgo"
)

func main() {
	bot, err := tgo.NewBot(
		tgo.WithToken(os.Getenv("TELEGRAM_BOT_TOKEN")),
	)
	if err != nil {
		panic(err)
	}

	bot.OnCommand("ping", nil, tgo.NewHandler(func(ctx *tgo.Context) (tgo.Response, error) {
		return ctx.NewMessage("pong"), nil
	}))

	bot.Bootstrap(context.TODO())
}

if you use uber/fx too, you can follow this example:

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/nekomeowww/fo"
	"github.com/nekomeowww/tgo"

	"go.uber.org/fx"
)

func NewBot() func() (*tgo.Bot, error) {
	return func() (*tgo.Bot, error) {
		bot, err := tgo.NewBot(tgo.WithToken(os.Getenv("TELEGRAM_BOT_TOKEN")))
		if err != nil {
			return nil, err
		}

		bot.OnCommand("ping", nil, tgo.NewHandler(func(ctx *tgo.Context) (tgo.Response, error) {
    		return ctx.NewMessage("pong"), nil
    	}))

		return bot, nil
	}
}

func Run() func(fx.Lifecycle, *tgo.Bot) {
	return func(lifecycle fx.Lifecycle, bot *tgo.Bot) {
		lifecycle.Append(fx.Hook{
			OnStart: func(ctx context.Context) error {
				go func() {
					_ = bot.Start(ctx)
				}()
				return nil
			},
			OnStop: func(ctx context.Context) error {
				return bot.Stop(ctx)
			},
		})
	}
}

func main() {
	app := fx.New(
		fx.Provide(NewBot()),
		fx.Invoke(Run()),
	)

	app.Run()

	stopCtx, stopCtxCancel := context.WithTimeout(context.Background(), time.Second*15)
	defer stopCtxCancel()

	if err := app.Stop(stopCtx); err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

View Source
const (
	MessageLengthLimit = 4096
)

Variables

This section is empty.

Functions

func EscapeHTMLSymbols

func EscapeHTMLSymbols(str string) string

EscapeHTMLSymbols

< with &lt;
> with &gt;
& with &amp;

func EscapeStringForMarkdownV2

func EscapeStringForMarkdownV2(src string) string

EscapeForMarkdownV2

1. 任何字符码表在 1 到 126 之间的字符都可以加前缀 '\' 字符来转义,在这种情况下,它被视为一个普通字符,而不是标记的一部分。这意味着 '\' 字符通常必须加前缀 '\' 字符来转义。 2. 在 pre 和 code 的实体中,所有 '`' 和 '\' 字符都必须加前缀 '\' 字符转义。 3. 在所有其他地方,字符 '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' 必须加前缀字符 '\' 转义。

https://core.telegram.org/bots/api#formatting-options

func FormatChatID added in v1.0.5

func FormatChatID(chatID int64) string

func FormatFullNameAndUsername added in v1.0.5

func FormatFullNameAndUsername(fullName, username string) string

func FullNameFromFirstAndLastName

func FullNameFromFirstAndLastName(firstName, lastName string) string

func MapChatTypeToChineseText

func MapChatTypeToChineseText(chatType ChatType) string

func MapMemberStatusToChineseText

func MapMemberStatusToChineseText(memberStatus MemberStatus) string

func RemoveHTMLBlocksFromString

func RemoveHTMLBlocksFromString(str string) string

RemoveHTMLBlocksFromString

<any> with ""
</any> with ""

func ReplaceMarkdownTitlesToTelegramBoldElement

func ReplaceMarkdownTitlesToTelegramBoldElement(text string) string

func SplitMessagesAgainstLengthLimitIntoMessageGroups

func SplitMessagesAgainstLengthLimitIntoMessageGroups(originalSlice []string) [][]string

Types

type Bot

type Bot struct {
	*tgbotapi.BotAPI
	*Dispatcher
	// contains filtered or unexported fields
}

func NewBot added in v1.0.1

func NewBot(callOpts ...CallOption) (*Bot, error)

func (*Bot) Bootstrap added in v1.0.5

func (b *Bot) Bootstrap(ctx context.Context)

func (*Bot) Bot

func (b *Bot) Bot() *BotAPI

func (*Bot) MayMakeRequest

func (b *Bot) MayMakeRequest(endpoint string, params tgbotapi.Params) *tgbotapi.APIResponse

func (*Bot) PinChatMessage

func (b *Bot) PinChatMessage(config PinChatMessageConfig) error

func (*Bot) Start

func (b *Bot) Start(ctx context.Context) error

func (*Bot) Stop

func (b *Bot) Stop(ctx context.Context) error

func (*Bot) UnpinChatMessage

func (b *Bot) UnpinChatMessage(config UnpinChatMessageConfig) error

type BotAPI

type BotAPI struct {
	*tgbotapi.BotAPI
	// contains filtered or unexported fields
}

func (*BotAPI) AssignOneCallbackQueryData

func (b *BotAPI) AssignOneCallbackQueryData(route string, data any) (string, error)

func (*BotAPI) AssignOneNopCallbackQueryData

func (b *BotAPI) AssignOneNopCallbackQueryData() (string, error)

func (*BotAPI) DeleteAllDeleteLaterMessages

func (b *BotAPI) DeleteAllDeleteLaterMessages(forUserID int64) error

func (*BotAPI) IsBotAdministrator

func (b *BotAPI) IsBotAdministrator(chatID int64) (bool, error)

func (*BotAPI) IsBotWasBlockedByTheUserErr

func (b *BotAPI) IsBotWasBlockedByTheUserErr(err error) bool

func (*BotAPI) IsCannotInitiateChatWithUserErr

func (b *BotAPI) IsCannotInitiateChatWithUserErr(err error) bool

func (*BotAPI) IsGroupAnonymousBot

func (b *BotAPI) IsGroupAnonymousBot(user *tgbotapi.User) bool

func (*BotAPI) IsUserMemberStatus

func (b *BotAPI) IsUserMemberStatus(chatID int64, userID int64, status []MemberStatus) (bool, error)

func (*BotAPI) MayRequest

func (b *BotAPI) MayRequest(chattable tgbotapi.Chattable) *tgbotapi.APIResponse

func (*BotAPI) MaySend

func (b *BotAPI) MaySend(chattable tgbotapi.Chattable) *tgbotapi.Message

func (*BotAPI) PushOneDeleteLaterMessage

func (b *BotAPI) PushOneDeleteLaterMessage(forUserID int64, chatID int64, messageID int) error

func (*BotAPI) RateLimitForCommand

func (b *BotAPI) RateLimitForCommand(chatID int64, command string, rate int64, perDuration time.Duration) (int64, bool, error)

func (*BotAPI) RemoveInlineKeyboardButtonFromInlineKeyboardMarkupThatMatchesDataWith

func (b *BotAPI) RemoveInlineKeyboardButtonFromInlineKeyboardMarkupThatMatchesDataWith(inlineKeyboardMarkup tgbotapi.InlineKeyboardMarkup, callbackData string) tgbotapi.InlineKeyboardMarkup

func (*BotAPI) ReplaceInlineKeyboardButtonFromInlineKeyboardMarkupThatMatchesDataWith

func (b *BotAPI) ReplaceInlineKeyboardButtonFromInlineKeyboardMarkupThatMatchesDataWith(inlineKeyboardMarkup tgbotapi.InlineKeyboardMarkup, callbackData string, replacedButton tgbotapi.InlineKeyboardButton) tgbotapi.InlineKeyboardMarkup

type CallOption

type CallOption func(*botOptions)

func WithAPIEndpoint

func WithAPIEndpoint(endpoint string) CallOption

func WithDispatcher

func WithDispatcher(dispatcher *Dispatcher) CallOption

func WithI18n

func WithI18n(i18n *i18n.I18n) CallOption

func WithLogger

func WithLogger(logger *logger.Logger) CallOption

func WithQueue

func WithQueue(queue queue.Queue) CallOption

func WithRueidis

func WithRueidis(rueidis rueidis.Client) CallOption

func WithTTLCache

func WithTTLCache(ttlcache ttlcache.TTLCache) CallOption

func WithToken

func WithToken(token string) CallOption

func WithWebhookPort

func WithWebhookPort(port string) CallOption

func WithWebhookURL

func WithWebhookURL(url string) CallOption

type ChatType

type ChatType string
const (
	ChatTypePrivate    ChatType = "private"
	ChatTypeGroup      ChatType = "group"
	ChatTypeSuperGroup ChatType = "supergroup"
	ChatTypeChannel    ChatType = "channel"
)

type Command

type Command struct {
	Command     string
	HelpMessage func(*Context) string
	Handler     Handler
}

type Context

type Context struct {
	Bot    *BotAPI
	Update tgbotapi.Update
	Logger *logger.Logger
	I18n   *i18n.I18n
	// contains filtered or unexported fields
}

func NewContext

func NewContext(bot *tgbotapi.BotAPI, botAPI *BotAPI, update tgbotapi.Update, logger *logger.Logger, i18n *i18n.I18n) *Context

func (*Context) Abort

func (c *Context) Abort()

func (*Context) BindFromCallbackQueryData

func (c *Context) BindFromCallbackQueryData(dst any) error

func (*Context) IsAborted

func (c *Context) IsAborted() bool

func (*Context) IsBotAdministrator

func (c *Context) IsBotAdministrator() (bool, error)

func (*Context) IsUserMemberStatus

func (c *Context) IsUserMemberStatus(userID int64, status []MemberStatus) (bool, error)

func (*Context) Language

func (c *Context) Language() string

func (*Context) NewEditMessageReplyMarkup

func (c *Context) NewEditMessageReplyMarkup(messageID int, replyMarkup tgbotapi.InlineKeyboardMarkup) EditMessageResponse

func (*Context) NewEditMessageText

func (c *Context) NewEditMessageText(messageID int, text string) EditMessageResponse

func (*Context) NewEditMessageTextAndReplyMarkup

func (c *Context) NewEditMessageTextAndReplyMarkup(messageID int, text string, replyMarkup tgbotapi.InlineKeyboardMarkup) EditMessageResponse

func (*Context) NewMessage

func (c *Context) NewMessage(message string) MessageResponse

func (*Context) NewMessageReplyTo

func (c *Context) NewMessageReplyTo(message string, replyToMessageID int) MessageResponse

func (*Context) RateLimitForCommand

func (c *Context) RateLimitForCommand(chatID int64, command string, rate int64, perDuration time.Duration) (int64, bool, error)

func (*Context) T

func (c *Context) T(key string, args ...any) string

func (*Context) UpdateType

func (c *Context) UpdateType() UpdateType

type Dispatcher

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

func NewDispatcher

func NewDispatcher(logger *logger.Logger) *Dispatcher

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(bot *tgbotapi.BotAPI, botAPI *BotAPI, i18n *i18n.I18n, update tgbotapi.Update)

func (*Dispatcher) OnCallbackQuery

func (d *Dispatcher) OnCallbackQuery(route string, h Handler)

func (*Dispatcher) OnCancelCommand

func (d *Dispatcher) OnCancelCommand(cancelHandler func(c *Context) (bool, error), handler Handler)

func (*Dispatcher) OnChannelPost

func (d *Dispatcher) OnChannelPost(handler Handler)

func (*Dispatcher) OnChatMigrationFrom

func (d *Dispatcher) OnChatMigrationFrom(h Handler)

func (*Dispatcher) OnCommand

func (d *Dispatcher) OnCommand(cmd string, commandHelp func(c *Context) string, h Handler)

func (*Dispatcher) OnCommandGroup

func (d *Dispatcher) OnCommandGroup(groupName func(*Context) string, group []Command)

func (*Dispatcher) OnLeftChatMember

func (d *Dispatcher) OnLeftChatMember(h Handler)

func (*Dispatcher) OnMyChatMember

func (d *Dispatcher) OnMyChatMember(handler Handler)

func (*Dispatcher) OnNewChatMember

func (d *Dispatcher) OnNewChatMember(h Handler)

func (*Dispatcher) OnStartCommand

func (d *Dispatcher) OnStartCommand(h Handler)

func (*Dispatcher) Use

func (d *Dispatcher) Use(middleware MiddlewareFunc)

type EditMessageResponse

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

func NewEditMessageReplyMarkup

func NewEditMessageReplyMarkup(chatID int64, messageID int, replyMarkup tgbotapi.InlineKeyboardMarkup) EditMessageResponse

func NewEditMessageText

func NewEditMessageText(chatID int64, messageID int, text string) EditMessageResponse

func NewEditMessageTextAndReplyMarkup

func NewEditMessageTextAndReplyMarkup(chatID int64, messageID int, text string, replyMarkup tgbotapi.InlineKeyboardMarkup) EditMessageResponse

func (EditMessageResponse) WithEditMessageCaptionConfig

func (r EditMessageResponse) WithEditMessageCaptionConfig(config tgbotapi.EditMessageCaptionConfig) EditMessageResponse

func (EditMessageResponse) WithEditMessageLiveLocationConfig

func (r EditMessageResponse) WithEditMessageLiveLocationConfig(config tgbotapi.EditMessageLiveLocationConfig) EditMessageResponse

func (EditMessageResponse) WithEditMessageMediaConfig

func (r EditMessageResponse) WithEditMessageMediaConfig(config tgbotapi.EditMessageMediaConfig) EditMessageResponse

func (EditMessageResponse) WithEditMessageReplyMarkupConfig

func (r EditMessageResponse) WithEditMessageReplyMarkupConfig(config tgbotapi.EditMessageReplyMarkupConfig) EditMessageResponse

func (EditMessageResponse) WithEditMessageTextConfig

func (r EditMessageResponse) WithEditMessageTextConfig(config tgbotapi.EditMessageTextConfig) EditMessageResponse

func (EditMessageResponse) WithInlineReplyMarkup

func (r EditMessageResponse) WithInlineReplyMarkup(inlineMarkup tgbotapi.InlineKeyboardMarkup) EditMessageResponse

func (EditMessageResponse) WithParseModeHTML

func (r EditMessageResponse) WithParseModeHTML() EditMessageResponse

type ExceptionError

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

func NewExceptionError

func NewExceptionError(err error) ExceptionError

func (ExceptionError) Error

func (e ExceptionError) Error() string

func (ExceptionError) WithDeleteLater

func (e ExceptionError) WithDeleteLater(userID int64, chatID int64) ExceptionError

func (ExceptionError) WithEdit

func (e ExceptionError) WithEdit(message *tgbotapi.Message) ExceptionError

func (ExceptionError) WithMessage

func (e ExceptionError) WithMessage(message string) ExceptionError

func (ExceptionError) WithReply

func (e ExceptionError) WithReply(message *tgbotapi.Message) ExceptionError

func (ExceptionError) WithReplyMarkup

func (e ExceptionError) WithReplyMarkup(replyMarkup tgbotapi.InlineKeyboardMarkup) ExceptionError

type HandleFunc

type HandleFunc func(ctx *Context) (Response, error)

type Handler

type Handler interface {
	Handle(c *Context) (Response, error)
}

func NewHandler

func NewHandler(h HandleFunc) Handler

type HandlerGroup

type HandlerGroup interface {
	Install(dispatcher *Dispatcher)
}

type MemberStatus

type MemberStatus string
const (
	MemberStatusCreator       MemberStatus = "creator"
	MemberStatusAdministrator MemberStatus = "administrator"
	MemberStatusMember        MemberStatus = "member"
	MemberStatusRestricted    MemberStatus = "restricted"
	MemberStatusLeft          MemberStatus = "left"
	MemberStatusKicked        MemberStatus = "kicked"
)

type MessageError

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

func NewMessageError

func NewMessageError(message string) MessageError

func (MessageError) Error

func (e MessageError) Error() string

func (MessageError) WithDeleteLater

func (e MessageError) WithDeleteLater(userID int64, chatID int64) MessageError

func (MessageError) WithEdit

func (e MessageError) WithEdit(message *tgbotapi.Message) MessageError

func (MessageError) WithParseModeHTML

func (e MessageError) WithParseModeHTML() MessageError

func (MessageError) WithReply

func (e MessageError) WithReply(message *tgbotapi.Message) MessageError

func (MessageError) WithReplyMarkup

func (e MessageError) WithReplyMarkup(replyMarkup tgbotapi.InlineKeyboardMarkup) MessageError

type MessageResponse

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

func NewMessage

func NewMessage(chatID int64, message string) MessageResponse

func NewMessageReplyTo

func NewMessageReplyTo(chatID int64, message string, replyToMessageID int) MessageResponse

func (MessageResponse) WithDeleteLater

func (r MessageResponse) WithDeleteLater(userID int64, chatID int64) MessageResponse

func (MessageResponse) WithMessageConfig

func (r MessageResponse) WithMessageConfig(config tgbotapi.MessageConfig) MessageResponse

func (MessageResponse) WithParseModeHTML

func (r MessageResponse) WithParseModeHTML() MessageResponse

func (MessageResponse) WithReplyMarkup

func (r MessageResponse) WithReplyMarkup(replyMarkup any) MessageResponse

type MiddlewareFunc

type MiddlewareFunc func(ctx *Context, next func())

type PinChatMessageConfig

type PinChatMessageConfig struct {
	ChatID              int64
	ChannelUsername     string
	MessageID           int
	DisableNotification bool
}

func NewPinChatMessageConfig

func NewPinChatMessageConfig(chatID int64, messageID int) PinChatMessageConfig

type Response

type Response interface{}

type UnpinChatMessageConfig

type UnpinChatMessageConfig struct {
	ChatID          int64
	ChannelUsername string
	MessageID       int
}

func NewUnpinChatMessageConfig

func NewUnpinChatMessageConfig(chatID int64, messageID int) UnpinChatMessageConfig

type UpdateType

type UpdateType string
const (
	UpdateTypeUnknown            UpdateType = "unknown"
	UpdateTypeMessage            UpdateType = "message"
	UpdateTypeEditedMessage      UpdateType = "edited_message"
	UpdateTypeChannelPost        UpdateType = "channel_post"
	UpdateTypeEditedChannelPost  UpdateType = "edited_channel_post"
	UpdateTypeInlineQuery        UpdateType = "inline_query"
	UpdateTypeChosenInlineResult UpdateType = "chosen_inline_result"
	UpdateTypeCallbackQuery      UpdateType = "callback_query"
	UpdateTypeShippingQuery      UpdateType = "shipping_query"
	UpdateTypePreCheckoutQuery   UpdateType = "pre_checkout_query"
	UpdateTypePoll               UpdateType = "poll"
	UpdateTypePollAnswer         UpdateType = "poll_answer"
	UpdateTypeMyChatMember       UpdateType = "my_chat_member"
	UpdateTypeChatMember         UpdateType = "chat_member"
	UpdateTypeLeftChatMember     UpdateType = "left_chat_member"
	UpdateTypeNewChatMembers     UpdateType = "new_chat_members"
	UpdateTypeChatJoinRequest    UpdateType = "chat_join_request"
	UpdateTypeChatMigrationFrom  UpdateType = "chat_migration_from"
	UpdateTypeChatMigrationTo    UpdateType = "chat_migration_to"
)

Directories

Path Synopsis
examples
pkg

Jump to

Keyboard shortcuts

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