def handle(self, *args, **options): if not hasattr(settings, 'IRCBOT_PID'): print "Please set IRCBOT_PID to a file location to enable bot." return with open(settings.IRCBOT_PID, 'w') as pid: pid.write(str(os.getpid())) atexit.register(lambda: os.unlink(settings.IRCBOT_PID)) HeartBeat.objects.filter(name="ircbot").delete() self.beat = HeartBeat.objects.create(name="ircbot") self.client = BotClient() self.commands = list(self.load_irc_modules()) self.client.start() self.connection = self.client.connections[0] self.log_status("Server Started!", 0) drum = 10 # wait for a minute between beats while True: try: time.sleep(drum) self.beat.save() assert (self.connection.socket.connected) self.ready_commands() except KeyboardInterrupt: self.client.quit() for x, conn in enumerate(self.client.connections): if conn.socket.connected: conn.socket.disconnect() self.log_status("Keyboard Interrupt", 1) drum = 0.1 except AssertionError: threads = [ t for t in threading.enumerate() if t.name != 'MainThread' and t.isAlive() ] for t in threads: # This is for error tracking when treading is messed up self.log_status( "Thread Locked: %s (Alive:%s, Daemon:%s)" % (t.name, t.isAlive(), t.isDaemon()), -10) if not threads: self.log_status("Socket Disconnected", -1) break else: drum = 0.1
# -*- coding: utf-8 -*- """Example bot code for basic command-based bot using prefix command.""" # Creates a bot client to write a new bot. from easyirc.client.bot import BotClient client = BotClient() # Creates a simple storage from easyirc.storage import make_storage nicks = make_storage('nicks.json', 'nickmark') # Initializes a list. if not nicks.known: nicks.known = [] from easyirc.const import JOIN # You can use 'JOIN' in simple way. from easyirc import util # Message hook of JOIN message # We will say 'hello' to new nick for this bot. # About number of params of each message, refer to RFC. @client.events.hookmsg(JOIN) def on_join(connection, sender, channel): ident = util.parseid(sender) # 'util' has parsers of irc text. nick = ident.nick # Got a nick now! if not nick in nicks.known: # You can use irc protocols-wrapper for connection. # See easyirc.command.protocol connection.privmsg(channel, u'Hello, new user! ' + nick) nicks.known.append(nick)
# -*- coding: utf-8 -*- """Example bot code for basic command-based bot using prefix command.""" from easyirc.client.bot import BotClient # Creates a bot client to write a new bot. client = BotClient() pevent = client.events.msgprefix # alias to avoid verbosity # Change the prefix to '.' # Now commands are used like: .help .hello .sayback pevent.prefix = '.' @pevent.hook('reply') def on_reply(context, reply='No message to reply'): # 'reply' is a convinient tool to reply sender. # If message comes from channel, reply to channel. If message comes from # user, reply to user. # If message is privmsg, reply as privmsg. If message is notice, reply as # notice. context.reply(reply) @pevent.hook('ident') def on_ident(context, message=None): # 'ident' is a user identifier in irc protocol. # 'ident' consists with parts of identity: nick, username, host context.reply('ident:' + context.ident) context.reply('nick:' + context.ident.nick) context.reply('username:' + context.ident.username)
# -*- coding: utf-8 -*- from easyirc.client.bot import BotClient client = BotClient() client.msgevents = client.events.msgprefix client.events.msgprefix.prefix = '.'
class Command(BaseCommand): help = 'Starts an irc bot that will join the main channel and interact with the website.' @property def nick(self): return self.client.connections[0].tried_nick def handle(self, *args, **options): if not hasattr(settings, 'IRCBOT_PID'): print "Please set IRCBOT_PID to a file location to enable bot." return with open(settings.IRCBOT_PID, 'w') as pid: pid.write(str(os.getpid())) atexit.register(lambda: os.unlink(settings.IRCBOT_PID)) HeartBeat.objects.filter(name="ircbot").delete() self.beat = HeartBeat.objects.create(name="ircbot") self.client = BotClient() self.commands = list(self.load_irc_modules()) self.client.start() self.connection = self.client.connections[0] self.log_status("Server Started!", 0) drum = 10 # wait for a minute between beats while True: try: time.sleep(drum) self.beat.save() assert (self.connection.socket.connected) self.ready_commands() except KeyboardInterrupt: self.client.quit() for x, conn in enumerate(self.client.connections): if conn.socket.connected: conn.socket.disconnect() self.log_status("Keyboard Interrupt", 1) drum = 0.1 except AssertionError: threads = [ t for t in threading.enumerate() if t.name != 'MainThread' and t.isAlive() ] for t in threads: # This is for error tracking when treading is messed up self.log_status( "Thread Locked: %s (Alive:%s, Daemon:%s)" % (t.name, t.isAlive(), t.isDaemon()), -10) if not threads: self.log_status("Socket Disconnected", -1) break else: drum = 0.1 def log_status(self, msg, status=-1): print msg if self.beat.status == 0: self.beat.error = msg self.beat.status = status self.beat.save() def load_irc_modules(self): """Generate all BotCommands available in all installed apps""" for command in self.load_irc_commands( globals(), 'inkscape.management.commands.ircbot'): yield command for app_config in apps.app_configs.values(): app = app_config.module if module_has_submodule(app, 'irc_commands'): app = app.__name__ module = import_module("%s.%s" % (app, 'irc_commands')) for command in self.load_irc_commands(module.__dict__, module.__name__): yield command def load_irc_commands(self, possible, mod): """See if this is an item that is a Bot Command""" for (name, value) in possible.items(): if type(value) is type(BotCommand) and \ issubclass(value, BotCommand) and \ value is not BotCommand and \ value.__module__ == mod: yield self.register_command(value(self)) def register_command(self, command): """Register a single command class inheriting from BotCommand""" print "Hooking up: %s" % command.name regexes = command.regex if not isinstance(regexes, (list, tuple)): regexes = [regexes] for regex in regexes: self.client.events.msgregex.hookback(regex)(command) return command def ready_commands(self): """Make commands ready after we know for sure that we're connected""" for command in self.commands: try: if not command.is_ready: command.is_ready = bool(command.ready()) except Exception as err: print "Error getting %s ready: %s" % (command.name, str(err))