go-telegram / bot

Telegram Bot API Go framework
MIT License
507 stars 46 forks source link

Multiline text #5

Closed ryszard-suchocki closed 1 year ago

ryszard-suchocki commented 1 year ago

Hello, I want to ask about long text/byte array submissions. How to correctly encode it, so it can be sent via your library. I intend to create a bot that invokes some specific commands defined in the YAML config file. The exec output is a byte array and I'm unable to predict its content (which means not only whitespace, and unprintable signs but some fancy/exotic UTF signs can occur).

Can you help me?

negasus commented 1 year ago

Do you want send bytes data to users in telegram?

ryszard-suchocki commented 1 year ago

Hello, I want to send a text (the output of the command) which is returned as a byte array (docs)

negasus commented 1 year ago

This example will sent a result of command on any message to the bot

package main

import (
    "bytes"
    "context"
    "log"
    "os"
    "os/exec"
    "os/signal"

    "github.com/go-telegram/bot"
    "github.com/go-telegram/bot/models"
)

func main() {
    opts := []bot.Option{
        bot.WithDefaultHandler(handler),
    }

    b := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...)

    ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
    defer cancel()

    b.Start(ctx)
}

func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
    buf := bytes.NewBuffer(nil)

    cmd := exec.Command("pwd")
    cmd.Stdout = buf

    err := cmd.Run()
    if err != nil {
        log.Printf("error run command, %v", err)
        return
    }

    b.SendMessage(ctx, &bot.SendMessageParams{
        ChatID: update.Message.Chat.ID,
        Text:   buf.String(),
    })
}
ryszard-suchocki commented 1 year ago

Thank you!!