tgsupergroup

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2024 License: MIT Imports: 10 Imported by: 0

README

Telegram Supergroup Bot Library


A lightweight library for managing topics in Telegram supergroups. It provides tools for sending messages to topics by name and handling topic creation automatically when needed. This library is designed to simplify interaction with Telegram's topic-based messaging for bots.


Features
  • Send messages to specific topics by name.
  • Automatic topic management: If the target topic doesn't exist, it will be created automatically (requires bot admin privileges).
  • Flexible storage options:
    • In-memory storage for lightweight use cases.
    • Redis-based storage for scalable and persistent topic management.
  • Support for both synchronous and asynchronous message sending.
  • Customizable options for fine-tuning bot behavior.

Installation

Install the library using go get:

go get github.com/https-whoyan/[email protected]

Usage Example

Here’s a quick example of how to use the library to send a message to a specific topic:

package main

import (
	"context"
	"log"

	"github.com/https-whoyan/tgsupergroup"
)

func main() {
	// Replace with your bot's token
	var botToken string // Your token
	ctx := context.Background()

	// Initialize the bot
	bot, err := tgsupergroup.NewBot(botToken)
	if err != nil {
		log.Fatal(err)
	}

	// Replace with your chat's ID
	var yourChatID tgsupergroup.ChatID // Chat ID as int64

	// Send a message to a specific topic by its name
	err = bot.SendMessageToTopicByChatID(
		ctx, yourChatID, "example topic name", "example message",
	)
	if err != nil {
		log.Fatal(err)
	}
}

Project Architecture

The library is structured for clarity and modularity. Below is an overview of the main directories and key files:


├── errors
|     └── Handles custom error definitions used across the library.
├── internal
|     └── Internal package for interacting with the Telegram Bot API. | Includes HTTP request handling and utility functions for marshaling/unmarshaling data. | 
├── types
|     └── Contains all data types used by the library. You can use is from tgsupergroup package
|
├── bot.go
|     └── The main entry point for the library, containing bot initialization and configuration options.
├── send.go
|     └── Implements synchronous message-sending methods for topics and chats.
├── async.go
|     └── Asynchronous versions of message-sending methods with error handling via callback.
└── storage.go
      └── Defines the Storage interface for managing topic-related data, with a Redis-based implementation.


Limitations

While the library validates most requirements programmatically, there are a few conditions to be aware of:

  • The bot must have permission to send messages in the target group.
  • To create topics, the bot must be an administrator in the group with sufficient privileges.
  • If the library cannot find the topic by enumerating ThreadIDs, it will attempt to create the topic. This might fail if the bot does not have the necessary permissions or if Telegram API limits are reached.

Ensure your bot has the required permissions to avoid errors during runtime.


License

This library is licensed under the MIT License. See the LICENSE file for more details.

Documentation

Overview

This package is designed to work with supergroup topics and to send messages to specific topics instead of sending messages to the main supergroup topic.

Use NewBot to initialize the API

Index

Constants

View Source
const (
	ParseModeHTML       = types.ParseModeHTML
	ParseModeMarkdown   = types.ParseModeMarkdown
	ParseModeMarkdownV2 = types.ParseModeMarkdownV2

	SuperGroupType = types.SuperGroupType
)
View Source
const RedisKeyAsset = "TGSGroups:%d" // ChatID

Variables

View Source
var (
	NewTopic      = types.NewTopic
	EmptyThreadID = types.EmptyTopicID
)

Functions

This section is empty.

Types

type Bot

type Bot struct {
	io.Closer
	// contains filtered or unexported fields
}

Main structure for operand topics.

Main method : SendMessageToTopicByChatID

The method calls the telegram API, which is responsible for sending a message to a specific topic, and for that it needs the ThreadID of the chat, not the chat name. To find a id, bot has 3 levels of get this id.

The first one is local, the bot hashes chats and topics in the group.

The second is Storage, which stores the group's tops in any database. The library already implements storage using Redis. Storage is configured with the WithStorage option. To get storage via Redis, use the NewRedisStorage function Otherwise, if nothing is found, the bot finds the right topic by enumerating the IDs. The maximum standard value is 100, but this is Option WithMaxSpamThreadIDs

If the desired chat is not found, a new one is created. Make sure that the bot has enough permissions to create topics.

func NewBot

func NewBot(token string, opts ...Option) (*Bot, error)

NewBot Returns an instance of the bot, look for Option's above

func NewBotsGroup added in v1.0.3

func NewBotsGroup(tokens []string, opts ...Option) (*Bot, error)

func (*Bot) AsyncSendMessage

func (b *Bot) AsyncSendMessage(ctx context.Context, onError ErrorHandlerFunc, messageText string, args ...interface{})

Async version of SendMessage

func (*Bot) AsyncSendMessageToChat

func (b *Bot) AsyncSendMessageToChat(
	ctx context.Context, onError ErrorHandlerFunc, chatID ChatID, messageText string, args ...interface{},
)

Async version of SendMessageToChat

func (*Bot) AsyncSendMessageToTopic

func (b *Bot) AsyncSendMessageToTopic(
	ctx context.Context, onError ErrorHandlerFunc, topicName TopicName, messageText string, args ...interface{},
)

Async version of SendMessageToTopic

func (*Bot) AsyncSendMessageToTopicByChatID

func (b *Bot) AsyncSendMessageToTopicByChatID(
	ctx context.Context, onError ErrorHandlerFunc,
	chatID ChatID, topicName TopicName, messageText string, args ...interface{},
)

Async version of SendMessageToTopicByChatID

func (*Bot) AsyncSendMessageToTopicByID

func (b *Bot) AsyncSendMessageToTopicByID(
	ctx context.Context, onError ErrorHandlerFunc,
	chatID ChatID, topicID TopicThreadID, messageText string, args ...interface{},
)

Async version of SendMessageToTopicByID

func (*Bot) Close

func (b *Bot) Close() error

func (*Bot) PreloadChatTopics

func (b *Bot) PreloadChatTopics(ctx context.Context, chatIDs ...ChatID) error

Preload Chat Topics using Storage

func (*Bot) SendMessage

func (b *Bot) SendMessage(ctx context.Context, messageText string, args ...interface{}) error

Just send message to prepared chatID

func (*Bot) SendMessageToChat

func (b *Bot) SendMessageToChat(ctx context.Context, chatID ChatID, messageText string, args ...interface{}) error

Just send message to chatID

func (*Bot) SendMessageToTopic

func (b *Bot) SendMessageToTopic(
	ctx context.Context, topicName TopicName, messageText string, args ...interface{},
) error

Use this method if you provided chatID in the options during initialization.

Otherwise, use SendMessageToTopicByChatID method.

func (*Bot) SendMessageToTopicByChatID

func (b *Bot) SendMessageToTopicByChatID(
	ctx context.Context, chatID ChatID, topicName TopicName, messageText string, args ...interface{},
) error

Sends a message to a group's topic by its name.

func (*Bot) SendMessageToTopicByID

func (b *Bot) SendMessageToTopicByID(
	ctx context.Context, chatID ChatID, topicID TopicThreadID, messageText string, args ...interface{},
) error

May be useful if you have a threadID

type Chat

type Chat = types.Chat

type ChatID

type ChatID = types.ChatID

type ErrorHandlerFunc

type ErrorHandlerFunc = func(ctx context.Context, err error)

Handler type for async versions of sending messages

type Option

type Option func(*Bot)

List: WithHTTPClient, WithStorage, WithChatID, WithMaxSpamThreadIDs, WithContext, WithParseMode, WithBotName

func WithChatID

func WithChatID(chatID ChatID) Option

Configure default chatID, if you need to operand only with this chat.

func WithContext

func WithContext(ctx context.Context) Option

Configure context.Context. Default: context.Background

func WithHTTPClient

func WithHTTPClient(httpCli *http.Client) Option

Configure http.Client. Default: http.DefaultClient

func WithMaxSpamThreadIDs

func WithMaxSpamThreadIDs(maxThreadIDs uint) Option

Configure max attemps to find a need topic. Default: 100

func WithParseMode

func WithParseMode(m ParseMode) Option

Configure ParseMode. Default: ParseModeMarkdownV2

func WithStorage

func WithStorage(cacher Storage) Option

Configure Storage to save TopicThreadID. Use NewRedisStorage if you're comfortable using redis.

May be nil. (No Storage)

type ParseMode

type ParseMode = types.ParseMode

type Storage

type Storage interface {
	GetAll(ctx context.Context, chatID ChatID) (*Topics, error)
	Save(ctx context.Context, topic *Topic) error
	GetByName(ctx context.Context, chatID ChatID, name TopicName) (*Topic, error)
}

func NewRedisStorage

func NewRedisStorage(client redis.UniversalClient) Storage

Initiates Storage using the redis.Client

type Topic

type Topic = types.Topic

type TopicName

type TopicName = types.TopicName

type TopicThreadID

type TopicThreadID = types.TopicThreadID

type Topics

type Topics = types.Topics

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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