def parse(msg_content, parser_info): print(msg_content) # bot pings server matched = re.match(r'PING :(?P<ping_id>\w+)', msg_content) if matched: return Ramen.pong(matched.group('ping_id')) # bot joins channel matched = re.match(r'^:%s' % parser_info['nick'], msg_content) if matched: return Ramen.join(parser_info['channel']) # bot reads msgs matched = re.match(r'^:(?P<sender_nick>[\w, -]+)!\S+ (?P<irc_command>\w+)(?: (?P<receiver>[#\w, -]+|[\w, -]+))* :(?P<msg_body>.+)$', msg_content) if matched: if matched.group('irc_command') == 'JOIN': chop = Chopsticks(parser_info['tellfile']) chop.userub( ((matched.group('sender_nick'),datetime.datetime.timestamp(datetime.datetime.utcnow())),) ) elif matched.group('irc_command') == 'PRIVMSG': return Ramen.resolv_com(parser_info, matched.group('sender_nick'), matched.group('receiver'), matched.group('msg_body')) # list of users in the channel matched = re.match(r'.+ = %s :%s((?: (?:[(?:%%|~|&|@|\+)\w, -]+|[\w, -]+))*)' % (parser_info['channel'], parser_info['nick']), msg_content) if matched: # .translate(symbol_map) removes nickname symbols # .split(' ') separates users into a list users = matched.group(1)[1:].translate(symbol_map).split(' ') Ramen.log_join(parser_info, users)
def log_join(info, users): chop = Chopsticks(info['tellfile']) timest = datetime.datetime.timestamp(datetime.datetime.utcnow()) usr_tupl = tuple() for user in users: usr_tupl += ((user, timest, 0, 0),) chop.userub(usr_tupl)
def read_msgs(info, nick, receiver): chop = Chopsticks(info['tellfile']) msgs = chop.retrievemsg(nick) pack = [] for msg in msgs: if not msg[2]: sendto = receiver else: sendto = nick pack.append(Ramen.build_msg(send_to=sendto, body='{0} left this msg for {1}: {2}', fparts=(msg[0], nick, msg[1]))) return pack
def lastseen(info, nick, receiver, args): if not args: return [Ramen.build_msg(send_to=receiver, body='Baka, this command needs a valid nick as argument')] chop = Chopsticks(info['tellfile']) # retrieves user lastseen timestamp from database # and converts it into a datetime obj timestamp = chop.user_rts(args[0]) if not timestamp: return [Ramen.build_msg(send_to=receiver, body='That person didn\'t connect while I was around')] date = datetime.datetime.fromtimestamp(timestamp) return [Ramen.build_msg(send_to=receiver, body='{0} was last seen {1} utc', fparts=(args[0], date.strftime('on %Y-%m-%d at %H:%M:%S')))]
def stats(receiver, args, tellfile): if not args: return [Ramen.build_msg(send_to=receiver, body='This command needs a nick as argument')] nick = args[0] attr = args[1:] chop = Chopsticks(tellfile) # no increments suplied if not attr: userinfo = chop.userstats(nick) # not nickname in database if not userinfo: return [Ramen.build_msg(send_to=receiver, body='No user stored with that nickname')] return [Ramen.build_msg(send_to=receiver, body='[{0}] autism: {1} cozyness: {2}', fparts=(nick, userinfo[0], userinfo[1]))] dto = {'autism': None, 'cozy': None} count = 0 userinfo_q = len(attr) if userinfo_q % 2 != 0: return [Ramen.build_msg(send_to=receiver, body='Argument error')] while count < userinfo_q: try: dto[attr[count]] = Ramen.statconvert(attr[count+1]) except KeyError: pass except RuntimeError as err: pass count += 2 try: update = chop.statsupdate(nick, dto) except RuntimeError as err: if err.args[0] == 'empty_dto': return [Ramen.build_msg(send_to=receiver, body='Argument error')] return [Ramen.build_msg(send_to=receiver, body='[{0}] autism: {1} cozyness: {2}', fparts=(nick, update['autism'], update['cozy']))]
def tell(info, nick, receiver, args): if not args: return [Ramen.build_msg(send_to=receiver, body='Try .help tell')] elif len(args) < 1: return [Ramen.build_msg(send_to=receiver, body='The msg need a body')] chop = Chopsticks(info['tellfile']) try: if receiver[0] != '#': chop.storemsg(nick, args[0], args[1:], 1) else: chop.storemsg(nick, args[0], args[1:], 0) except: return [Ramen.build_msg(send_to=receiver, body='For some reason the message couldn\'t be stored, sorry :c')] else: return [Ramen.build_msg(send_to=receiver, body='The msg will be delivered :3')]
def __init__(self, host='', port=0, nick='', realname='', channel='', tellfile='', ssl=False): self.host = host self.port = port self.nick = nick self.realname = realname self.channel = channel self.tellfile = expanduser(tellfile) self.ssl = ssl # creating tellfile.db chop = Chopsticks(self.tellfile) # setup db table structure chop.setup( """CREATE TABLE IF NOT EXISTS user(nickname TEXT PRIMARY KEY NOT NULL, lastseen REAL, cozy INTEGER NOT NULL, autism INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS msg(id_msg INTEGER PRIMARY KEY NOT NULL, body TEXT, sender_id INTEGER NOT NULL, receiver_id INTEGER NOT NULL, priv INTEGER NOT NULL, FOREIGN KEY(sender_id) REFERENCES user(nickname))""" )
path = FLAGS.output_dir or f"/tmp/{int(time.time())}" os.system('mkdir -p ' + path) with open(os.path.join(path, 'flags.json'), 'w') as f: f.write(json.dumps(FLAGS.__dict__)) with timer("loading data"): if 'chopsticks' in FLAGS.dataset: from chopsticks import Chopsticks m = re.search(r'depth(\d)_([a-z]+)', FLAGS.dataset) depth = int(m.group(1)) variant = m.group(2) noise = 0 if 'noise' in FLAGS.dataset: noise = float(re.search(r'noise([0-9\.]+)', FLAGS.dataset).group(1)) dataset = Chopsticks(depth, variant, noise) elif FLAGS.dataset == 'spaceshapes': from spaceshapes import Spaceshapes dataset = Spaceshapes() else: raise ValueError(f"Unrecognized dataset {FLAGS.dataset} -- should either be 'spaceshapes' or a Chopsticks variant string with a depth and slope/inter/either/both, e.g. 'chopsticks_depth3_both' or 'chopsticks_depth2_slope'.") true_hier = dataset.hierarchy data = dataset.data X = data.X A = data.A ground_truth_factors = data.AMZ order = np.arange(len(X)) rs = np.random.RandomState(seed=0) rs.shuffle(order)
import logging from philosopher import Philosopher from chopsticks import Chopsticks if __name__ == "__main__": logging.basicConfig( format='[%(asctime)s]:%(name)s:%(levelname)s:%(message)s', level=logging.DEBUG) log = logging.getLogger(__name__) names = ["Puper", "Schultz", "Bados", "Denis", "Fabel"] chopsticks = Chopsticks(5) philosophers = [Philosopher(name, chopsticks) for name in names] threads = [phil.start() for phil in philosophers] joins = [phil.join() for phil in philosophers] log.info("All done")