bertybot

package
v2.318.7 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2021 License: Apache-2.0, MIT Imports: 11 Imported by: 1

Documentation

Overview

Example
package main

import (
	"context"
	"os"
	"time"

	qrterminal "github.com/mdp/qrterminal/v3"
	"go.uber.org/zap"
	"moul.io/u"

	"berty.tech/berty/v2/go/pkg/bertybot"
)

func main() {
	logger, _ := zap.NewDevelopment()
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// init bot
	bot, _ := bertybot.New(
		bertybot.WithLogger(logger.Named("botlib")),                                  // configure a logger
		bertybot.WithDisplayName("example bot"),                                      // bot name
		bertybot.WithInsecureMessengerGRPCAddr("127.0.0.1:9091"),                     // connect to running berty messenger daemon
		bertybot.WithReplay(),                                                        // replay old events as if they are just happening
		bertybot.WithEntityUpdates(),                                                 // include entity updates; i.e., acknowledge
		bertybot.WithFromMyself(),                                                    // trigger hooks for events authored by the bot itself
		bertybot.WithRecipe(bertybot.DebugEventRecipe(logger.Named("debug"))),        // debug events
		bertybot.WithRecipe(bertybot.DelayResponseRecipe(time.Second)),               // add a delay before sending replies
		bertybot.WithRecipe(bertybot.AutoAcceptIncomingContactRequestRecipe()),       // accept incoming contact requests
		bertybot.WithRecipe(bertybot.WelcomeMessageRecipe("welcome to example bot")), // send welcome message to new contacts and new conversations
		bertybot.WithRecipe(bertybot.EchoRecipe("you said: ")),                       // reply to messages with the same message
		bertybot.WithHandler(bertybot.UserMessageHandler, func(ctx bertybot.Context) { // custom handler
			ctx.ReplyString("hello world!")
		}),
	)

	// display link and qr code
	logger.Info("retrieve instance Berty ID", zap.String("pk", bot.PublicKey()), zap.String("link", bot.BertyIDURL()))
	qrterminal.GenerateHalfBlock(bot.BertyIDURL(), qrterminal.L, os.Stdout)

	// signal handling
	go func() {
		u.WaitForCtrlC()
		cancel()
	}()

	// start bot
	bot.Start(ctx)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bot

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

func New

func New(opts ...NewOption) (*Bot, error)

New initializes a new Bot. The order of the passed options may have an impact.

func (*Bot) BertyIDURL

func (b *Bot) BertyIDURL() string

BertyIDURL returns the shareable Berty ID in the form of `https://berty.tech/id#xxx`.

func (*Bot) PublicKey

func (b *Bot) PublicKey() string

PublicKey returns the public key of the messenger node.

func (*Bot) Start

func (b *Bot) Start(ctx context.Context) error

Start starts the main event loop and can be stopped by canceling the passed context.

type CommandFn

type CommandFn func(ctx Context)

type Context

type Context struct {
	// common
	HandlerType  HandlerType
	EventPayload proto.Message `json:"-"` // content of the payload is already available in the parsed payloads
	EventType    messengertypes.StreamEvent_Type
	Context      context.Context
	Client       messengertypes.MessengerServiceClient
	Logger       *zap.Logger
	IsReplay     bool // whether the event is a replayed or a fresh event
	IsMine       bool // whether the bot is the author
	IsAck        bool // whether the event is an ack
	IsNew        bool // whether the event is new or an entity update

	// parsed payloads, depending on the context
	Contact        *messengertypes.Contact      `json:"Contact,omitempty"`
	Conversation   *messengertypes.Conversation `json:"Conversation,omitempty"`
	Interaction    *messengertypes.Interaction  `json:"Interaction,omitempty"`
	Member         *messengertypes.Member       `json:"Member,omitempty"`
	Account        *messengertypes.Account      `json:"Account,omitempty"`
	Device         *messengertypes.Device       `json:"Device,omitempty"`
	ConversationPK string                       `json:"ConversationPK,omitempty"`
	UserMessage    string                       `json:"UserMessage,omitempty"`
	CommandArgs    []string
	// contains filtered or unexported fields
}

Context is the main argument passed to handlers.

func (*Context) ReplyString

func (ctx *Context) ReplyString(text string) error

ReplyString sends a text message on the conversation related to the context. The conversation can be 1-1 or multi-member.

type Handler

type Handler func(ctx Context)

type HandlerType

type HandlerType uint
const (
	UnknownHandler HandlerType = iota

	ErrorHandler
	PreAnythingHandler
	PostAnythingHandler
	EndOfReplayHandler

	ContactUpdatedHandler
	InteractionUpdatedHandler
	ConversationUpdatedHandler
	AccountUpdatedHandler
	MemberUpdatedHandler
	DeviceUpdatedHandler
	NotificationHandler

	IncomingContactRequestHandler
	AcceptedContactHandler
	UserMessageHandler
	NewConversationHandler
	CommandHandler
	CommandNotFoundHandler
)

type NewOption

type NewOption func(*Bot) error

NewOption can be passed to the `New` function to configure the bot.

func WithCommand

func WithCommand(name, description string, handler CommandFn) NewOption

WithCommand registers a new command that can be called with the '/' prefix. If name was already used, the preview command is replaced by the new one.

func WithDisplayName

func WithDisplayName(name string) NewOption

WithDisplayName sets the name of the bot, by default, the name will be named "My Berty Bot".

func WithEntityUpdates added in v2.181.0

func WithEntityUpdates() NewOption

WithEntityUpdates sets the bot to call handlers for new entity events and also for entity updates (acknowledges, etc).

func WithFromMyself added in v2.181.0

func WithFromMyself() NewOption

WithFromMyself sets the bot to call handlers for its own events.

func WithHandler

func WithHandler(typ HandlerType, handler Handler) NewOption

WithHandler append a new Handler for the specified HandlerType.

func WithInsecureMessengerGRPCAddr

func WithInsecureMessengerGRPCAddr(addr string) NewOption

WithInsecureMessengerGRPCAddr tries to open a new gRPC connection against the passed TCP address. It uses grpc.WithInsecure as dialer option and won't check any certificate.

func WithLogger

func WithLogger(logger *zap.Logger) NewOption

WithLogger passes a configured zap Logger.

func WithMessengerClient

func WithMessengerClient(client messengertypes.MessengerServiceClient) NewOption

WithMessengerClient passes an already initialized messenger client.

func WithMessengerGRPCConn

func WithMessengerGRPCConn(cc *grpc.ClientConn) NewOption

WithMessengerGRPCConn configures a new Messenger client from an already initialized gRPC connection.

func WithRecipe

func WithRecipe(recipe Recipe) NewOption

WithRecipe configures the passed recipe.

func WithReplay added in v2.181.0

func WithReplay() NewOption

WithReplay will process replayed (old) events as if they just happened.

type Recipe

type Recipe map[HandlerType][]Handler

Recipe is a set of handlers that performs common behaviors.

func AutoAcceptIncomingContactRequestRecipe

func AutoAcceptIncomingContactRequestRecipe() Recipe

AutoAcceptIncomingContactRequestRecipe makes the bot "click" on the "accept" button automatically.

func AutoAcceptIncomingGroupInviteRecipe

func AutoAcceptIncomingGroupInviteRecipe() Recipe

AutoAcceptIncomingContactRequestRecipe makes the bot "click" on the "accept" button automatically. NOT YET IMPLEMENTED.

func DebugEventRecipe

func DebugEventRecipe(logger *zap.Logger) Recipe

DebugEventRecipe logs every event using zap.DebugLevel.

func DelayResponseRecipe

func DelayResponseRecipe(duration time.Duration) Recipe

DelayResponseRecipe will wait for the specified duration before handling an event.

func EchoRecipe

func EchoRecipe(prefix string) Recipe

EchoRecipe configures the bot to automatically reply any message with the same message. If a prefix is specified, the bot will prefix its response. If a prefix is specified, the bot will ignore incoming messages with that prefix (i.e., a conversation with multiple echo bots). The bot will skip incoming commands (messages starting with a '/').

func SendErrorToClientRecipe

func SendErrorToClientRecipe() Recipe

SendErrorToClientRecipe will send internal errors to the related context (a contact or a conversation). NOT YET IMPLEMENTED.

func WelcomeMessageRecipe

func WelcomeMessageRecipe(text string) Recipe

WelcomeMessageRecipe automatically sends a text message to new contacts.

Jump to

Keyboard shortcuts

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