Communi  3.0.0
A cross-platform IRC framework written with Qt
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Properties Macros Groups Pages
QML bot example

The QML bot example is a simplified version of the bot example, written in QML. See the QML compatibility article for more QML specific details.

qmlbot.png
The QML bot example in action

The following snippet illustrates how IrcConnection is prepared and opened, and how a command is queued to automatically join a channel when connected.

connection: IrcConnection {
id: connection
host: "irc.freenode.net"
userName: "communi"
nickName: "QmlBot" + Math.round(Math.random() * 9999)
realName: qsTr("Communi %1 QML bot example").arg(irc.version())
Component.onCompleted: {
// queue a command to automatically join a channel when connected
sendCommand(command.createJoin(channel))
open()
}

The example utilizes IrcCommandParser for parsing commands from messages received from other clients. In order to take the parser in use, the supported commands must be teached, as illustrated below. Some of the commands are context sensitive, and the parser must be therefore kept aware of the list of channels the bot is on. This is easily achieved by binding the IrcCommandParser::channels property to the value of the IrcBufferModel::channels property. Furthermore, like a typical IRC bot, the commands are triggered using a slightly different syntax in queries and channels.

property IrcCommandParser parser: IrcCommandParser {
id: parser
// keep the parser aware of the context
channels: model.channels
// - on channel, respond to: "!<command> <params>" and "bot: <command> <params>"
// - in query, respond to: "!<command> <params>" and "<command> <params>"
triggers: connection.network.isChannel(target) ? ["!", connection.nickName + ":"] : ["!", ""]
Component.onCompleted: {
// teach the bot some commands
parser.addCommand(IrcCommand.Nick, "NICK <nick>");
parser.addCommand(IrcCommand.Join, "JOIN <#channel> (<key>)");
parser.addCommand(IrcCommand.Part, "PART (<#channel>) (<message...>)");
parser.addCommand(IrcCommand.Quit, "QUIT (<message...>)");
parser.addCommand(IrcCommand.Message, "SAY [target] <message...>");
}
}

The bot listens to incoming messages via IrcConnection::messageReceived(). The current target is chosen based on whether the incoming message is a channel or a private message. Each message content is parsed for commands that were taught earlier.

onMessageReceived: {
if (message.type === IrcMessage.Private) {
// - in private, reply to the message sender
// - on channel, reply to the target channel
parser.target = message.private ? message.nick : message.target
var command = parser.parse(message.content)
if (command) {
// send the command to the IRC server
sendCommand(command)
if (command.type === IrcCommand.Quit) {
// close the connection & quit the app when a !quit command was received
close()
Qt.quit()
}
}
}
}

Files: