Skip to content
This repository has been archived by the owner on Jul 30, 2024. It is now read-only.

Module HOWTO

Kimmo Huoman edited this page Jul 31, 2014 · 4 revisions

Basic modules

Commands

Commands start with a cmdchar, which is . by default (for example try as an admin .ping). You can write a command handle by defining a new function command_mycommand. As a result message .mycommand would call the function.

A normal module listens to a specific trigger and responds to it:

def command_helloworld(bot, user, channel, args):
  nick = getNick(user) # parses nick from nick!user@host
  if channel == "#hellochannel":
    bot.say(channel, "%s: Hello, World!" % nick)

Handlers

Messages

You can write a handler for all irc-input (privmsg). This handler will receive all messages typed by irc users, in both queries and in channels.

import logging

log = logging.getLogger("myprivmsghandler")
def handle_privmsg(bot, user, channel, msg):
  log.info("I received a message: %s" % msg)

URLs

There is also handler for urls:

import logging

log = logging.getLogger("myurlhandler")
def handle_url(bot, user, channel, msg):
  log.info("I received a url: %s" % msg)

Repeated tasks

Call a method or function consecutively:

import logging
from twisted.internet import reactor
import twisted.internet.error

log = logging.getLogger("motionmachine")
machine = None
factory = None


def init(factoryref):
    ''' Called when the bot is loaded and on rehash '''
    global factory
    factory = factoryref
    # Just to be sure, finalize first (shouldn't be needed though)
    finalize()
    # Start machine with 60 second interval
    perpetual_motion_machine(60)


def finalize():
    ''' Called before rehash, stops machine if needed '''
    global machine
    # If machine exists, cancel it
    if machine:
        try:
            machine.cancel()
        except twisted.internet.error.AlreadyCalled:
            pass
    machine = None


def perpetual_motion_machine(delay):
    ''' Run at set interval, calls self with the same delay '''
    global machine
    global factory

    bot_instance = factory.find_bot_for_network('nerv')
    # If bot instance was found, say something to channel
    if bot_instance:
        bot_instance.say('#pyfibot', 'Hello world!')
    machine = reactor.callLater(delay, perpetual_motion_machine, delay)
Clone this wiki locally