### Setup on Registration Callback Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Sets up a callback to be executed upon successful registration with the IRC server. This is commonly used to join channels or perform initial setup tasks. ```APIDOC ## Setup on Registration ### Description Sets up a callback to be executed upon successful registration with the IRC server. This is commonly used to join channels or perform initial setup tasks. ### Example ```go conn.AddCallback("REGISTRATION", func(msg ircmsg.Message) { fmt.Println("Successfully registered!") conn.Join("#channel") }) conn.AddCallback("001", func(msg ircmsg.Message) { // Also called on successful registration }) ``` ``` -------------------------------- ### Setup Callback on Registration Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Registers callbacks to be executed upon successful IRC registration. Includes examples for general registration and specific numeric replies like '001'. ```go conn.AddCallback("REGISTRATION", func(msg ircmsg.Message) { fmt.Println("Successfully registered!") conn.Join("#channel") }) conn.AddCallback("001", func(msg ircmsg.Message) { // Also called on successful registration }) ``` -------------------------------- ### Go Function Example Usage Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/00-START-HERE.md Provides a placeholder for real-world usage code examples that should accompany function documentation. This ensures users can easily adapt and implement the functionality. ```go // Real usage code ``` -------------------------------- ### Clone and Read Project Documentation Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/MANIFEST.md Clone the repository and use command-line tools to read the generated documentation files, starting with the index. ```bash # Clone the repo git clone https://github.com/ergochat/irc-go # Read the reference cat output/INDEX.md # Start here cat output/README.md # Architecture overview cat output/api-reference/* # Detailed API docs cat output/configuration.md # Setup options cat output/errors.md # Error handling ``` -------------------------------- ### Basic IRC Bot Implementation Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md A fundamental example of setting up an IRC bot, connecting to a server, and registering callbacks for channel joins and private messages. ```go conn := &ircevent.Connection{ Server: "irc.libera.chat:6667", Nick: "mybot", User: "bot", RealName: "My Bot", } if err := conn.Connect(); err != nil { log.Fatal(err) } conn.AddCallback("REGISTRATION", func(msg ircmsg.Message) { conn.Join("#channel") }) conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { text := msg.Params[1] if strings.HasPrefix(text, "!") { target := conn.GetReplyTarget(msg) conn.Privmsg(target, "Command: "+text) } }) go conn.Loop() ``` -------------------------------- ### Initialize and Connect IRC Client Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Initialize an ircevent.Connection with server details and nickname, then connect to the IRC server. Start the main loop in a goroutine. ```go conn := &ircevent.Connection{Server: "irc.example.com:6667", Nick: "mybot"} conn.Connect() go conn.Loop() ``` -------------------------------- ### Go Function Example Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/INDEX.md Demonstrates a basic Go function definition within a fenced code block. ```go func Example() {} ``` -------------------------------- ### Message Tag Setter Example Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/INDEX.md Example of setting a tag on an IRC message object. Includes source file reference. ```go func (msg *Message) SetTag(tagName, tagValue string) { // ... code ... } // Source: ircmsg/message.go:104 ``` -------------------------------- ### Go Function Parameter Table Example Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/00-START-HERE.md Demonstrates how to present function parameters in a table format, specifying parameter name, type, requirement, default value, and a description of its purpose. ```go | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | param | type | yes/no | value | What it does | ``` -------------------------------- ### Example Usage of IRC Reader Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Demonstrates how to create an IRC Reader and continuously read lines from an IRC server connection. Handles potential errors during reading. ```go conn, _ := net.Dial("tcp", "irc.example.com:6667") reader := ircreader.NewIRCReader(conn) // Read lines for { line, err := reader.ReadLine() if err != nil { break } fmt.Println(string(line)) } ``` -------------------------------- ### Go Function Signature Example Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/00-START-HERE.md Illustrates the standard format for defining a Go function within API documentation, including parameters, types, and return values. ```go func FunctionName(param type) (result type) ``` -------------------------------- ### Connect to IRC Server and Register Callbacks Source: https://github.com/ergochat/irc-go/blob/master/ircevent/README.markdown Illustrates basic connection setup, TLS usage, nickname setting, and registering callbacks for connection events and PRIVMSG. Ensure to handle the error from Connect and call Loop to process messages. ```go irc := ircevent.Connection{ Server: "testnet.ergo.chat:6697", UseTLS: true, Nick: "ircevent-test", Debug: true, RequestCaps: []string{"server-time", "message-tags"}, } irc.AddConnectCallback(func(e ircmsg.Message) { irc.Join("#ircevent-test") }) irc.AddCallback("PRIVMSG", func(event ircmsg.Message) { // event.Source is the source; // event.Params[0] is the target (the channel or nickname the message was sent to) // and event.Params[1] is the message itself }); err := irc.Connect() if err != nil { log.Fatal(err) } irc.Loop() ``` -------------------------------- ### Example: Reply to a PRIVMSG Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Demonstrates how to use GetReplyTarget to send a reply to a received PRIVMSG. Ensures a valid target is determined before sending the reply. ```go conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { target := conn.GetReplyTarget(msg) if target != "" { conn.Privmsg(target, "Reply to message") } }) ``` -------------------------------- ### Connect to IRC Server Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Initiates a connection to the IRC server, handling validation, TCP/TLS setup, goroutine spawning, authentication, capability negotiation, and waiting for successful registration (RPL_WELCOME). ```go conn := &ircevent.Connection{ Server: "irc.example.com:6667", Nick: "mybot", User: "bot", RealName: "My Bot", } err := conn.Connect() if err != nil { log.Fatal("Failed to connect:", err) } ``` -------------------------------- ### Join Channel Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a JOIN command to join a specified channel. The channel name should typically start with '#'. ```go conn.Join("#channel") ``` -------------------------------- ### Parse and Render Formatted IRC Text Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircfmt.md This example demonstrates parsing raw IRC formatted text into chunks and then rendering these chunks into an HTML-like format. It also shows how to escape and unescape IRC formatting for storage and later use. ```go // Parse and render formatted IRC text raw := "Welcome \x02\x034admin\x0f! You have \x031,8new\x0f messages." chunks := ircfmt.Split(raw) for _, chunk := range chunks { if chunk.Bold { fmt.Print("") } if chunk.ForegroundColor.IsSet { fmt.Printf("", chunk.ForegroundColor.Value) } fmt.Print(chunk.Content) if chunk.ForegroundColor.IsSet || chunk.Bold { fmt.Print("") } } // Alternative: use escaped notation for storage escaped := ircfmt.Escape(raw) // escaped == "Welcome $b$c[red]admin$r! You have $c[red,white]new$r messages." stored := escaped // Later, send it: realMsg := ircfmt.Unescape(stored) client.Privmsg("#channel", realMsg) ``` -------------------------------- ### IRC Connection Configuration Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/INDEX.md Defines common settings for establishing an IRC connection, including server details, authentication, TLS, SASL, and requested capabilities. Use this for basic client setup. ```go conn := &ircevent.Connection{ Server: "irc.example.com:6697", Nick: "botname", User: "bot", RealName: "My Bot", UseTLS: true, UseSASL: true, SASLLogin: "username", SASLPassword: "password", RequestCaps: []string{"message-tags", "account-tag"}, EnableCTCP: true, Debug: true, } ``` -------------------------------- ### Initialize IRC Reader with Custom Buffer Sizes Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Initializes a `Reader` instance with specified initial and maximum buffer sizes. This allows for reusing an existing `Reader` struct. Ensure `conn` is a valid `io.Reader`, `initialSize` is the starting buffer capacity, and `maxSize` is the hard limit. ```go var reader ircreader.Reader reader.Initialize(conn, 1024, 16384) ``` -------------------------------- ### Handling Formatted IRC Text Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Provides examples for parsing and unescaping formatted IRC text using the ircfmt package. This includes handling bold and color codes. ```go // Parse formatted IRC message chunks := ircfmt.Split(message) for _, chunk := range chunks { if chunk.Bold { fmt.Print("") } fmt.Print(chunk.Content) if chunk.Bold { fmt.Print("") } } // Send formatted message msg := "This is $bbold$b and $c[red]red$r text" raw := ircfmt.Unescape(msg) conn.Privmsg("#channel", raw) ``` -------------------------------- ### Get IRCv3 Labeled Response Synchronously Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Use `GetLabeledResponse` to send a command and synchronously wait for its labeled response. It returns a `Batch` with the server's reply or `nil` on timeout. Errors include `NoLabeledResponse` or `CapabilityNotNegotiated`. ```go func (irc *Connection) GetLabeledResponse(tags map[string]string, command string, params ...string) (batch *Batch, err error) ``` ```go batch, err := conn.GetLabeledResponse(nil, "MODE", "#channel") if err != nil { log.Printf("mode lookup failed: %v", err) return } for _, item := range batch.Items { fmt.Println(item.Params) } ``` -------------------------------- ### Get Server ISUPPORT Parameters Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Access server capabilities and limits advertised via ISUPPORT parameters using ISupport(). These are extracted from RPL_ISUPPORT numerics and include details like channel types, nickname length, and maximum modes. ```go isupport := conn.ISupport() chanTypes := isupport["CHANTYPES"] nickLen, _ := strconv.Atoi(isupport["NICKLEN"]) ``` -------------------------------- ### Get Preferred IRC Nickname Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Retrieve the desired nickname that was initially set using the Nick field. ```go conn.PreferredNick() ``` -------------------------------- ### Connect to IRC and Handle PRIVMSG Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/00-START-HERE.md This snippet shows how to create a connection, set up TLS, and add a callback for PRIVMSG events. Ensure you have configured your connection details correctly. ```go // Create and connect conn := &ircevent.Connection{ Server: "irc.libera.chat:6697", Nick: "mybot", User: "bot", UseTLS: true, } if err := conn.Connect(); err != nil { log.Fatal(err) } // Handle events conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { target := conn.GetReplyTarget(msg) if target != "" { conn.Privmsg(target, "Hello!") } }) // Run go conn.Loop() ``` -------------------------------- ### Configure Connection Using Environment Variables Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/configuration.md This snippet shows how to initialize an ircevent.Connection struct by reading configuration values from environment variables. Ensure that the necessary environment variables (e.g., IRC_SERVER, IRC_NICK) are set before running the application. ```go conn := &ircevent.Connection{ Server: os.Getenv("IRC_SERVER"), Nick: os.Getenv("IRC_NICK"), SASLLogin: os.Getenv("SASL_USER"), SASLPassword: os.Getenv("SASL_PASS"), Debug: os.Getenv("IRC_DEBUG") != "", } ``` -------------------------------- ### UnescapeTagValue Example Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-tags.md Demonstrates how to use UnescapeTagValue to convert an escaped tag value back to its raw form. This function is typically called automatically during message parsing. ```go escaped := "hello\\: world\\ntest" unescaped := ircmsg.UnescapeTagValue(escaped) // Result: "hello; world\ntest" ``` -------------------------------- ### Minimal IRC Client Configuration Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/configuration.md Configure a basic IRC client connection with server, nickname, username, and real name. Ensure to call Connect() and Loop(). ```go conn := &ircevent.Connection{ Server: "irc.libera.chat:6667", Nick: "mybot", User: "bot", RealName: "My IRC Bot", } err := conn.Connect() if err != nil { log.Fatal(err) } go conn.Loop() ``` -------------------------------- ### EscapeTagValue Example Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-tags.md Demonstrates how to use EscapeTagValue to escape a raw tag value before setting it as a message tag. This function is usually called automatically by the Message API. ```go escaped := ircmsg.EscapeTagValue("hello; world\ntest") // Result: "hello\: world\ntest" msg.SetTag("custom", escaped) line, _ := msg.Line() // Tags in line are properly escaped ``` -------------------------------- ### Initialize IRCReader with Custom Buffer Sizes Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Use Initialize with custom initialSize and maxSize for specific use cases like embedded systems or high-volume bots. Note that the buffer will not shrink below initialSize. ```go ircreader.Initialize(conn, 256, 4096) ``` ```go ircreader.Initialize(conn, 2048, 16384) ``` -------------------------------- ### Extract Nickname from Message Source Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-message.md Use this method to get the nickname from a message's source. Returns an empty string if the source is not a valid NUH format. ```go func (msg *Message) Nick() (nick string) ``` ```go nick := msg.Nick() if nick != "" { fmt.Println("Message from:", nick) } ``` -------------------------------- ### Get Acknowledged IRCv3 Capabilities Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Retrieve the IRCv3 capabilities successfully negotiated with the server using AcknowledgedCaps(). This map indicates which capabilities were acknowledged via CAP ACK. ```go caps := conn.AcknowledgedCaps() if _, ok := caps["message-tags"]; ok { fmt.Println("Server supports message tags") } ``` -------------------------------- ### Get Reply Target for IRC Messages Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Determines the appropriate target (channel or nick) for a reply to a PRIVMSG, NOTICE, or TAGMSG. Uses ISUPPORT CHANTYPES to detect channels. ```go func (irc *Connection) GetReplyTarget(msg ircmsg.Message) string ``` -------------------------------- ### Multiple Handlers for Same Command Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Demonstrates registering multiple callback functions for the same IRC command. Callbacks are invoked in the order they are registered. ```go // Callbacks are invoked in registration order id1 := conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { // Handler 1 }) id2 := conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { // Handler 2 (called after handler 1) }) ``` -------------------------------- ### Handle Connection Not Ready Error Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/INDEX.md Shows how to check for and handle the `ClientDisconnected` error when attempting to send a message, indicating the client is not yet ready. ```go err := conn.Privmsg("#channel", "hello") if err == ircevent.ClientDisconnected { // Not connected yet or reconnecting return err } ``` -------------------------------- ### Handling Labeled Responses in IRC Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Shows how to make a synchronous query using GetLabeledResponse to retrieve specific server information, such as WHOIS data, and how to handle potential errors like capability negotiation failure. ```go // Synchronous query batch, err := conn.GetLabeledResponse(nil, "WHOIS", "targetuser") if err == ircevent.CapabilityNotNegotiated { log.Println("Server does not support labeled-response") return } if err == ircevent.NoLabeledResponse { log.Println("Server failed to respond") return } // Process results for _, item := range batch.Items { fmt.Println(item.Command, item.Params) } ``` -------------------------------- ### Handle ErrorBadParam in IRC Messages Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/errors.md Detect ErrorBadParam when constructing IRC messages if a non-final parameter is empty, contains spaces, or starts with ':'. Fix by ensuring such parameters are treated as the final parameter. ```go var ErrorBadParam = errors.New("Cannot have an empty param, a param with spaces, or a param that starts with ':' before the last parameter") ``` ```go // This is invalid: space in middle param msg := ircmsg.MakeMessage(nil, "", "MODE", "#channel ops", "user") line, err := msg.Line() if err == ircmsg.ErrorBadParam { log.Println("Parameter violates IRC syntax") // Fix by using the problematic value as the final parameter msg2 := ircmsg.MakeMessage(nil, "", "MODE", "#channel", "ops user") line, _ := msg2.Line() } ``` -------------------------------- ### Get Current IRC Nickname Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Retrieve the nickname currently assigned by the server using CurrentNick(). This is useful when the initially set nickname might have been rejected. Returns an empty string if registration is not yet complete. ```go fmt.Println("I am:", conn.CurrentNick()) ``` -------------------------------- ### Configuration Options Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/MANIFEST.md Details on the configurable fields within the Connection struct. ```APIDOC ## Configuration Options ### Description Documentation for the 20+ fields within the `Connection` struct, detailing their purpose, type, default values, and usage requirements. ### Fields Each field includes: - **Purpose and use case**: Explains what the field controls. - **Type and default value**: Specifies the data type and its default setting. - **Required/optional status**: Indicates if the field must be set by the user. - **Integration examples**: Demonstrates how to use the field in practice. ``` -------------------------------- ### Connect Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Initiates a connection to the IRC server, handling initialization, authentication, and capability negotiation. It returns an error if the connection fails at any stage. ```APIDOC ## Connect ### Description Initiates a connection to the IRC server. This function performs parameter validation, TCP/TLS connection, spawns read/write/keepalive goroutines, performs SASL authentication, negotiates IRCv3 capabilities, and waits for RPL_WELCOME to signal successful registration. ### Method `Connect()` ### Parameters None ### Return Value `error` - nil on success, or an error if connection fails. ### Throws - Network errors from dial attempts - `ClientHasQuit` if Quit() was called - SASL-related errors if SASL is required and fails - Capability negotiation errors ### Default Values - Nick: "ircevent" - User: (same as Nick) - RealName: (same as User) - KeepAlive: 4 minutes - Timeout: 1 minute - ReconnectFreq: 2 minutes - MaxLineLen: 512 - SASLMech: "PLAIN" ### Example ```go conn := &ircevent.Connection{ Server: "irc.example.com:6667", Nick: "mybot", User: "bot", RealName: "My Bot", } err := conn.Connect() if err != nil { log.Fatal("Failed to connect:", err) } ``` ``` -------------------------------- ### Serialize Message to IRC Line Bytes Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-message.md Use `LineBytes` to get the serialized IRC message as a byte slice, including the \r\n terminator. This is useful for direct network writes. It shares the same error conditions as the `Line` method. ```go func (msg *Message) LineBytes() (result []byte, err error) ``` ```go bytes, err := msg.LineBytes() if err == nil { conn.Write(bytes) } ``` -------------------------------- ### Create IRC Message with MakeMessage Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-message.md Use `MakeMessage` to construct a new IRC message with optional tags, a source, a command, and parameters. The command is automatically normalized to uppercase. ```go func MakeMessage(tags map[string]string, source string, command string, params ...string) (ircmsg Message) ``` ```go msg := ircmsg.MakeMessage( map[string]string{"time": "2024-01-01T12:00:00Z"}, "nick!user@host", "PRIVMSG", "#channel", "Hello world!", ) ``` -------------------------------- ### Send Formatted NOTICE Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a formatted NOTICE message using fmt.Sprintf syntax. ```go conn.Noticef("#channel", "User %s has joined", username) ``` -------------------------------- ### Noticef Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a formatted NOTICE message using fmt.Sprintf syntax. ```APIDOC ## Noticef ### Description Sends a formatted NOTICE. ### Method func (irc *Connection) Noticef(target, format string, a ...interface{}) error ### Parameters #### Path Parameters - **target** (string) - Required - Recipient (channel or nickname) - **format** (string) - Required - The format string for the notice - **a** (...interface{}) - Required - Arguments to be formatted into the notice ``` -------------------------------- ### Multiple Handlers for Same Command Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Demonstrates how to register multiple callback functions for the same IRC command. Callbacks are invoked in the order they are registered. ```APIDOC ## Multiple Handlers for Same Command ### Description Demonstrates how to register multiple callback functions for the same IRC command. Callbacks are invoked in the order they are registered. ### Example ```go // Callbacks are invoked in registration order id1 := conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { // Handler 1 }) id2 := conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { // Handler 2 (called after handler 1) }) ``` ``` -------------------------------- ### Get Tag Value from IRC Message Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-message.md Retrieves the value of a tag from an IRC message. Handles both regular and client-only tags automatically based on the tag name prefix. Returns a boolean indicating presence and the tag's value. ```go present, value := msg.GetTag("time") if present { fmt.Println("Message time:", value) } ``` -------------------------------- ### NewIRCReader Constructor Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Creates a new IRC Reader with default buffer sizes suitable for the IRC protocol. Use this to initialize the reader with a network connection. ```go func NewIRCReader(conn io.Reader) *Reader ``` -------------------------------- ### Connection Type Definition Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/types.md Defines the configuration and runtime fields for an IRC connection. Use this to set up connection parameters before establishing a connection. ```go type Connection struct { // Configuration fields (all exported, user-settable) Server string TLSConfig *tls.Config Nick string User string RealName string WebIRC []string Password string RequestCaps []string SASLLogin string SASLPassword string SASLMech string SASLOptional bool QuitMessage string Version string Timeout time.Duration KeepAlive time.Duration ReconnectFreq time.Duration MaxLineLen int UseTLS bool UseSASL bool EnableCTCP bool Debug bool AllowPanic bool AllowTruncation bool DialContext func(context.Context, string, string) (net.Conn, error) // Runtime field (read-only) Log *log.Logger } ``` -------------------------------- ### Secure IRC Connection with SASL Authentication Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Demonstrates how to establish a secure TLS connection to an IRC server and authenticate using SASL PLAIN mechanism. It also shows how to request specific IRCv3 capabilities. ```go conn := &ircevent.Connection{ Server: "irc.libera.chat:6697", Nick: "mybot", UseTLS: true, UseSASL: true, SASLLogin: "username", SASLPassword: "password", RequestCaps: []string{"message-tags", "account-tag"}, } if err := conn.Connect(); err != nil { log.Fatal(err) } go conn.Loop() ``` -------------------------------- ### Verify Function Implementation with Source Code Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/MANIFEST.md Locate the exact source code line for a documented function using grep and line numbers. ```bash ircmsg/message.go:174 # ParseLine function ↓ grep -n "func ParseLine" irc-go/ircmsg/message.go ``` -------------------------------- ### Actionf Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a formatted ACTION message using fmt.Sprintf syntax. ```APIDOC ## Actionf ### Description Sends a formatted ACTION. ### Method func (irc *Connection) Actionf(target, format string, a ...interface{}) error ### Parameters #### Path Parameters - **target** (string) - Required - Recipient (channel or nickname) - **format** (string) - Required - The format string for the action - **a** (...interface{}) - Required - Arguments to be formatted into the action ``` -------------------------------- ### Send NOTICE Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a NOTICE (server message) to a user or channel. Typically used for non-critical information. ```go conn.Notice("#channel", "This is a notice") ``` -------------------------------- ### Handle ErrorCommandMissing Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/errors.md Demonstrates handling the ErrorCommandMissing error when attempting to serialize a message without a command. ```go msg := ircmsg.MakeMessage(nil, "server", "", "param") line, err := msg.Line() if err == ircmsg.ErrorCommandMissing { log.Println("Cannot serialize message without a command") } ``` -------------------------------- ### Create and Use Optimized IRC Reader Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Use ircreader.NewIRCReader to create an optimized buffered line reader for IRC protocol data. Read lines using reader.ReadLine(). ```go reader := ircreader.NewIRCReader(conn) line, err := reader.ReadLine() ``` -------------------------------- ### Handle ErrorLineIsEmpty Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/errors.md Demonstrates how to check for and handle the ErrorLineIsEmpty when parsing an IRC message. ```go msg, err := ircmsg.ParseLine(line) if err == ircmsg.ErrorLineIsEmpty { // Skip this message, it's empty continue } ``` -------------------------------- ### Register BATCH Callback Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Registers a callback for handling IRCv3 BATCH messages. Callbacks are executed in an undefined order; the first to return true handles the batch. If none handle it, the batch is processed individually. ```go func (irc *Connection) AddBatchCallback(callback func(*Batch) bool) CallbackID ``` ```go id := conn.AddBatchCallback(func(batch *Batch) bool { if batch.Command != "netsplit" { return false // Not our batch type } // Handle netsplit batch fmt.Printf("Netsplit: %v\n", batch.Items) return true // Successfully handled }) ``` -------------------------------- ### Join Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a JOIN command to join a specified channel. The user will become a member of the channel. ```APIDOC ## Join ### Description Sends a JOIN command to join a channel. ### Method func (irc *Connection) Join(channel string) error ### Parameters #### Path Parameters - **channel** (string) - Required - Channel name ### Response #### Success Response (nil) Returns nil on success. #### Error Response - `ClientDisconnected` if not connected. ### Request Example ```go conn.Join("#channel") ``` ``` -------------------------------- ### IRC Message Flow (Raw Data to Message) Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Illustrates the process of reading raw IRC data from a socket, parsing it into a structured message, and invoking registered callbacks. ```go Raw IRC Data ↓ ircreader.Reader.ReadLine() → []byte ↓ ircmsg.ParseLine() → Message ↓ Connection.runCallbacks() → registered Callback functions ``` -------------------------------- ### Connection Type Definition Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Defines the structure of the Connection type, outlining its configuration options for server details, authentication, capabilities, and connection management. ```go type Connection struct { // Configuration (user-settable) Server string // IRC server address (host:port) TLSConfig *tls.Config // TLS configuration for secure connections Nick string // Desired nickname User string // Username/ident RealName string // IRC realname/GECOS field WebIRC []string // Parameters for WEBIRC command Password string // Server password (PASS command) RequestCaps []string // IRCv3 capabilities to request SASLLogin string // SASL username SASLPassword string // SASL password SASLMech string // SASL mechanism (PLAIN or EXTERNAL) SASLOptional bool // If true, SASL failure is non-fatal QuitMessage string // Message to send on QUIT Version string // CTCP VERSION response text Timeout time.Duration // Timeout for server responses KeepAlive time.Duration // Interval for PING keepalive ReconnectFreq time.Duration // Delay between reconnection attempts MaxLineLen int // Maximum message length (default 512) UseTLS bool // Enable TLS/SSL UseSASL bool // Enable SASL authentication EnableCTCP bool // Enable CTCP auto-responders Debug bool // Enable debug logging AllowPanic bool // If true, don't recover() from callback panics AllowTruncation bool // If true, truncate lines exceeding MaxLineLen DialContext func(context.Context, string, string) (net.Conn, error) // Custom dial function // Internal state (read-only) Log *log.Logger // Logger for debug output } ``` -------------------------------- ### Connection State Methods Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Methods to check the current connection status and retrieve server-assigned information. ```APIDOC ## Connected ### Description Returns whether the client is currently connected to the server. Returns false during reconnection delays or if Quit() has been called. ### Method Signature ```go func (irc *Connection) Connected() bool ``` ### Return Value `bool` — true if connected and ready to send messages, false otherwise. ### Example ```go if conn.Connected() { conn.Privmsg("#channel", "Hello!") } ``` ``` ```APIDOC ## CurrentNick ### Description Returns the nickname currently assigned by the server. This may differ from the desired Nick if the server rejected it. Returns empty string if not yet registered. ### Method Signature ```go func (irc *Connection) CurrentNick() string ``` ### Return Value `string` — The current nickname. ### Example ```go fmt.Println("I am:", conn.CurrentNick()) ``` ``` ```APIDOC ## PreferredNick ### Description Returns the desired nickname (from the Nick field). ### Method Signature ```go func (irc *Connection) PreferredNick() string ``` ### Return Value `string` — The preferred nickname. ``` ```APIDOC ## SetNick ### Description Sets the desired nickname and sends a NICK command to the server. ### Method Signature ```go func (irc *Connection) SetNick(n string) ``` ### Parameters #### Path Parameters - **n** (string) - Required - The new nickname to use ### Example ```go conn.SetNick("newbot") ``` ``` ```APIDOC ## ISupport ### Description Returns the ISUPPORT parameters advertised by the server, which define server capabilities and limits. These are extracted from 005 (RPL_ISUPPORT) numerics. ### Method Signature ```go func (irc *Connection) ISupport() map[string]string ``` ### Return Value `map[string]string` — Server capability map. ### Common Keys - `CHANTYPES` — Channel type prefixes (e.g., "#" for normal channels) - `NICKLEN` — Maximum nickname length - `CHANNELLEN` — Maximum channel name length - `TOPICLEN` — Maximum topic length - `AWAYLEN` — Maximum away message length - `KICKLEN` — Maximum kick reason length - `MODES` — Maximum modes per MODE command ### Example ```go isupport := conn.ISupport() chanTypes := isupport["CHANTYPES"] nickLen, _ := strconv.Atoi(isupport["NICKLEN"]) ``` ``` ```APIDOC ## AcknowledgedCaps ### Description Returns the IRCv3 capabilities that were successfully negotiated with the server (those that returned CAP ACK). ### Method Signature ```go func (irc *Connection) AcknowledgedCaps() map[string]string ``` ### Return Value `map[string]string` — Map of capability names to their values. ### Example ```go caps := conn.AcknowledgedCaps() if _, ok := caps["message-tags"]; ok { fmt.Println("Server supports message tags") } ``` ``` -------------------------------- ### Send Formatted ACTION Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a formatted CTCP ACTION message using fmt.Sprintf syntax. ```go conn.Actionf("#channel", "%s waves hello", username) ``` -------------------------------- ### Handle IRC Formatting Codes Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/README.md Use ircfmt.Split to parse and split text with IRC formatting codes, ircfmt.Escape to convert raw control characters to escaped notation, and ircfmt.Unescape to convert escaped notation back to raw text. ```go chunks := ircfmt.Split(rawText) escaped := ircfmt.Escape(rawText) raw := ircfmt.Unescape(escapedText) ``` -------------------------------- ### Read IRC Lines and Parse with ircmsg Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Create an IRCReader and loop to read raw lines. Parse each line using ircmsg.ParseLine, handling potential parsing errors before processing the message. ```go reader := ircreader.NewIRCReader(conn) for { rawLine, err := reader.ReadLine() if err != nil { break } msg, parseErr := ircmsg.ParseLine(string(rawLine)) if parseErr != nil { log.Printf("parse error: %v", parseErr) continue } // Process message fmt.Printf("Command: %s\n", msg.Command) } ``` -------------------------------- ### Send IRC Command with Tags Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Use this to send an IRC command that includes IRCv3 message tags. Tags provide additional metadata for the message. ```go conn.SendWithTags( map[string]string{"time": "2024-01-01T12:00:00Z"}, "PRIVMSG", "#channel", "Tagged message", ) ``` -------------------------------- ### Handle Private Messages Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-callbacks.md Sets up a callback to process incoming PRIVMSG events. It determines if the message is to a channel or private, extracts sender and text, and logs the message. ```go conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { target := conn.GetReplyTarget(msg) if target == "" { return } // Check if it's a channel or private isChannel := strings.HasPrefix(target, "#") nick := msg.Nick() text := msg.Params[1] if isChannel { fmt.Printf("<%s> in %s: %s\n", nick, target, text) } else { fmt.Printf("<%s> (private): %s\n", nick, text) } }) ``` -------------------------------- ### MakeMessage Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-message.md Creates a new Message with the provided components, including tags, source, command, and parameters. ```APIDOC ## MakeMessage ### Description Creates a new Message with the provided components. ### Signature ```go func MakeMessage(tags map[string]string, source string, command string, params ...string) (ircmsg Message) ``` ### Parameters #### Path Parameters - **tags** (map[string]string) - Required - Map of tag names to values; pass `nil` for no tags - **source** (string) - Required - Message origin (e.g., "nick!user@host" or "server.name"); empty string for messages without a source - **command** (string) - Required - IRC command (automatically normalized to uppercase) - **params** (...string) - Required - Variable-length list of command parameters ### Return value - **ircmsg** (Message) - A new Message object. ### Example ```go msg := ircmsg.MakeMessage( map[string]string{"time": "2024-01-01T12:00:00Z"}, "nick!user@host", "PRIVMSG", "#channel", "Hello world!", ) ``` ``` -------------------------------- ### Handle Capability Not Negotiated Error Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/INDEX.md Demonstrates handling the `CapabilityNotNegotiated` error when requesting a labeled response, suggesting a fallback to normal callback-based handling. ```go _, err := conn.GetLabeledResponse(nil, "WHOIS", "user") if err == ircevent.CapabilityNotNegotiated { // Fall back to normal callback-based handling } ``` -------------------------------- ### Send Pre-constructed IRC Message Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Use this to send a fully constructed ircmsg.Message object. This is useful when you have already built the message structure. ```go msg := ircmsg.MakeMessage(nil, "", "PRIVMSG", "#channel", "Hello!") conn.SendIRCMessage(msg) ``` -------------------------------- ### Initialize Reader Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Initializes a Reader with custom buffer size limits. This allows for the reuse of an existing Reader struct. ```APIDOC ## Initialize Reader ### Description Initializes a Reader with custom buffer size limits. This is a "placement new" style initialization, allowing reuse of an existing Reader struct. ### Method Signature ```go func (cc *Reader) Initialize(conn io.Reader, initialSize, maxSize int) ``` ### Parameters #### Path Parameters - **conn** (io.Reader) - Required - The underlying connection to read from - **initialSize** (int) - Required - Initial buffer size (starting point for expansion) - **maxSize** (int) - Required - Maximum buffer size (hard limit) ### Request Example ```go var reader ircreader.Reader reader.Initialize(conn, 1024, 16384) line, _ := reader.ReadLine() ``` ``` -------------------------------- ### NewIRCReader Constructor Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircreader.md Creates a new Reader instance with default buffer sizes suitable for IRC protocol. It takes an io.Reader as input, which represents the underlying network connection. ```APIDOC ## NewIRCReader ### Description Creates a new Reader with sensible default buffer sizes for IRC protocol (initial: 512 bytes, max: 9216 bytes). ### Signature ```go func NewIRCReader(conn io.Reader) *Reader ``` ### Parameters #### Path Parameters - **conn** (io.Reader) - Required - The underlying connection to read from (e.g., net.Conn) ### Return Value - **&Reader** - A newly initialized Reader. ### Example ```go conn, _ := net.Dial("tcp", "irc.example.com:6667") reader := ircreader.NewIRCReader(conn) // Read lines for { line, err := reader.ReadLine() if err != nil { break } fmt.Println(string(line)) } ``` ``` -------------------------------- ### Send Formatted PRIVMSG Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a PRIVMSG using fmt.Sprintf syntax for dynamic message content. Useful for including variables in messages. ```go conn.Privmsgf("#channel", "Hello %s, you have %d messages", username, count) ``` -------------------------------- ### Send IRCv3 Labeled Response with Callback Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Use `SendWithLabel` to send a command and process its response asynchronously via a callback function. The callback receives a `Batch` containing the server's reply or `nil` on timeout. Ensure labeled-response capability is negotiated. ```go func (irc *Connection) SendWithLabel(callback func(*Batch), tags map[string]string, command string, params ...string) error ``` ```go // Get a list of channel members conn.SendWithLabel( func(batch *Batch) { if batch == nil { fmt.Println("Server failed to respond") return } for _, item := range batch.Items { fmt.Printf("User: %s\n", item.Params[2]) } }, nil, "WHO", "#channel", ) ``` -------------------------------- ### Feature-Rich IRC Bot Configuration Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/configuration.md Configure an advanced IRC bot with extensive features including IRCv3 capabilities, timeouts, message handling, and custom logging. Environment variables can be used for sensitive information like passwords and debug flags. ```go conn := &ircevent.Connection{ Server: "irc.example.com:6697", Nick: "advancedbot", User: "abot", RealName: "Advanced Bot", UseTLS: true, SASLLogin: "advancedbot", SASLPassword: os.Getenv("SASL_PASS"), EnableCTCP: true, Version: "AdvancedBot v1.0", // IRCv3 support RequestCaps: []string{ "message-tags", "batch", "labeled-response", "account-tag", "extended-join", "server-time", }, // Timing Timeout: 30 * time.Second, KeepAlive: 3 * time.Minute, ReconnectFreq: 30 * time.Second, // Message handling MaxLineLen: 512, AllowTruncation: true, // Debugging Debug: os.Getenv("DEBUG") != "", Log: log.New(os.Stderr, "[irc] ", log.LstdFlags), } err := conn.Connect() if err != nil { log.Fatal(err) } go conn.Loop() // Register handlers conn.AddCallback("REGISTRATION", func(msg ircmsg.Message) { conn.Join("#channel") }) conn.AddCallback("PRIVMSG", func(msg ircmsg.Message) { // Handle messages }) ``` -------------------------------- ### Create a SASL Buffer Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircutils.md Initializes a new SASLBuffer to handle buffering and decoding of SASL responses from successive AUTHENTICATE command parameters. Supports an optional maximum buffer size. ```go type SASLBuffer struct { maxLength int // Maximum buffered size (0 for no limit) // Private field: buf []byte } ``` ```go func NewSASLBuffer(maxLength int) *SASLBuffer ``` ```go // Create a buffer with 10KB max buf := ircutils.NewSASLBuffer(10240) ``` -------------------------------- ### ircutils Functions Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/MANIFEST.md Utilities for SASL authentication and hostname validation. ```APIDOC ## ircutils Functions ### Description Functions for encoding SASL responses and validating hostnames. ### Functions - **EncodeSASLResponse**: Encodes a SASL response. - **NewSASLBuffer**: Creates a new SASL buffer. - **Initialize**: Initializes a SASL buffer. - **Add**: Adds data to a SASL buffer. - **Clear**: Clears a SASL buffer. - **HostnameIsValid**: Validates if a string is a valid hostname. ``` -------------------------------- ### Part Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md Sends a PART command to leave a specified channel. The user will no longer be a member of the channel. ```APIDOC ## Part ### Description Sends a PART command to leave a channel. ### Method func (irc *Connection) Part(channel string) error ### Parameters #### Path Parameters - **channel** (string) - Required - Channel name ### Response #### Success Response (nil) Returns nil on success. #### Error Response - `ClientDisconnected` if not connected. ### Request Example ```go conn.Part("#channel") ``` ``` -------------------------------- ### Run IRC Connection Event Loop Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircevent-connection.md The main event loop that continuously monitors the connection. This function blocks and should be run in a goroutine. It handles reconnection with exponential backoff and repeats until Quit() is called. ```go err := conn.Connect() if err != nil { log.Fatal(err) } // Run the event loop in a goroutine go conn.Loop() // The connection is now active and will auto-reconnect as needed // Handle Quit() to stop ``` -------------------------------- ### ircevent Callbacks Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/INDEX.md Handles event registration and management for incoming IRC commands and responses. ```APIDOC ## ircevent Callbacks ### Description Manages the registration and handling of callbacks for various IRC events, allowing custom logic to be executed upon receiving specific commands or responses. ### Callback Management - `AddCallback(command string, callback CallbackFunc)`: Registers a function to be called when a specific IRC command is received. - `AddBatchCallback(batchName string, callback BatchCallbackFunc)`: Registers a function to be called for batched responses. - `RemoveCallback(command string)`: Removes a previously registered callback. - `ReplaceCallback(command string, callback CallbackFunc)`: Replaces an existing callback. - `ClearCallback(command string)`: Clears all callbacks for a given command. ### Utility Functions - `GetReplyTarget(msg *ircmsg.Message) string`: Determines the appropriate target for a reply based on the incoming message. ### Types - `Callback`: Represents a standard callback function. - `BatchCallback`: Represents a callback function for batched responses. - `LabelCallback`: Represents a callback function for labeled responses. - `Batch`: Represents a batch of messages. - `CallbackID`: An identifier for registered callbacks. ``` -------------------------------- ### Serialize Message to IRC Line String Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/api-reference/ircmsg-message.md The `Line` method serializes an `Message` object into a string format suitable for sending over IRC. It appends a \r\n to the end. Errors can occur if the command is missing, parameters are invalid, or tags are too long. ```go func (msg *Message) Line() (result string, err error) ``` ```go line, err := msg.Line() if err != nil { log.Printf("serialization error: %v", err) return } fmt.Println(line) // ":nick!user@host PRIVMSG #channel :Hello world!\r\n" ``` -------------------------------- ### Secure IRC Connection with SASL Source: https://github.com/ergochat/irc-go/blob/master/_autodocs/configuration.md Configure a secure IRC connection using TLS and SASL authentication. Set UseTLS, UseSASL, SASLLogin, SASLPassword, and SASLMech. Debugging can be enabled with Debug. ```go conn := &ircevent.Connection{ Server: "irc.libera.chat:6697", Nick: "mybot", User: "bot", RealName: "My Bot", UseTLS: true, UseSASL: true, SASLLogin: "mybot", SASLPassword: "secretpass", SASLMech: "PLAIN", Debug: true, } err := conn.Connect() if err != nil { log.Fatal(err) } go conn.Loop() ```