irc

package module
v2.1.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2018 License: MIT Imports: 10 Imported by: 12

README

go-irc

GoDoc Build Status Coverage Status

This package was originally created to only handle message parsing, but has since been expanded to include a small abstraction around a connection and a simple client.

This library is not designed to hide any of the IRC elements from you. If you just want to build a simple chat bot and don't want to deal with IRC in particular, there are a number of other libraries which provide a more full featured client if that's what you're looking for.

This library is meant to stay as simple as possible so it can be a building block for other packages.

This library aims for API compatibility whenever possible. New functions and other additions will most likely not result in a major version increase unless they break the API. This library aims to follow the semver recommendations mentioned on gopkg.in.

Due to complications in how to support x/net/context vs the built-in context package, only go 1.7+ is officially supported.

Import Paths

All development happens on the master branch and when features are considered stable enough, a new release will be tagged.

As a result of this, there are multiple import locations.

  • gopkg.in/irc.v2 should be used to develop against the commits tagged as stable
  • github.com/go-irc/irc should be used to develop against the master branch

Development

In order to run the tests, make sure all submodules are up to date. If you are just using this library, these are not needed.

Example

package main

import (
	"log"
	"net"

	"github.com/belak/irc"
)

func main() {
	conn, err := net.Dial("tcp", "chat.freenode.net:6667")
	if err != nil {
		log.Fatalln(err)
	}

	config := irc.ClientConfig{
		Nick: "i_have_a_nick",
		Pass: "password",
		User: "username",
		Name: "Full Name",
		Handler: irc.HandlerFunc(func(c *irc.Client, m *irc.Message) {
			if m.Command == "001" {
				// 001 is a welcome event, so we join channels there
				c.Write("JOIN #bot-test-chan")
			} else if m.Command == "PRIVMSG" && m.FromChannel() {
				// Create a handler on all messages.
				c.WriteMessage(&irc.Message{
					Command: "PRIVMSG",
					Params: []string{
						m.Params[0],
						m.Trailing(),
					},
				})
			}
		}),
	}

	// Create the client
	client := irc.NewClient(conn, config)
	err = client.Run()
	if err != nil {
		log.Fatalln(err)
	}
}

Major Version Changes

v1

Initial release

v2
  • CTCP messages will no longer be rewritten. The decision was made that this library should pass through all messages without mangling them.
  • Remove Message.FromChannel as this is not always accurate, while Client.FromChannel should always be accurate.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrZeroLengthMessage is returned when parsing if the input is
	// zero-length.
	ErrZeroLengthMessage = errors.New("irc: Cannot parse zero-length message")

	// ErrMissingDataAfterPrefix is returned when parsing if there is
	// no message data after the prefix.
	ErrMissingDataAfterPrefix = errors.New("irc: No message data after prefix")

	// ErrMissingDataAfterTags is returned when parsing if there is no
	// message data after the tags.
	ErrMissingDataAfterTags = errors.New("irc: No message data after tags")

	// ErrMissingCommand is returned when parsing if there is no
	// command in the parsed message.
	ErrMissingCommand = errors.New("irc: Missing message command")
)

Functions

func MaskToRegex added in v1.0.1

func MaskToRegex(rawMask string) (*regexp.Regexp, error)

MaskToRegex converts an irc mask to a go Regexp for more convenient use. This should never return an error, but we have this here just in case.

Types

type Client

type Client struct {
	*Conn
	// contains filtered or unexported fields
}

Client is a wrapper around Conn which is designed to make common operations much simpler.

func NewClient

func NewClient(rw io.ReadWriter, config ClientConfig) *Client

NewClient creates a client given an io stream and a client config.

func (*Client) CapAvailable

func (c *Client) CapAvailable(capName string) bool

CapAvailable allows you to check if a CAP is available on this server. Note that it will not be populated until after the CAP handshake is done, so it is recommended to wait to check this until after a message like 001.

func (*Client) CapEnabled

func (c *Client) CapEnabled(capName string) bool

CapEnabled allows you to check if a CAP is enabled for this connection. Note that it will not be populated until after the CAP handshake is done, so it is recommended to wait to check this until after a message like 001.

func (*Client) CapRequest

func (c *Client) CapRequest(capName string, required bool)

CapRequest allows you to request IRCv3 capabilities from the server during the handshake. The behavior is undefined if this is called before the handshake completes so it is recommended that this be called before Run. If the CAP is marked as required, the client will exit if that CAP could not be negotiated during the handshake.

func (*Client) CurrentNick

func (c *Client) CurrentNick() string

CurrentNick returns what the nick of the client is known to be at this point in time.

func (*Client) FromChannel added in v1.1.0

func (c *Client) FromChannel(m *Message) bool

FromChannel takes a Message representing a PRIVMSG and returns if that message came from a channel or directly from a user.

func (*Client) Run

func (c *Client) Run() error

Run starts the main loop for this IRC connection. Note that it may break in strange and unexpected ways if it is called again before the first connection exits.

func (*Client) RunContext

func (c *Client) RunContext(ctx context.Context) error

RunContext is the same as Run but a context.Context can be passed in for cancelation.

type ClientConfig

type ClientConfig struct {
	// General connection information.
	Nick string
	Pass string
	User string
	Name string

	// Connection settings
	PingFrequency time.Duration
	PingTimeout   time.Duration

	// SendLimit is how frequent messages can be sent. If this is zero,
	// there will be no limit.
	SendLimit time.Duration

	// SendBurst is the number of messages which can be sent in a burst.
	SendBurst int

	// Handler is used for message dispatching.
	Handler Handler
}

ClientConfig is a structure used to configure a Client.

type Conn

type Conn struct {
	*Reader
	*Writer
}

Conn represents a simple IRC client. It embeds an irc.Reader and an irc.Writer.

func NewConn

func NewConn(rw io.ReadWriter) *Conn

NewConn creates a new Conn

type Handler

type Handler interface {
	Handle(*Client, *Message)
}

Handler is a simple interface meant for dispatching a message from a Client connection.

type HandlerFunc

type HandlerFunc func(*Client, *Message)

HandlerFunc is a simple wrapper around a function which allows it to be used as a Handler.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(c *Client, m *Message)

Handle calls f(c, m)

type Message

type Message struct {
	// Each message can have IRCv3 tags
	Tags

	// Each message can have a Prefix
	*Prefix

	// Command is which command is being called.
	Command string

	// Params are all the arguments for the command.
	Params []string
}

Message represents a line parsed from the server

func MustParseMessage

func MustParseMessage(line string) *Message

MustParseMessage calls ParseMessage and either returns the message or panics if an error is returned.

func ParseMessage

func ParseMessage(line string) (*Message, error)

ParseMessage takes a message string (usually a whole line) and parses it into a Message struct. This will return nil in the case of invalid messages.

func (*Message) Copy

func (m *Message) Copy() *Message

Copy will create a new copy of an message

func (*Message) String

func (m *Message) String() string

String ensures this is stringable

func (*Message) Trailing

func (m *Message) Trailing() string

Trailing returns the last argument in the Message or an empty string if there are no args

type Prefix

type Prefix struct {
	// Name will contain the nick of who sent the message, the
	// server who sent the message, or a blank string
	Name string

	// User will either contain the user who sent the message or a blank string
	User string

	// Host will either contain the host of who sent the message or a blank string
	Host string
}

Prefix represents the prefix of a message, generally the user who sent it

func ParsePrefix

func ParsePrefix(line string) *Prefix

ParsePrefix takes an identity string and parses it into an identity struct. It will always return an Prefix struct and never nil.

func (*Prefix) Copy

func (p *Prefix) Copy() *Prefix

Copy will create a new copy of an Prefix

func (*Prefix) String

func (p *Prefix) String() string

String ensures this is stringable

type Reader

type Reader struct {
	// DebugCallback is called for each incoming message. The name of this may
	// not be stable.
	DebugCallback func(string)
	// contains filtered or unexported fields
}

Reader is the incoming side of a connection. The data will be buffered, so do not re-use the io.Reader used to create the irc.Reader.

func NewReader

func NewReader(r io.Reader) *Reader

NewReader creates an irc.Reader from an io.Reader. Note that once a reader is passed into this function, you should no longer use it as it is being used inside a bufio.Reader so you cannot rely on only the amount of data for a Message being read when you call ReadMessage.

func (*Reader) ReadMessage

func (r *Reader) ReadMessage() (*Message, error)

ReadMessage returns the next message from the stream or an error.

type TagValue

type TagValue string

TagValue represents the value of a tag.

func ParseTagValue

func ParseTagValue(v string) TagValue

ParseTagValue parses a TagValue from the connection. If you need to set a TagValue, you probably want to just set the string itself, so it will be encoded properly.

func (TagValue) Encode

func (v TagValue) Encode() string

Encode converts a TagValue to the format in the connection.

type Tags

type Tags map[string]TagValue

Tags represents the IRCv3 message tags.

func ParseTags

func ParseTags(line string) Tags

ParseTags takes a tag string and parses it into a tag map. It will always return a tag map, even if there are no valid tags.

func (Tags) Copy

func (t Tags) Copy() Tags

Copy will create a new copy of all IRC tags attached to this message.

func (Tags) GetTag

func (t Tags) GetTag(key string) (string, bool)

GetTag is a convenience method to look up a tag in the map.

func (Tags) String

func (t Tags) String() string

String ensures this is stringable

type Writer

type Writer struct {
	// DebugCallback is called for each outgoing message. The name of this may
	// not be stable.
	DebugCallback func(line string)
	// contains filtered or unexported fields
}

Writer is the outgoing side of a connection.

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates an irc.Writer from an io.Writer.

func (*Writer) Write

func (w *Writer) Write(line string) error

Write is a simple function which will write the given line to the underlying connection.

func (*Writer) WriteMessage

func (w *Writer) WriteMessage(m *Message) error

WriteMessage writes the given message to the stream

func (*Writer) Writef

func (w *Writer) Writef(format string, args ...interface{}) error

Writef is a wrapper around the connection's Write method and fmt.Sprintf. Simply use it to send a message as you would normally use fmt.Printf.

Jump to

Keyboard shortcuts

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