roxy

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2023 License: GPL-3.0 Imports: 26 Imported by: 0

README

GitHub Repo stars GitHub forks GitHub watchers GitHub code size in bytes

Roxy

Command Handler Abstraction for whatsmeow

Installation

go get github.com/itzngga/Roxy
  • You need ffmpeg binary for generate image/video thumbnail

Get Started

package main

import (
	_ "github.com/itzngga/Roxy/examples/cmd"
	"log"

	"github.com/itzngga/Roxy"
	"github.com/itzngga/Roxy/options"

	"os"
	"os/signal"
	"syscall"
)

func main() {
	app, err := roxy.NewRoxyBase(options.NewDefaultOptions())
	if err != nil {
		log.Fatal(err)
	}

	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c
	app.Shutdown()
}


Config

default
app, err := roxy.NewRoxyBase(options.NewDefaultOptions())
if err != nil {
    log.Fatal(err)
}
custom
type Options struct {
    // HostNumber will use the first available device when null
    HostNumber string
    
    // StoreMode can be "postgres" or "sqlite"
    StoreMode string
    
    // LogLevel: "INFO", "ERROR", "WARN", "DEBUG"
    LogLevel string
    
    // This PostgresDsn Must add when StoreMode equal to "postgres"
    PostgresDsn *PostgresDSN
    
    // This SqliteFile Generate "ROXY.DB" when it null
    SqliteFile string
    
    // WithSqlDB wrap with sql.DB interface
    WithSqlDB *sql.DB
    
    WithCommandLog              bool
    CommandResponseCacheTimeout time.Duration
    SendMessageTimeout          time.Duration
    
    // OSInfo system name in client
    OSInfo string
    
    // LoginOptions constant of ScanQR or PairCode
    LoginOptions LoginOptions
    
    // HistorySync is used to synchronize message history
    HistorySync bool
    // AutoRejectCall allow to auto reject incoming calls
    AutoRejectCall bool
    
    // Bot General Settings
    
    // AllowFromPrivate allow messages from private
    AllowFromPrivate bool
    // AllowFromGroup allow message from groups
    AllowFromGroup bool
    // OnlyFromSelf allow only from self messages
    OnlyFromSelf bool
    // CommandSuggestion allow command suggestion
    CommandSuggestion bool
    // DebugMessage debug incoming message to console
    DebugMessage bool
}
PostgresSQL
from env
package main

import (
	roxy "github.com/itzngga/Roxy"
	_ "github.com/itzngga/Roxy/examples/cmd"
	"github.com/itzngga/Roxy/options"
	"github.com/joho/godotenv"

	"log"

	"os"
	"os/signal"
	"syscall"
)

func init() {
	err := godotenv.Load()
	if err != nil {
		panic(err)
	}
}

func main() {
	// Required ENV
	// PG_HOST : postgresql host
	// PG_PORT : postgresql port
	// PG_USERNAME : postgresql username
	// PG_PASSWORD : postgresql password
	// PG_DATABASE : postgresql database

	opt := options.NewDefaultOptions()
	opt.StoreMode = "postgres"
	opt.PostgresDsn = options.NewPostgresDSN().FromEnv()

	app, err := roxy.NewRoxyBase(opt)
	if err != nil {
		log.Fatal(err)
	}

	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c
	app.Shutdown()
}
default parser
package main

import (
	roxy "github.com/itzngga/Roxy"
	_ "github.com/itzngga/Roxy/examples/cmd"
	"github.com/itzngga/Roxy/options"

	"log"

	"os"
	"os/signal"
	"syscall"
)

func main() {
	pg := options.NewPostgresDSN()
	pg.SetHost("localhost")
	pg.SetPort("4321")
	pg.SetUsername("postgres")
	pg.SetPassword("root123")
	pg.SetDatabase("roxy")

	opt := options.NewDefaultOptions()
	opt.StoreMode = "postgres"
	opt.PostgresDsn = pg

	app, err := roxy.NewRoxyBase(opt)
	if err != nil {
		log.Fatal(err)
	}

	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c
	app.Shutdown()
}
Sqlite
package main

import (
	roxy "github.com/itzngga/Roxy"
	_ "github.com/itzngga/Roxy/examples/cmd"
	"github.com/itzngga/Roxy/options"

	"log"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	opt := options.NewDefaultOptions()
	app, err := roxy.NewRoxyBase(opt)
	if err != nil {
		log.Fatal(err)
	}

	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	<-c
	app.Shutdown()
}

Add a Command

create a simple command with:

command/hello_world.go
package cmd

import (
	"fmt"
	waProto "github.com/go-whatsapp/whatsmeow/binary/proto"
	"github.com/itzngga/Roxy"
	"github.com/itzngga/Roxy/context"
	"time"
)

func init() {
	roxy.Commands.Add(speed)
}

var speed = &roxy.Command{
	Name:        "speed",
	Description: "Testing speed",
	RunFunc: func(ctx *context.Ctx) *waProto.Message {
		t := time.Now()
		ctx.SendReplyMessage("wait...")
		return ctx.GenerateReplyMessage(fmt.Sprintf("Duration: %f seconds", time.Now().Sub(t).Seconds()))
	},
}

Create Question State

example with media question state

package media

import (
	"github.com/itzngga/Leficious/src/cmd/constant"
	"github.com/itzngga/Roxy"
	"github.com/itzngga/Roxy/context"
	"github.com/itzngga/Roxy/util/cli"
	waProto "github.com/go-whatsapp/whatsmeow/binary/proto"
	"log"
)

func init() {
	roxy.Commands.Add(ocr)
}

var ocr = &roxy.Command{
	Name:        "ocr",
	Category:    "media",
	Description: "Scan text on images",
	context: func(ctx *context.Ctx) *waProto.Message {
		var captured *waProto.Message
		ctx.NewUserQuestion().
			CaptureMediaQuestion("Please send/reply a media message", &captured).
			Exec()

		result, err := ctx.Download(captured, false)
		if err != nil {
			log.Fatal(err)
		}
		res := cli.ExecPipeline("tesseract", result, "stdin", "stdout", "-l", "ind", "--oem", "1", "--psm", "3", "-c", "preserve_interword_spaces=1")

		return ctx.GenerateReplyMessage(string(res))
	},
}

Example

currently available example project in Lara

Documentation

DOC

License

GNU

Contribute

Pull Request are pleased to

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Categories types.Embed[string]
View Source
var Commands types.Embed[*Command]
View Source
var GlobalMiddlewares types.Embed[context.MiddlewareFunc]

Functions

This section is empty.

Types

type App

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

func NewRoxyBase

func NewRoxyBase(options *options.Options) (*App, error)

func (*App) AddNewCategory

func (app *App) AddNewCategory(category string)

func (*App) AddNewCommand

func (app *App) AddNewCommand(command Command)

func (*App) AddNewMiddleware

func (app *App) AddNewMiddleware(middleware context.MiddlewareFunc)

func (*App) Client

func (app *App) Client() *whatsmeow.Client

func (*App) ClientJID

func (app *App) ClientJID() waTypes.JID

func (*App) FindMessageByID

func (app *App) FindMessageByID(jid waTypes.JID, id string) *events.Message

func (*App) GetAllChats

func (app *App) GetAllChats() []*events.Message

func (*App) GetChatInJID

func (app *App) GetChatInJID(jid waTypes.JID) []*events.Message

func (*App) GetStatusMessages

func (app *App) GetStatusMessages() []*events.Message

func (*App) HandleEvents

func (app *App) HandleEvents(event interface{})

func (*App) InitializeClient

func (app *App) InitializeClient() error

func (*App) SendMessage

func (app *App) SendMessage(to waTypes.JID, message *waProto.Message, extra ...whatsmeow.SendRequestExtra) (whatsmeow.SendResponse, error)

func (*App) Shutdown

func (app *App) Shutdown()

func (*App) UpsertMessages

func (app *App) UpsertMessages(jid waTypes.JID, message []*events.Message)

type Command

type Command struct {
	Name        string
	Aliases     []string
	Description string

	Category string
	Cache    bool

	HideFromHelp bool
	GroupOnly    bool
	PrivateOnly  bool

	OnlyAdminGroup   bool
	OnlyIfBotAdmin   bool
	AdditionalValues map[string]interface{}

	RunFunc    context.RunFunc
	Middleware context.MiddlewareFunc
}

func (*Command) Validate

func (c *Command) Validate()

type Muxer

type Muxer struct {
	Options              *options.Options                             `json:"options,omitempty"`
	Log                  waLog.Logger                                 `json:"log,omitempty"`
	MessageTimeout       time.Duration                                `json:"message_timeout,omitempty"`
	Categories           *xsync.MapOf[string, string]                 `json:"categories,omitempty"`
	GlobalMiddlewares    *xsync.MapOf[string, context.MiddlewareFunc] `json:"global_middlewares,omitempty"`
	Middlewares          *xsync.MapOf[string, context.MiddlewareFunc] `json:"middlewares,omitempty"`
	Commands             *xsync.MapOf[string, *Command]               `json:"commands,omitempty"`
	CommandResponseCache *xsync.MapOf[string, *waProto.Message]       `json:"command_response_cache,omitempty"`
	QuestionState        *xsync.MapOf[string, *context.QuestionState] `json:"question_state,omitempty"`
	PollingState         *xsync.MapOf[string, *context.PollingState]  `json:"polling_state,omitempty"`
	GroupCache           *xsync.MapOf[string, []*waTypes.GroupInfo]   `json:"group_cache,omitempty"`
	Locals               *xsync.MapOf[string, string]                 `json:"locals,omitempty"`

	QuestionChan    chan *context.QuestionState                           `json:"question_chan,omitempty"`
	PollingChan     chan *context.PollingState                            `json:"polling_chan,omitempty"`
	SuggestionModel *fuzzy.Model                                          `json:"suggestion_model,omitempty"`
	CommandParser   func(str string) (prefix string, cmd string, ok bool) `json:"command_parser,omitempty"`

	types.AppMethods
}

func NewMuxer

func NewMuxer(log waLog.Logger, options *options.Options, appMethods types.AppMethods) *Muxer

func (*Muxer) AddCommand

func (muxer *Muxer) AddCommand(cmd *Command)

func (*Muxer) AddCommandParser

func (muxer *Muxer) AddCommandParser(context func(str string) (prefix string, cmd string, ok bool))

func (*Muxer) AddGlobalMiddleware

func (muxer *Muxer) AddGlobalMiddleware(middleware context.MiddlewareFunc)

func (*Muxer) AddMiddleware

func (muxer *Muxer) AddMiddleware(middleware context.MiddlewareFunc)

func (*Muxer) CacheAllGroup

func (muxer *Muxer) CacheAllGroup()

func (*Muxer) Clean

func (muxer *Muxer) Clean()

func (*Muxer) FindGroupByJid

func (muxer *Muxer) FindGroupByJid(groupJid waTypes.JID) (group *waTypes.GroupInfo, err error)

func (*Muxer) GenerateSuggestionModel

func (muxer *Muxer) GenerateSuggestionModel()

func (*Muxer) GetActiveCommand

func (muxer *Muxer) GetActiveCommand() []*Command

func (*Muxer) GetActiveGlobalMiddleware

func (muxer *Muxer) GetActiveGlobalMiddleware() []context.MiddlewareFunc

func (*Muxer) GetActiveMiddleware

func (muxer *Muxer) GetActiveMiddleware() []context.MiddlewareFunc

func (*Muxer) GetAllGroups

func (muxer *Muxer) GetAllGroups() (group []*waTypes.GroupInfo, err error)

func (*Muxer) IsClientGroupAdmin

func (muxer *Muxer) IsClientGroupAdmin(chat waTypes.JID) (bool, error)

func (*Muxer) IsGroupAdmin

func (muxer *Muxer) IsGroupAdmin(chat waTypes.JID, jid any) (bool, error)

func (*Muxer) RunCommand

func (muxer *Muxer) RunCommand(c *whatsmeow.Client, evt *events.Message)

func (*Muxer) SendEmojiMessage

func (muxer *Muxer) SendEmojiMessage(event *events.Message, emoji string)

func (*Muxer) SuggestCommand

func (muxer *Muxer) SuggestCommand(event *events.Message, prefix, command string)

func (*Muxer) UnCacheOneGroup

func (muxer *Muxer) UnCacheOneGroup(info *events.GroupInfo, joined *events.JoinedGroup)

Directories

Path Synopsis
cmd
cli

Jump to

Keyboard shortcuts

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