notify

package module
v0.0.0-...-31b1bd2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 13 Imported by: 0

README

notify

Go-библиотека для отправки уведомлений через Telegram и Email.

Установка

go get git.gm6.ru/icewind/notify

Telegram

Создание бота
bot, err := notify.NewTelegram("BOT_TOKEN", true) // true — отключить IPv6
if err != nil {
    log.Fatal(err)
}

Второй параметр disableIPV6 принудительно использует TCP4 для соединений с Telegram API — полезно в средах, где IPv6 недоступен или работает нестабильно.

Отправка текстовых сообщений
// Markdown
bot.SendTextMessage(chatID, "*Жирный* и _курсив_")

// HTML
bot.SendHTMLMessage(chatID, "<b>Жирный</b> и <i>курсив</i>")
Отправка фото
// Из файла
bot.SendPhotoFromFile(chatID, "/path/to/image.png", "Подпись")

// По URL
bot.SendPhotoFromURL(chatID, "https://example.com/image.png", "Подпись")

// Из байтов
bot.SendPhotoFromBytes(chatID, imageData, "photo.png", "Подпись")
Отправка документов
// Из файла
bot.SendDocumentFromFile(chatID, "/path/to/report.pdf", "Отчёт за месяц")

// По URL
bot.SendDocumentFromURL(chatID, "https://example.com/report.pdf", "Отчёт")

// Из байтов
bot.SendDocumentFromBytes(chatID, fileData, "report.pdf", "Отчёт")
Доступ к нативному API

Для операций, не покрытых обёрткой, можно получить оригинальный *tgbotapi.BotAPI:

api := bot.GetAPI()
updates, _ := api.GetUpdates(tgbotapi.NewUpdate(0))

Таблицы для Telegram

BuildTelegramTable формирует ASCII-таблицу с рамками, готовую для отправки в <pre> блоке. Заголовки выравниваются по центру, числа — по правому краю, текст — по левому. Корректно работает с кириллицей и другими широкими символами.

rows := [][]string{
    {"Товар", "Цена", "Кол-во"},
    {"Яблоки", "120", "5"},
    {"Бананы", "-90", "30"},
    {"Киви", "+200", "1"},
}

table := notify.BuildTelegramTable(rows)
bot.SendHTMLMessage(chatID, "<pre>" + table + "</pre>")

Результат в Telegram:

+--------+------+--------+
| Товар  | Цена | Кол-во |
+--------+------+--------+
| Яблоки |  120 |      5 |
| Бананы |  -90 |     30 |
| Киви   | +200 |      1 |
+--------+------+--------+

Email

Отправка HTML-письма
auth := notify.SmtpAuth{
    Addr: "smtp.example.com:587",
    Auth: smtp.PlainAuth("", "user@example.com", "password", "smtp.example.com"),
}

from := mail.Address{Name: "Система", Address: "noreply@example.com"}
to := mail.Address{Name: "Иванов", Address: "ivanov@example.com"}

err := notify.SendEmailHTML(auth, "<h1>Отчёт</h1><p>Всё в порядке</p>", "Тема письма", from, to)

Можно указать несколько получателей:

notify.SendEmailHTML(auth, body, subject, from, recipient1, recipient2, recipient3)
Отправка с вложениями

Для писем с вложениями или расширенной настройкой используйте SenndEmailMessage с объектом email.Message:

import "github.com/scorredoira/email"

mes := email.NewMessage("Тема", "Текст письма")
mes.From = from
mes.AddTo(to)
mes.AttachFile("/path/to/file.xlsx")

err := notify.SenndEmailMessage(auth, mes)

Лицензия

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildTelegramTable

func BuildTelegramTable(rows [][]string) string

BuildTelegramBoxTable строит ASCII-таблицу с рамками для Telegram HTML <pre>

func SendEmailHTML

func SendEmailHTML(auth SmtpAuth, message, subject string, from mail.Address, to ...mail.Address) error

func SenndEmailMessage

func SenndEmailMessage(auth SmtpAuth, mes *email.Message) error

Types

type Bot

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

func NewTelegram

func NewTelegram(token string, disableIPV6 bool) (*Bot, error)

func (*Bot) GetAPI

func (s *Bot) GetAPI() *tgbotapi.BotAPI

func (*Bot) SendDocumentFromBytes

func (s *Bot) SendDocumentFromBytes(chatID int64, data []byte, filename string, caption string) (tgbotapi.Message, error)

func (*Bot) SendDocumentFromFile

func (s *Bot) SendDocumentFromFile(chatID int64, filePath string, caption string) (tgbotapi.Message, error)

func (*Bot) SendDocumentFromURL

func (s *Bot) SendDocumentFromURL(chatID int64, fileURL string, caption string) (tgbotapi.Message, error)

func (*Bot) SendHTMLMessage

func (s *Bot) SendHTMLMessage(chatID int64, text string) (tgbotapi.Message, error)

func (*Bot) SendPhotoFromBytes

func (s *Bot) SendPhotoFromBytes(chatID int64, data []byte, filename string, caption string) (tgbotapi.Message, error)

func (*Bot) SendPhotoFromFile

func (s *Bot) SendPhotoFromFile(chatID int64, filePath string, caption string) (tgbotapi.Message, error)

func (*Bot) SendPhotoFromURL

func (s *Bot) SendPhotoFromURL(chatID int64, fileURL string, caption string) (tgbotapi.Message, error)

func (*Bot) SendTextMessage

func (s *Bot) SendTextMessage(chatID int64, text string) (tgbotapi.Message, error)

type SmtpAuth

type SmtpAuth struct {
	Addr string
	Auth smtp.Auth
}