tgbot

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2022 License: MIT Imports: 11 Imported by: 0

README

go-tgbot

Go Reference Go Report Card

Wrapped telegram-bot-api to create telegram bot faster.

1. Installation

Run the following command under your project:

go get -u github.com/imzhongqi/go-tgbot

2. Example

package main

import (
	"log"
	"time"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/imzhongqi/go-tgbot"
	"github.com/panjf2000/ants/v2"
)

func main() {
	api, err := tgbotapi.NewBotAPI("xxx")
	if err != nil {
		panic(err)
	}

	pool, err := ants.NewPool(10000, ants.WithExpiryDuration(10*time.Second))
	if err != nil {
		panic(err)
	}

	bot := tgbot.NewBot(api,
		tgbot.WithTimeout(2*time.Second),
		
		// tgbot.WithWorkersNum(-1), // use can use unlimited workers.
		
		tgbot.WithWorkersPool(tgbot.NewAntsPool(pool)),

		tgbot.WithUpdatesHandler(func(ctx *tgbot.Context) {
			err := ctx.ReplyText(ctx.Message().Text, func(c *tgbotapi.MessageConfig) {
				c.ReplyToMessageID = ctx.Message().MessageID
			})
			if err != nil {
				log.Printf("reply text error: %s", err)
			}
		}),

		tgbot.WithUndefinedCmdHandler(func(ctx *tgbot.Context) error {
			return ctx.ReplyMarkdown("*unknown command*", tgbot.WithDisableWebPagePreview(false))
		}),

		tgbot.WithErrorHandler(func(err error) {
			log.Println(err)
		}),
	)
	
	bot.AddCommands(
		tgbot.NewCommand("ping", "ping the bot", func(ctx *tgbot.Context) error {
			return ctx.ReplyMarkdown("pong")
		},
			tgbot.WithHide(true),
			tgbot.WithScopes(
				tgbot.CommandScopeDefault(),
				tgbot.CommandScopeAllGroupChats(),
				tgbot.CommandScopeChat(100),
			),
		),
	)
	if err := bot.Run(); err != nil {
		panic(err)
	}
}

Documentation

Index

Examples

Constants

View Source
const (
	ScopeTypeDefault               = "default"
	ScopeTypeAllPrivateChats       = "all_private_chats"
	ScopeTypeAllGroupChats         = "all_group_chats"
	ScopeTypeAllChatAdministrators = "all_chat_administrators"
	ScopeTypeChat                  = "chat"
	ScopeTypeChatAdministrators    = "chat_administrators"
	ScopeTypeChatMember            = "chat_member"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Bot

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

Bot wrapper the telegram bot.

func NewBot

func NewBot(api *tgbotapi.BotAPI, opts ...Option) *Bot

NewBot new a telegram bot.

Example
api, err := tgbotapi.NewBotAPI("xxx")
if err != nil {
	panic(err)
}

pool, err := ants.NewPool(10000, ants.WithExpiryDuration(10*time.Second))
if err != nil {
	panic(err)
}

bot := tgbot.NewBot(api,
	tgbot.WithTimeout(2*time.Second),

	tgbot.WithWorkersPool(tgbot.NewAntsPool(pool)),

	tgbot.WithUpdatesHandler(func(ctx *tgbot.Context) {
		err := ctx.ReplyText(ctx.Message().Text, func(c *tgbotapi.MessageConfig) {
			c.ReplyToMessageID = ctx.Message().MessageID
		})
		if err != nil {
			log.Printf("reply text error: %s", err)
		}
	}),

	tgbot.WithUndefinedCmdHandler(func(ctx *tgbot.Context) error {
		return ctx.ReplyMarkdown("*unknown command*", tgbot.WithDisableWebPagePreview(false))
	}),

	tgbot.WithErrorHandler(func(err error) {
		log.Println(err)
	}),
)
bot.AddCommands(
	tgbot.NewCommand("ping", "ping the bot", func(ctx *tgbot.Context) error {
		return ctx.ReplyMarkdown("pong")
	},
		tgbot.WithHide(true),
		tgbot.WithScopes(
			tgbot.CommandScopeDefault(),
			tgbot.CommandScopeAllGroupChats(),
			tgbot.CommandScopeChat(100),
		),
	),
)
if err := bot.Run(); err != nil {
	panic(err)
}
Output:

func (*Bot) AddCommands

func (bot *Bot) AddCommands(commands ...*Command)

AddCommands add commands to the bot.

func (*Bot) ClearBotCommands

func (bot *Bot) ClearBotCommands() error

func (*Bot) Commands

func (bot *Bot) Commands() map[string]*Command

func (*Bot) CommandsWithScope

func (bot *Bot) CommandsWithScope() map[CommandScope][]*Command

func (*Bot) Run

func (bot *Bot) Run() error

func (*Bot) Stop

func (bot *Bot) Stop() context.Context

type Command

type Command struct {
	Name        string
	Description string
	Handler     Handler
	// contains filtered or unexported fields
}

Command is telegram command.

func NewCommand

func NewCommand(name, desc string, handler Handler, opts ...CommandOption) *Command

func (*Command) Hide

func (c *Command) Hide() bool

func (*Command) Scopes

func (c *Command) Scopes() []CommandScope

func (Command) String

func (c Command) String() string

type CommandOption

type CommandOption func(cmd *Command)

func WithHide

func WithHide(v bool) CommandOption

func WithScopes

func WithScopes(scopes ...CommandScope) CommandOption

type CommandScope

type CommandScope interface {
	Type() string
	ChatID() int64
	UserID() int64
	LanguageCode() string
}

CommandScope is command scope for telegram.

func CommandScopeAllChatAdministrators

func CommandScopeAllChatAdministrators(lc ...string) CommandScope

CommandScopeAllChatAdministrators represents the scope of bot commands, covering all group and supergroup chat administrators.

func CommandScopeAllGroupChats

func CommandScopeAllGroupChats(lc ...string) CommandScope

CommandScopeAllGroupChats represents the scope of bot commands, covering all group and supergroup chats.

func CommandScopeAllPrivateChats

func CommandScopeAllPrivateChats(lc ...string) CommandScope

CommandScopeAllPrivateChats represents the scope of bot commands, covering all private chats.

func CommandScopeChat

func CommandScopeChat(chatID int64, lc ...string) CommandScope

CommandScopeChat represents the scope of bot commands, covering a specific chat.

func CommandScopeChatAdministrators

func CommandScopeChatAdministrators(chatID int64, lc ...string) CommandScope

CommandScopeChatAdministrators represents the scope of bot commands, covering all administrators of a specific group or supergroup chat.

func CommandScopeChatMember

func CommandScopeChatMember(chatID, userID int64, lc ...string) CommandScope

CommandScopeChatMember represents the scope of bot commands, covering a specific member of a group or supergroup chat.

func CommandScopeDefault

func CommandScopeDefault(lc ...string) CommandScope

CommandScopeDefault represents the default scope of bot commands.

func CommandScopeNoScope

func CommandScopeNoScope() CommandScope

type Context

type Context struct {
	context.Context

	*tgbotapi.BotAPI
	// contains filtered or unexported fields
}

func (*Context) Command

func (c *Context) Command() string

Command return command name if message is non-nil.

func (*Context) CommandArgs

func (c *Context) CommandArgs() string

CommandArgs return command arguments if message is non-nil.

func (*Context) FromChat

func (c *Context) FromChat() *tgbotapi.Chat

func (*Context) IsCommand

func (c *Context) IsCommand() bool

IsCommand report whether the current message is a command.

func (*Context) Message

func (c *Context) Message() *tgbotapi.Message

func (*Context) ReplyHTML

func (c *Context) ReplyHTML(text string, opts ...MessageOption) error

ReplyHTML reply to the current chat, text format is HTML.

func (*Context) ReplyMarkdown

func (c *Context) ReplyMarkdown(text string, opts ...MessageOption) error

ReplyMarkdown reply to the current chat, text format is markdown.

func (*Context) ReplyText

func (c *Context) ReplyText(text string, opts ...MessageOption) error

ReplyText reply to the current chat.

func (*Context) SendReply

func (c *Context) SendReply(chat tgbotapi.Chattable) error

SendReply send reply.

func (*Context) SentFrom

func (c *Context) SentFrom() *tgbotapi.User

func (*Context) Update

func (c *Context) Update() *tgbotapi.Update

func (*Context) WithContext

func (c *Context) WithContext(ctx context.Context) *Context

WithContext clone a Context for use in other goroutine.

type ErrHandler

type ErrHandler func(err error)

ErrHandler error handler.

type Handler

type Handler func(ctx *Context) error

Handler command handler.

type MessageOption

type MessageOption func(c *tgbotapi.MessageConfig)

func WithChatId

func WithChatId(chatId int64) MessageOption

WithChatId set message chat id.

func WithDisableWebPagePreview

func WithDisableWebPagePreview(disable bool) MessageOption

WithDisableWebPagePreview disable web page preview.

func WithHTML

func WithHTML() MessageOption

WithHTML set parse mode to html.

func WithInlineKeyboardMarkup

func WithInlineKeyboardMarkup(markup tgbotapi.InlineKeyboardMarkup) MessageOption

WithInlineKeyboardMarkup set inline keyboard.

func WithKeyboardMarkup

func WithKeyboardMarkup(markup tgbotapi.ReplyKeyboardMarkup) MessageOption

WithKeyboardMarkup set keyboard.

func WithMarkdown

func WithMarkdown() MessageOption

WithMarkdown set parse mode to markdown.

func WithMarkdownV2

func WithMarkdownV2() MessageOption

WithMarkdownV2 set parse mode to markdown v2.

func WithRemoveKeyboard

func WithRemoveKeyboard(markup tgbotapi.ReplyKeyboardRemove) MessageOption

WithRemoveKeyboard remove keyboard.

type Option

type Option func(o *options)

func WithBufferSize

func WithBufferSize(size int) Option

WithBufferSize set the buffer size for receive updates.

func WithContext

func WithContext(ctx context.Context) Option

WithContext with the context.

func WithDisableAutoSetupCommands

func WithDisableAutoSetupCommands(v bool) Option

WithDisableAutoSetupCommands disable auto setup telegram commands.

func WithDisableHandleAllUpdateOnStop

func WithDisableHandleAllUpdateOnStop(v bool) Option

WithDisableHandleAllUpdateOnStop disable handle all updates on stop.

func WithErrorHandler

func WithErrorHandler(h ErrHandler) Option

WithErrorHandler set error handler.

func WithGetUpdatesAllowedUpdates

func WithGetUpdatesAllowedUpdates(v ...string) Option

WithGetUpdatesAllowedUpdates set allowed updates.

func WithGetUpdatesLimit

func WithGetUpdatesLimit(limit int) Option

WithGetUpdatesLimit set the get updates limit.

func WithGetUpdatesTimeout

func WithGetUpdatesTimeout(timeout int) Option

WithGetUpdatesTimeout set the get updates updateTimeout, timeout unit is seconds, max is 50 second.

func WithPanicHandler

func WithPanicHandler(h PanicHandler) Option

WithPanicHandler set panic handler.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout set context timeout.

func WithUndefinedCmdHandler

func WithUndefinedCmdHandler(h Handler) Option

WithUndefinedCmdHandler set how to handle undefined commands.

func WithUpdatesHandler

func WithUpdatesHandler(handler UpdatesHandler) Option

WithUpdatesHandler set the updates handler.

func WithWorkersNum

func WithWorkersNum(n int) Option

WithWorkersNum set the number of workers to process updates.

func WithWorkersPool

func WithWorkersPool(p Pool) Option

WithWorkersPool set the worker pool for execute handler if the workersPool is non-nil.

type PanicHandler

type PanicHandler func(*Context, interface{})

PanicHandler is panic handler.

type Pool

type Pool interface {
	IsClosed() bool
	Go(f func()) error
}

func NewAntsPool

func NewAntsPool(p *ants.Pool) Pool

type UpdatesHandler

type UpdatesHandler func(ctx *Context)

UpdatesHandler handler another update.

Jump to

Keyboard shortcuts

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