Skip to content

Instantly share code, notes, and snippets.

@suut
Created May 16, 2014 19:36
Show Gist options
  • Select an option

  • Save suut/d5ed757b1996cb76ef86 to your computer and use it in GitHub Desktop.

Select an option

Save suut/d5ed757b1996cb76ef86 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3.3
# -*- coding: utf-8 -*-
# core.py
# Functions:
# [X] ToSend object
# [X] loading servers details
# [ ] loading servers config (in which is found username, etc.)
# [ ] logging to disk commands and status
# [ ] loading and providing configuration e.g. is_enabled()
# [ ] provides ini reading interface
import irc.bot, configparser
import sys
class ServerSpec(irc.bot.ServerSpec):
def __init__(self, host, port, password, nickname, username, realname, channels):
if password == '':
password = None
super().__init__(host, port, password)
self.nickname = nickname
self.realname = realname
self.username = username
self.channels = channels
class ToSend:
""" a class to ease the slicing of messages to send """
def __init__(self, target, content):
#TODO: split the msg in 512o chunks
self.target = target
self.content = content
# LOADING SERVERS CONFIG
sys.argv.append('epiknet')
print('booting up...')
_serversparser = configparser.ConfigParser()
_serversparser.read('servers.ini')
print('available servers:', ', '.join(_serversparser.sections()))
assert len(sys.argv) > 1, 'you must provide a server to connect to'
assert sys.argv[1] in _serversparser.sections(), '{0} server does not exist'.format(sys.argv[1])
print('will connect to {0} ({1}:{2})'.format(sys.argv[1],
_serversparser[sys.argv[1]]['host'],
_serversparser[sys.argv[1]]['port']))
#loading server details
server_config = configparser.ConfigParser()
server_config.read('config/{0}.ini'.format(sys.argv[1]))
_details = server_config['details']
def write_config():
with open('config/{0}.ini'.format(sys.argv[1]), mode='w') as f:
server_config.write(f)
#creating the ServerSpec object
chosen_server = ServerSpec(_serversparser[sys.argv[1]]['host'],
int(_serversparser[sys.argv[1]]['port']),
_serversparser[sys.argv[1]]['password'],
_details['nickname'],
_details['username'],
_details['realname'],
_details['channels'].split(','))
def process_cmd(msg, source, target):
# [ ] check if the user is muted
# [ ] retrieve function registry
# [ ] get matching cmdnames
# [ ] sort by priority
# [ ] call in decreasing order
pass
# -*- coding: utf-8 -*-
# functions_core.py
# Elements:
# [X] IRC exceptions
# [X] sandbox function
# [X] function object
import core
class IRCException(Exception):
pass
class InvalidPasswordException(IRCException):
pass
class NotSufficentPrivilegesException(IRCException):
pass
class MutedCommandException(IRCException):
pass
class MutedUserException(IRCException):
pass
class UnknownCommandException(IRCException):
pass
class InvalidArgumentsException(IRCException):
pass
class _function_return:
def __eq__(self, c):
return isinstance(self, c)
class NEXT(_function_return):
""" sent by a function when it terminates """
class STOP(_function_return):
""" sent by a function when it terminates """
def __init__(self, data):
""" to_send could be either a core.ToSend object either None """
self.data = data
# a function either sends NEXT to call the next function on the list either
# STOP, with argument what should be printed back on the channel, sent to a
# print_to_channel type of function
def Sandbox(func):
def f(*args, **kwargs):
print('beggining of execution...\n\tsandboxing func...')
try:
ret = func(*args, **kwargs)
except IRCException as e:
print('\tERROR:', e)
else:
print('\texecution went fine.')
if ret == STOP:
print('\tfunction requested STOP:')
print('\t\t"', ret.data.content, '" to be sent to ', ret.data.target, sep='')
elif ret == NEXT:
print('\tfunction requested NEXT')
finally:
print('end of execution.')
return f
class _Function:
def __init__(self, cmdnames, f, priority):
self.f = f
self.cmdnames = cmdnames
self.priority = priority
self.muted = False
self.muted_users = []
def __call__(self, *args, **kwargs):
return self.f(*args, **kwargs)
def Function(cmdnames, priority):
def decorator(f):
return _Function(cmdnames, f, priority)
return decorator
## EXEMPLE
## @Sandbox
## @Function(cmdnames=('reverse',), priority=1)
## def reverse(s):
## return STOP(core.ToSend('#bite', s[::-1]))
# -*- coding: utf-8 -*-
# IRC bot
# Roadmap:
# [X] Functions core
# [X] Bot backbone
# [X] Server loader
# [ ] Per-server config loader
# [ ] Functions registry
# [ ] Highest priority functions (auth)
# /!\ NO GLOBAL CONF, ONLY PER-SERVER CONF /!\
# when config changes, (1) apply it OTF,
# (2) save it immediately to disk
from core import chosen_server
from superbot import SuperBot
bot = SuperBot(chosen_server)
bot.start()
# -*- coding: utf-8 -*-
import irc.bot
class SuperBot(irc.bot.SingleServerIRCBot):
def __init__(self, server):
print('initializing...')
super().__init__((server,), server.nickname, server.username, server.realname)
self.connection.buffer_class.errors = 'replace' # prevents crashing due to unicode errors
self._channels = server.channels
print('bot initialized.')
def start(self):
print('starting bot...')
super().start()
def on_welcome(self, serv, event):
print('\tgot welcome message.')
if self._channels is not None:
print('\tjoining following channels:', ', '.join(self._channels), '...')
for chan in self._channels:
serv.join(chan)
print('\tchannel joining attempt done.')
print('bot started.')
def on_pubmsg(self, serv, event):
print(':', event.source, ' PRIVMSG ', event.target, ' :', event.arguments[0], sep='')
# on_pubmsg called -> calls process_cmd @ core: verify is the user is muted,
# retrieve functions registry -> get matching cmdnames -> sort by priority
# -> call in decreasing order -> sends back result (if any) from the last
# call to on_pubmsg -> on_pubmsg calls sender @ core (to check if the bot
# is muted on that channel, globally...) which sends it back to the server
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment