Where is an example of userbot with getting updates? Is gotd async (Does new updates handle in goroutines)? #574
Answered
by
tdakkota
Mandofskii
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
tdakkota
Aug 12, 2021
Replies: 1 comment 1 reply
-
There is no difference between bot and user with getting updates. Also you can use Example echo userbot: package main
import (
"bufio"
"context"
"fmt"
"os"
"os/signal"
"strings"
"golang.org/x/xerrors"
"github.com/gotd/td/telegram"
"github.com/gotd/td/telegram/auth"
"github.com/gotd/td/telegram/message"
"github.com/gotd/td/tg"
)
func echo(ctx context.Context) error {
d := tg.NewUpdateDispatcher()
// Create client using testing app_id and app_hash.
// You can get it from https://my.telegram.org/apps.
client := telegram.NewClient(telegram.TestAppID, telegram.TestAppHash, telegram.Options{
UpdateHandler: d,
})
// Create message sending helper.
sender := message.NewSender(client.API())
d.OnNewMessage(func(ctx context.Context, e tg.Entities, update *tg.UpdateNewMessage) error {
// Don't echo service message.
msg, ok := update.Message.(*tg.Message)
if !ok {
return nil
}
// Echo received message.
_, err := sender.Answer(e, update).Text(ctx, msg.Message)
return err
})
// Ask code helper.
codeAsk := func(ctx context.Context, sentCode *tg.AuthSentCode) (string, error) {
fmt.Print("code:")
code, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", err
}
code = strings.ReplaceAll(code, "\n", "")
return code, nil
}
return client.Run(ctx, func(ctx context.Context) error {
// Here we create authentication flow.
// auth.Env will get credentials from PHONE and PASSWORD (if needed) environment variables.
a := auth.Env(
"",
auth.CodeAuthenticatorFunc(codeAsk),
)
flow := auth.NewFlow(a, auth.SendCodeOptions{})
if err := client.Auth().IfNecessary(ctx, flow); err != nil {
return xerrors.Errorf("auth: %w", err)
}
// Wait until context cancellation.
<-ctx.Done()
return ctx.Err()
})
}
func main() {
// Cancel context if got Ctrl+C signal.
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
if err := echo(ctx); err != nil {
fmt.Println(err)
os.Exit(1)
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
ernado
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is no difference between bot and user with getting updates.
You need to set
UpdateHandler
field intelegram.Options
and pass it toNewClient
constructor.Also you can use
tg.UpdateDispatcher
to set handlers for specific updates.Example echo userbot: