class account(object):
__duser_id = ''
__duser_name =''
__duser_no = ''
def __init__(self, default, entry_name, password, user_id='', user_name='', user_no=''):
if type(default) != bool:
raise Exception("Error 0x1: type(default) is boolean ")
if default == False:
self.__user_id = user_id
self.__user_name = user_name
self.__user_no = user_no
else:
self.__user_id = __duser_id
self.__user_name = __duser_name
self.__user_no = __duser_no
self.__entry_name = entry_name
self.__password = password
def dset(self, duser_id=__duser_id, duser_name=__duser_name, duser_no=__duser_no):
__duser_id = duser_id
__duser_name = duser_name
__duser_no = duser_no
return (__duser_id, __duser_name, __duser_no)
def dget(self):
return (__duser_id, __duser_name, __duser_no)
def set(self, user_name=self.__user_name, user_id=self.__user_id, user_no=self.__user_no, password=self.__password):
self.__user_id = user_id
self.__user_name = user_name
self.__user_no = user_no
self.__password = password
return (self.__user_id, self.__user_name, self.__user_no, self.password)
def get(self):
return (self.__user_id, self.__user_name, self.__user_no, self.password)
if __name__ == '__main__':
gmail = account(default=True, entry_name='gmail', password='pass***')
print(gmail.dget())
print(gmail.get())
out put is:
Traceback (most recent call last):
File "interface.py", line 1, in
class account(object):
File "interface.py", line 30, in account
def set(self, user_name=self.__user_name, user_id=self.__user_id, user_no=self.__user_no, password=self.__password):
NameError: name 'self' is not defined
Ok o got it.
but there is another one i just changed code.
This is a decorator with arbitrary number of arguments and keyword
arguments
def user_no_is_number(func):
def wrapper(*args, **kargs):
if 'user_no' in kargs:
if type(kargs['user_no']) != int:
raise Exception('Error 1x0: user_no must contains only numbers.')
else:
return func(*args, **kargs)
return wrapper
#staticmethod
#user_no_is_number
def dset(user_id=None, user_name=None, user_no=None):
if user_id:
account.__duser_id = user_id
if user_name:
account.__duser_name = user_name
if user_no:
account.__duser_no = user_no
return (account.__duser_id, account.__duser_name, account.__duser_no)
but the dset() function return always None
*I think there is problem with arbitrary keywords parameters. by using **kargs in decorator parameter it becomes dictionary and by again passing **kargs it just return values of that dictionary.*
Related
from Exception.Exceptions import *
import re
class Repo(object):
def __init__(self):
self.__items_dictionary = {}
def get_element(self, id):
try:
return self.__items_dictionary[id]
except KeyError:
raise RepositoryError("ID not existent")
def add_item(self, new_item):
try:
if new_item.id in self.__items_dictionary.keys():
raise RepositoryError("Id already exists!")
self.__items_dictionary[new_item.id] = new_item
except AttributeError:
raise RepositoryError('Element does not have an id introduced!')
def remove_item(self, id):
try:
if id in self.__items_dictionary.keys():
return self.__items_dictionary.pop(id)
else:
raise RepositoryError("Element does not exist!")
except KeyError:
raise RepositoryError("Element with that id does not exist!")
def update_item(self, id, attribute, new_value):
if id in self.__items_dictionary.keys():
if hasattr(self.__items_dictionary[id], attribute):
setattr(self.__items_dictionary[id], attribute, new_value)
else:
raise RepositoryError("Element with that attribute does not exist!")
else:
raise RepositoryError('Element with that id does not exist!')
def search_item(self, attribute, search_value):
searched_items = []
try:
if attribute == 'id':
search_value = int(search_value)
if search_value in self.__items_dictionary.keys():
searched_items.append(self.__items_dictionary[search_value])
else:
search_value = search_value.lower()
for item in self.__items_dictionary.keys():
item_string = getattr(self.__items_dictionary[item], attribute).lower()
if re.findall(search_value, item_string):
searched_items.append(self.__items_dictionary[item])
return searched_items
except ValueError as ve:
raise RepositoryError(ve)
#property
def get_all(self):
return self.__items_dictionary
def get_all_for_file(self):
return self.__items_dictionary
class FileRepository(Repo):
def __init__(self,filename, read_entity, write_entity):
Repo.__init__(self)
self.__filename = filename
self.__read_entity = read_entity
self.__write_entity = write_entity
def _read_all_from_file(self):
self._entities = {}
with open(self.__filename,'r') as file:
lines = file.readlines()
for line in lines:
line = line.strip()
if line != "":
entity = self.__read_entity(line)
self._entities[entity.id] = entity
def _write_all_to_file(self):
with open(self.__filename, 'w') as file:
for entity in self._entities:
line = self.__write_entity(entity)
file.write(line + "\n")
def add_item(self,new_item):
self._read_all_from_file()
Repo.add_item(self, new_item)
self._write_all_to_file()
def search_item(self, attribute, search_value):
self._read_all_from_file()
return Repo.search_item(self, attribute,search_value)
def update_item(self, id, attribute, new_value):
self._read_all_from_file()
Repo.update_item(self, id,attribute,new_value)
self._write_all_to_file()
def remove_item(self, id):
self._read_all_from_file()
Repo.remove_item(self, id)
self._write_all_to_file()
def get_all(self):
self._read_all_from_file()
return Repo.get_all
def get_element(self, id):
self._read_all_from_file()
return Repo.get_element(self,id)
I have checked and all gets added to it but whenever I try to access anything I get something like 'function' object has no attribute 'values' or 'method' object is not iterable. Could it be that I am calling that #property? But even when I tried with get_all_for_file() it still did't work...
I'm tring to provide a remote server by thrift, and below is my server-side trial:
from test_thrift.test_server.TestService import Iface,Processor
from thrift.Thrift import TType,TException
from thrift.Thrift import TProcessor
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.server import TNonblockingServer
port = int(config["server"]["port"])
handler = SmbService()
processor = Processor(handler)
socket = TSocket.TServerSocket(port=port)
server = TNonblockingServer.TNonblockingServer(processor, socket)
server.setNumThreads(100)
server.serve()
At my client-side, for every request I will create a new connect and close it after got response from server.
from thrift.transport.TSocket import TTransportException
from thrift.Thrift import TException
from thrift.protocol import TBinaryProtocol, TCompactProtocol
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift import Thrift
from test_thrift.test_server import TestService
class SmbClient(object):
def __init__(self):
try:
self.tsocket = TSocket.TSocket(settings.THRIFT_HOST, settings.THRIFT_PORT_PRODUCT)
self.transportFactory = TTransport.TFramedTransportFactory()
self.transport = self.transportFactory.getTransport(self.tsocket)
self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
self.client = TestService.Client(self.protocol)
self.transport.open()
except Thrift.TException as e:
self.logger.info(e)
class BaseService(object):
def __init__(self):
self.commonLogger = logging.getLogger('ads')
self.header = "header111"
def search_ads_list(self, request, account_id):
self.smbClient.client.getFBAdsByAccount(param1, param2)
def __enter__(self):
self.smbClient = SmbClient()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.smbClient.transport.close()
ech request call is like this:
with BaseService() as BaseSingleService:
status, data, info = BaseSingleService.search_ads_list(
request, account_id)
The actual amount of requests from client are not big enough , but after period of time. I got error like :
Traceback (most recent call last):
File "/home/xxx/xxx/src/smb_thrift_server.py", line 2200, in <module>
server.serve()
File "/home/xxx/xxx/venv3/lib/python3.5/site-packages/thrift/server/TNonblockingServer.py", line 350, in serve
self.handle()
File "/home/xxx/xxxx/venv3/lib/python3.5/site-packages/thrift/server/TNonblockingServer.py", line 310, in handle
rset, wset, xset = self._select()
File "/home/luban/smb_thrift_server/venv3/lib/python3.5/site-packages/thrift/server/TNonblockingServer.py", line 302, in _select
return select.select(readable, writable, readable)
ValueError: filedescriptor out of range in select()
Why error happended as I've closed the client connect each time after receiving the response?
update TestService codes below:
#
# Autogenerated by Thrift Compiler (0.9.1)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from .ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class Iface(object):
"""..."""
def getFBAdsByAccount(self, header, account_id, effective_status, access_token):
"""
Parameters:
- header
- account_id
- effective_status
- access_token
"""
pass
"""..."""
class Client(Iface):
def __init__(self, iprot, oprot=None):
self._iprot = self._oprot = iprot
if oprot is not None:
self._oprot = oprot
self._seqid = 0
def getFBAdsByAccount(self, header, account_id, effective_status, access_token):
"""
Parameters:
- header
- account_id
- effective_status
- access_token
"""
self.send_getFBAdsByAccount(header, account_id, effective_status, access_token)
return self.recv_getFBAdsByAccount()
def send_getFBAdsByAccount(self, header, account_id, effective_status, access_token):
self._oprot.writeMessageBegin('getFBAdsByAccount', TMessageType.CALL, self._seqid)
args = getFBAdsByAccount_args()
args.header = header
args.account_id = account_id
args.effective_status = effective_status
args.access_token = access_token
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getFBAdsByAccount(self):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getFBAdsByAccount_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success is not None:
return result.success
if result.e is not None:
raise result.e
raise TApplicationException(TApplicationException.MISSING_RESULT, "getFBAdsByAccount failed: unknown result");
class Processor(Iface, TProcessor):
def __init__(self, handler):
self._handler = handler
self._processMap = {}
self._processMap["getFBAdsByAccount"] = Processor.process_getFBAdsByAccount
def process(self, iprot, oprot):
(name, type, seqid) = iprot.readMessageBegin()
if name not in self._processMap:
iprot.skip(TType.STRUCT)
iprot.readMessageEnd()
x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))
oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)
x.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
return
else:
self._processMap[name](self, seqid, iprot, oprot)
return True
def process_getFBAdsByAccount(self, seqid, iprot, oprot):
args = getFBAdsByAccount_args()
args.read(iprot)
iprot.readMessageEnd()
result = getFBAdsByAccount_result()
try:
result.success = self._handler.getFBAdsByAccount(args.header, args.account_id, args.effective_status, args.access_token)
except test_thrift.common.ttypes.ServerException as e:
result.e = e
oprot.writeMessageBegin("getFBAdsByAccount", TMessageType.REPLY, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
class getFBAdsByAccount_args(object):
"""
Attributes:
- header
- account_id
- effective_status
- access_token
"""
thrift_spec = (
None, # 0
(1, TType.STRUCT, 'header', (test_thrift.common.ttypes.RequestHeader, test_thrift.common.ttypes.RequestHeader.thrift_spec), None, ), # 1
(2, TType.STRING, 'account_id', None, None, ), # 2
(3, TType.LIST, 'effective_status', (TType.STRING,None), None, ), # 3
(4, TType.STRING, 'access_token', None, None, ), # 4
)
def __init__(self, header=None, account_id=None, effective_status=None, access_token=None,):
self.header = header
self.account_id = account_id
self.effective_status = effective_status
self.access_token = access_token
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.header = test_thrift.common.ttypes.RequestHeader()
self.header.read(iprot)
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.account_id = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.LIST:
self.effective_status = []
(_etype24, _size21) = iprot.readListBegin()
for _i25 in range(_size21):
_elem26 = iprot.readString();
self.effective_status.append(_elem26)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.STRING:
self.access_token = iprot.readString();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('getFBAdsByAccount_args')
if self.header is not None:
oprot.writeFieldBegin('header', TType.STRUCT, 1)
self.header.write(oprot)
oprot.writeFieldEnd()
if self.account_id is not None:
oprot.writeFieldBegin('account_id', TType.STRING, 2)
oprot.writeString(self.account_id)
oprot.writeFieldEnd()
if self.effective_status is not None:
oprot.writeFieldBegin('effective_status', TType.LIST, 3)
oprot.writeListBegin(TType.STRING, len(self.effective_status))
for iter27 in self.effective_status:
oprot.writeString(iter27)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.access_token is not None:
oprot.writeFieldBegin('access_token', TType.STRING, 4)
oprot.writeString(self.access_token)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class getFBAdsByAccount_result(object):
"""
Attributes:
- success
- e
"""
thrift_spec = (
(0, TType.STRUCT, 'success', (test_thrift.common.ttypes.ResponseListMap, test_thrift.common.ttypes.ResponseListMap.thrift_spec), None, ), # 0
(1, TType.STRUCT, 'e', (test_thrift.common.ttypes.ServerException, test_thrift.common.ttypes.ServerException.thrift_spec), None, ), # 1
)
def __init__(self, success=None, e=None,):
self.success = success
self.e = e
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = test_thrift.common.ttypes.ResponseListMap()
self.success.read(iprot)
else:
iprot.skip(ftype)
elif fid == 1:
if ftype == TType.STRUCT:
self.e = test_thrift.common.ttypes.ServerException()
self.e.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('getFBAdsByAccount_result')
if self.success is not None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
if self.e is not None:
oprot.writeFieldBegin('e', TType.STRUCT, 1)
self.e.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
I'm using python3 and when trying to run the following code, I'm facing the error:
NameError: name '_length' is not defined
The code itself:
class OFPHELLO(GenericStruct):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._length = self.get_size()
_msg_type = OFPType.OFPT_HELLO
_build_order = ('header', 'x')
header = OFPHeader(type = _msg_type, length = _length)
x = UBInt8()
The problem is the _length variable that I'm passing in OFPHeader, the value of which is computed in GenericStruct. How can I compute the _length variable inside the OFPHELLO class and use it as parameter in the OFPHeader class?
Following the GenericStruct code:
class GenericStruct(object):
def __init__(self, **kwargs):
for a in kwargs:
try:
field = getattr(self, a)
field.value = kwargs[a]
except AttributeError:
raise OFPException("Attribute error: %s" % a)
def build(self):
hexa = ""
for field in self._build_order:
hexa += getattr(self, field).build()
return hexa
def parse(self, buff):
begin = 0
for field in self._build_order:
size = getattr(self, field).get_size()
getattr(self,field).parse(buff, offset=begin)
begin += size
def get_size(self):
tot = 0
for field in self._build_order:
tot += getattr(self, field).get_size()
return tot
- how have you defined (GenericStruct)
- header = OFPHeader(type = _msg_type, length = _lenght)
- correct the spelling to _length
-- and please post the entire code next time
I am working with Google App Engine and using the datastore to create a table for Users containing the entities username, the hash of the password, the email and the date joined. But when I run a function to register a user the function that hashes the passwords is returning the NoneType error.
I tried to look for the error, but the form is posting the values and I am able to get them from the headers.
This is the piece of code that handles the registration
def make_salt():
chars = string.ascii_uppercase + string.ascii_lowercase + string.ascii_digits
return ''.join(random.choice(chars) for x in range(5))
def make_pw_h(name, pw, salt = None):
if salt:
salt = make_salt()
return "%s,%s" % (salt, hashlib.sha256(name + pw + salt).hexdigest())
def check_pw_h(name, pw, h):
h = h.split(',')[1]
return h == make_pw_h(name, pw, h)
class Users(db.Model):
username = db.StringProperty(required = True)
pw_hash = db.StringProperty(required = True)
emai = db.StringProperty()
user_since = db.DateTimeProperty(auto_now_add = True)
#classmethod
def by_id(cls, uid):
return Users.get_by_id(uid)
#classmethod
def by_name(cls, name):
user = Users.all().filter('name = ', name).get()
return user
#classmethod
def register(cls, name, pw, email = None):
pw_h = make_pw_h(name, pw)
return Users(username = name,
pw_hash = pw_h,
email = email)
#classmethod
def login(cls, name, pw):
u = cls.by_name(name)
if u and check_pw(pw):
return u
def make_secure_val(s):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def check_secure_val(sec_val):
val = val.split('|')[0]
if sec_val == make_secure_val(val):
return val
class BaseHandler(webapp2.RequestHandler):
#this function uses the render_str funcion to display the html form in the browser
def render(self, template, **kw):
self.response.out.write(render_str(template, **kw))
#this funcion is a simple function using the template engine to write out the required data with
#any extra parameters
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def set_sec_coki(self, name, val):
sec_val = make_secure_val(val)
self.response.headers.add_cookie('Set-Cookie', "%s=%s; Path=/" % (name, sec_val))
def read_sec_coki(self, name):
coki_val = self.request.cookies.get(name)
return coki_val and check_secure_val(coki_val)
def Initialize(self, *a, **kw):
webapp2.RequestHandler.Initialize(self, *a, **kw)
uid = self.read_sec_coki('user-id')
self.user = uid and Users.by_id(int(uid))
class Signup(BaseHandler):
def get(self):
self.render("signup-form.html")
def post(self):
have_error = False
self.username = self.request.get('username')
self.password = self.request.get('password')
self.verify = self.request.get('verify')
self.email = self.request.get('email')
params = dict(username = self.username,
email = self.email)
if not valid_username(self.username):
params['error_username'] = "That's not a valid username."
have_error = True
if not valid_password(self.password):
params['error_password'] = "That wasn't a valid password."
have_error = True
elif self.password != self.verify:
params['error_verify'] = "Your passwords didn't match."
have_error = True
if not valid_email(self.email):
params['error_email'] = "That's not a valid email."
have_error = True
if have_error:
self.render('signup-form.html', **params)
else:
u = Users.by_name(self.username)
if u:
msg = "User already exists"
self.render('signup-form.html', error_username = msg)
else:
sing_user = Users.register(self.username, self.password, self.email)
sing_user.put()
self.login(sing_user)
self.set_sec_coki('user-id', sing_user.key().id())
self.redirect('/welcome')
class WelcomePage(BaseHandler):
def get(self):
coki_val = read_sec_coki('user-id')
u_id = coki_val.check_secure_val(coki_val)
part_usr = u_id.by_id(int(u_id))
name = part_usr.username
self.render("welcome.html", username = name)
And this is the error stack that I am getting when I try to register a new user via the form
Traceback (most recent call last):
File "/home/bigb/google_projects/google_appengine/lib/webapp2/webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "/home/bigb/google_projects/google_appengine/lib/webapp2/webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "/home/bigb/google_projects/google_appengine/lib/webapp2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/bigb/google_projects/google_appengine/lib/webapp2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/home/bigb/google_projects/google_appengine/lib/webapp2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/bigb/google_projects/google_appengine/lib/webapp2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/home/bigb/google_projects/my-ramblings/blog.py", line 197, in post
sing_user = Users.register(self.username, self.password, self.email)
File "/home/bigb/google_projects/my-ramblings/blog.py", line 55, in register
pw_h = make_pw_h(name, pw)
File "/home/bigb/google_projects/my-ramblings/blog.py", line 32, in make_pw_h
return "%s,%s" % (salt, hashlib.sha256(name + pw + salt).hexdigest())
TypeError: coercing to Unicode: need string or buffer, NoneType found
You call make_pw_h() with just two arguments, name and pw. You leave salt to the default, None:
def make_pw_h(name, pw, salt = None):
if salt:
salt = make_salt()
return "%s,%s" % (salt, hashlib.sha256(name + pw + salt).hexdigest())
This means the if salt: test is False and you end up with passing None to hashlib.sha256.
Perhaps you meant to test if salt is not set:
def make_pw_h(name, pw, salt=None):
if salt is None:
salt = make_salt()
return "%s,%s" % (salt, hashlib.sha256(name + pw + salt).hexdigest())
Sooo I have an IRC bot based on Skybot (IRC bot). I've looked into its documentation but it's not stated how to do it. I'd like to make it join, quit, part, set mode and other irc commands, but typing them from chan. Simple example:
.part #hello ~ Parts the chan
.mode #hello +b Tom - Bans Tom
That's what it has in its documentation about events
#hook.event(irc_command)
Event hooks are called whenever a specific IRC command is issued. For
example, if you provide "*" as parameter, it will trigger on every
line. If you provide "PRIVMSG", it will only trigger on actual lines
of chat (not nick-changes).
The first argument in these cases will be a two-element list of the
form ["#channel", "text"].
That's how a simple command works.
from util import hook, http
#hook.command
def calc(inp,say=None):
'Does calculation'
h = http.get_html('http://www.google.com/search', q=inp)
m = h.xpath('//h2[#class="r"]/text()')
if not m:
say("I can't calculate " + inp + ".")
res = ' '.join(m[0].split())
say(res + ".")
hook.py
import inspect
import re
def _hook_add(func, add, name=''):
if not hasattr(func, '_hook'):
func._hook = []
func._hook.append(add)
if not hasattr(func, '_filename'):
func._filename = func.func_code.co_filename
if not hasattr(func, '_args'):
argspec = inspect.getargspec(func)
if name:
n_args = len(argspec.args)
if argspec.defaults:
n_args -= len(argspec.defaults)
if argspec.keywords:
n_args -= 1
if argspec.varargs:
n_args -= 1
if n_args != 1:
err = '%ss must take 1 non-keyword argument (%s)' % (name,
func.__name__)
raise ValueError(err)
args = []
if argspec.defaults:
end = bool(argspec.keywords) + bool(argspec.varargs)
args.extend(argspec.args[-len(argspec.defaults):
end if end else None])
if argspec.keywords:
args.append(0) # means kwargs present
func._args = args
if not hasattr(func, '_thread'): # does function run in its own thread?
func._thread = False
def sieve(func):
if func.func_code.co_argcount != 5:
raise ValueError(
'sieves must take 5 arguments: (bot, input, func, type, args)')
_hook_add(func, ['sieve', (func,)])
return func
def command(arg=None, **kwargs):
args = {}
def command_wrapper(func):
args.setdefault('name', func.func_name)
_hook_add(func, ['command', (func, args)], 'command')
return func
if kwargs or not inspect.isfunction(arg):
if arg is not None:
args['name'] = arg
args.update(kwargs)
return command_wrapper
else:
return command_wrapper(arg)
def event(arg=None, **kwargs):
args = kwargs
def event_wrapper(func):
args['name'] = func.func_name
args.setdefault('events', ['*'])
_hook_add(func, ['event', (func, args)], 'event')
return func
if inspect.isfunction(arg):
return event_wrapper(arg, kwargs)
else:
if arg is not None:
args['events'] = arg.split()
return event_wrapper
def singlethread(func):
func._thread = True
return func
def regex(regex, flags=0, **kwargs):
args = kwargs
def regex_wrapper(func):
args['name'] = func.func_name
args['regex'] = regex
args['re'] = re.compile(regex, flags)
_hook_add(func, ['regex', (func, args)], 'regex')
return func
if inspect.isfunction(regex):
raise ValueError("regex decorators require a regex to match against")
else:
return regex_wrapper
and misc.py, there's one hook.event command there:
#autorejoin channels
#hook.event('KICK')
def rejoin(paraml, conn=None):
if paraml[1] == conn.nick:
if paraml[0].lower() in conn.channels:
conn.join(paraml[0])
#join channels when invited
#hook.event('INVITE')
def invite(paraml, conn=None):
conn.join(paraml[-1])
#hook.event('004')
def onjoin(paraml, conn=None):
# identify to services
nickserv_password = conn.conf.get('nickserv_password', '')
nickserv_name = conn.conf.get('nickserv_name', 'nickserv')
nickserv_command = conn.conf.get('nickserv_command', 'IDENTIFY %s')
if nickserv_password:
conn.msg(nickserv_name, nickserv_command % nickserv_password)
time.sleep(1)
# set mode on self
mode = conn.conf.get('mode')
if mode:
conn.cmd('MODE', [conn.nick, mode])
# join channels
for channel in conn.channels:
conn.join(channel)
time.sleep(1) # don't flood JOINs
# set user-agent
ident, rev = get_version()
main.py, where conn things are defined.
class Input(dict):
def __init__(self, conn, raw, prefix, command, params,
nick, user, host, paraml, msg):
chan = paraml[0].lower()
if chan == conn.nick.lower(): # is a PM
chan = nick
def say(msg):
conn.msg(chan, msg)
def reply(msg):
if chan == nick: # PMs don't need prefixes
conn.msg(chan, msg)
else:
conn.msg(chan, nick + ': ' + msg)
def pm(msg):
conn.msg(nick, msg)
def set_nick(nick):
conn.set_nick(nick)
def me(msg):
conn.msg(chan, "\x01%s %s\x01" % ("ACTION", msg))
def notice(msg):
conn.cmd('NOTICE', [nick, msg])
dict.__init__(self, conn=conn, raw=raw, prefix=prefix, command=command,
params=params, nick=nick, user=user, host=host,
paraml=paraml, msg=msg, server=conn.server, chan=chan,
notice=notice, say=say, reply=reply, pm=pm, bot=bot,
me=me, set_nick=set_nick, lastparam=paraml[-1])
# make dict keys accessible as attributes
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self[key] = value
I don't really get how can I do it. Thanks for your help!