def main(url=Config.get("URL", "ships"), debug=False): stats = urllib2.urlopen(url).read() session.execute(Ship.__table__.delete()) session.execute( text("SELECT setval('ships_id_seq', 1, :false);", bindparams=[false])) for line in sre.findall(stats): ship = Ship() line = list(line) for index, key in enumerate(keys): if line[index] in mapping: line[index] = mapping[line[index]] elif line[index].isdigit(): line[index] = int(line[index]) if line[index] not in ( '-', '', ): setattr(ship, key, line[index]) ship.total_cost = ship.metal + ship.crystal + ship.eonium if debug: print "%12s%12s%12s%12s" % ( ship.name, ship.class_, ship.race, ship.type, ) session.add(ship) session.commit() session.close()
def invite(self, message, user, params): person = params.group(1) if person.lower() == Config.get("Connection","nick").lower(): message.reply("I am already here, shitface.") return u = User.load(name=person,access="member") if u is not None: message.reply("Stupid %s, that wanker %s is already a member."%(user.name,person)) return if self.is_already_proposed_invite(person): message.reply("Silly %s, there's already a proposal to invite %s."%(user.name,person)) return if not self.member_count_below_limit(): message.reply("You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you."%(Config.getint("Alliance", "members"),)) return anc = user.has_ancestor(person) if anc is True: message.reply("Ew, incest.") return if anc is None: message.reply("Filthy orphans should be castrated.") return prop = Invite(id=self.new_prop_id(), proposer=user, person=person, comment_text=params.group(2)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) to invite %s." %(user.name, prop.id, person) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply)
def execute(self, page, uid, pa_id, gid=None): scanlog("Scan: %s (group: %s)" %(pa_id,gid,)) page = decode(page) m = re.search('>([^>]+) on (\d+)\:(\d+)\:(\d+) in tick (\d+)', page) if not m: scanlog("Expired/non-matchinng scan (id: %s)" %(pa_id,)) return scantype = m.group(1)[0].upper() x = int(m.group(2)) y = int(m.group(3)) z = int(m.group(4)) tick = int(m.group(5)) m = re.search("<p class=\"right scan_time\">Scan time: ([^<]*)</p>", page) scantime = m.group(1) planet = Planet.load(x,y,z,) try: Q = session.query(Scan).filter(Scan.pa_id == pa_id).filter(Scan.planet_id == None) if Q.count() > 0: scan = Q.first() else: scan = Scan(pa_id=pa_id, scantype=scantype, tick=tick, time=scantime, group_id=gid, scanner_id=uid) session.add(scan) if planet: planet.scans.append(scan) session.commit() scan_id = scan.id except IntegrityError, e: session.rollback() scanlog("Scan %s may already exist: %s" %(pa_id,str(e),)) return
def run(self, request, **kwargs): try: user, cookie, key, planet_id = self.router(request) response = self.execute(request, user, **kwargs) session = Session() session.add(PageView(page = self.name, full_request = request.get_full_path(), username = user.name, session = key, planet_id = user.planet.id if user.planet else None, hostname = request.META['REMOTE_ADDR'],)) session.commit() if cookie is not None: response.set_cookie(SESSION_KEY, cookie, expires=request.session.expire) if planet_id is False: response.delete_cookie(PLANET_KEY) elif planet_id is not True: response.set_cookie(PLANET_KEY, planet_id, expires=datetime.now()+timedelta(days=65)) return response except UserError, e: return self.login_page(request, str(e))
def execute(self, message, user, params): chan = params.group(1) access = params.group(2) if not access.isdigit(): try: access = Config.getint("Access",access) except Exception: message.reply("Invalid access level '%s'" % (access,)) return else: access = int(access) if access > user.access: message.reply("You may not add a user with higher access to your own") return try: session.add(Channel(name=chan, userlevel=access, maxlevel=user.access)) session.commit() message.reply("Added chan %s at level %s" % (chan,access,)) message.privmsg("set %s autoinvite on" %(chan,),Config.get("Services", "nick")); message.privmsg("invite %s" %(chan,),Config.get("Services", "nick")); except IntegrityError: session.rollback() message.reply("Channel %s already exists" % (chan,))
def kick(self, message, user, params): person = params.group(1) if person.lower() == Config.get("Connection", "nick").lower(): message.reply("I'll peck your eyes out, c**t.") return u = User.load(name=person, access="member") if u is None: message.reply( "Stupid %s, you can't kick %s, they're not a member." % (user.name, person)) return if self.is_already_proposed_kick(person): message.reply("Silly %s, there's already a proposal to kick %s." % (user.name, person)) return if u.access > user.access: message.reply( "Unfortunately I like %s more than you. So none of that." % (u.name, )) return prop = Kick(proposer=user, kicked=u, comment_text=params.group(2)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) to kick %s." % ( user.name, prop.id, person) reply += " When people have been given a fair shot at voting you can call a count using !prop expire %d." % ( prop.id, ) message.reply(reply)
def authenticate(self, request): request.session = None request.user = None key = request.COOKIES.get(SESSION_KEY) if key: auth = Arthur.load(key, datetime.now()) if auth is None: raise UserError("Your session has expired, please login again.") if request.path == LOGOUT: session.delete(auth) session.commit() raise UserError("Logged out.") request.session = auth return auth.user, None, key elif (request.POST.get(USER) and request.POST.get(PASS)): user = User.load(name=request.POST.get(USER), passwd=request.POST.get(PASS)) if user is None: raise UserError("Invalid user.") else: key = self.generate_key(user) auth = Arthur(key=key, expire=datetime.now()+timedelta(days=1), user=user) session.query(Arthur).filter(Arthur.user == user).delete() session.add(auth) session.commit() request.session = auth return user, key, key else: return None, None, None
def main(url = Config.get("URL", "ships"), debug=False): req = urllib2.Request(url) req.add_header('User-Agent', useragent) stats = urllib2.urlopen(req).read() session.execute(Ship.__table__.delete()) if Config.get("DB", "dbms") == "mysql": session.execute(text("ALTER TABLE ships AUTO_INCREMENT=1;", bindparams=[false])) else: session.execute(text("SELECT setval('ships_id_seq', 1, :false);", bindparams=[false])) for line in sre.findall(stats): ship = Ship() line = list(line) for index, key in enumerate(keys): if line[index] in mapping: line[index] = mapping[line[index]] elif line[index].isdigit(): line[index] = int(line[index]) if line[index] not in ('-', '',): setattr(ship,key,line[index]) ship.total_cost = ship.metal + ship.crystal + ship.eonium if debug: print "%12s%12s%12s%12s" % (ship.name, ship.class_, ship.race, ship.type,) session.add(ship) session.commit() session.close()
def run(self, message): m = self.match(message, self.commandre) if m is None: if self.match(message, self.helpre) is not None: self.help(message) return command = m.group(2) try: route, subcommand, user, params = self.router(message, command) route(message, user, params) session = Session() session.add(Command(command_prefix = message.get_prefix(), command = self.name, subcommand = subcommand, command_parameters = self.hide_passwords(self.name, message.get_msg()[len(m.group(1))+1:].strip()), nick = message.get_nick(), username = "" if user is True else user.name, hostname = message.get_hostmask(), target = message.get_chan() if message.in_chan() else message.get_nick(),)) session.commit() session.close() except PNickParseError: message.alert(self.PParseError) except UserError: message.alert(self.AccessError) except PrefError: message.alert(self.PrefError) except ChanParseError, e: message.alert(self.ChanError%e)
def run(self, request, **kwargs): try: user, cookie, key, planet_id = self.router(request) response = self.execute(request, user, **kwargs) session = Session() session.add( PageView( page=self.name, full_request=request.get_full_path(), username=user.name, session=key, planet_id=user.planet.id if user.planet else None, hostname=request.META['REMOTE_ADDR'], )) session.commit() if cookie is not None: response.set_cookie(SESSION_KEY, cookie, expires=request.session.expire) if planet_id is False: response.delete_cookie(PLANET_KEY) elif planet_id is not True: response.set_cookie(PLANET_KEY, planet_id, expires=datetime.now() + timedelta(days=65)) return response except UserError, e: return self.login_page(request, str(e))
def authenticate(self, request): request.session = None request.user = None key = request.COOKIES.get(SESSION_KEY) if key: auth = Arthur.load(key, datetime.now()) if auth is None: raise UserError( "Your session has expired, please login again.") if request.path == LOGOUT: session.delete(auth) session.commit() raise UserError("Logged out.") request.session = auth return auth.user, None, key elif (request.REQUEST.get(USER) and request.REQUEST.get(PASS)): user = User.load(name=request.REQUEST.get(USER), passwd=request.REQUEST.get(PASS)) if user is None: raise UserError("Invalid user.") else: key = self.generate_key(user) auth = Arthur(key=key, expire=datetime.now() + timedelta(days=1), user=user) session.query(Arthur).filter(Arthur.user == user).delete() session.add(auth) session.commit() request.session = auth return user, key, key else: return None, None, None
def execute(self, message, user, params): chan = params.group(1) access = params.group(2) if not access.isdigit(): try: access = Config.getint("Access", access) except Exception: message.reply("Invalid access level '%s'" % (access,)) return else: access = int(access) if access > user.access: message.reply("You may not add a user with higher access to your own") return try: session.add(Channel(name=chan, userlevel=access, maxlevel=user.access)) session.commit() message.reply("Added chan %s at level %s" % (chan, access)) message.privmsg("set %s autoinvite on" % (chan,), Config.get("Services", "nick")) message.privmsg("invite %s" % (chan,), Config.get("Services", "nick")) except IntegrityError: session.rollback() message.reply("Channel %s already exists" % (chan,))
def new(self, message, user, params): tick = Updates.current_tick() comment = params.group(3) or "" when = int(params.group(1)) if when < PA.getint("numbers", "protection"): eta = when when += tick elif when <= tick: message.alert( "Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick) ) return else: eta = when - tick if when > 32767: when = 32767 attack = Attack(landtick=when, comment=comment) session.add(attack) for coord in re.findall(loadable.coord, params.group(2)): if not coord[4]: galaxy = Galaxy.load(coord[0], coord[2]) if galaxy: attack.addGalaxy(galaxy) else: planet = Planet.load(coord[0], coord[2], coord[4]) if planet: attack.addPlanet(planet) session.commit() message.reply(str(attack))
def invite(self, message, user, params): person = params.group(1) if person.lower() == Config.get("Connection","nick").lower(): message.reply("I am already here, shitface.") return u = User.load(name=person,access="member") if u is not None: message.reply("Stupid %s, that wanker %s is already a member."%(user.name,person)) return if self.is_already_proposed_invite(person): message.reply("Silly %s, there's already a proposal to invite %s."%(user.name,person)) return if not self.member_count_below_limit(): message.reply("You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you."%(Config.getint("Alliance", "members"),)) return anc = user.has_ancestor(person) if anc is True: message.reply("Ew, incest.") return if anc is None: message.reply("Filthy orphans should be castrated.") return prop = Invite(proposer=user, person=person, comment_text=params.group(2)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) to invite %s." %(user.name, prop.id, person) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply)
def delete_ships(self, user, taker, fleet, tick): session.delete(fleet) session.add( FleetLog(taker=taker, user=user, ship=fleet.ship, ship_count=fleet.ship_count, tick=tick))
def suggest(self,message,user,params): prop = Suggestion(id=self.new_prop_id(), proposer=user, comment_text=params.group(1)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) : %s" %(user.name,prop.id,prop.comment_text) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply)
def suggest(self,message,user,params): prop = Suggestion(proposer=user, comment_text=params.group(1)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) : %s" %(user.name,prop.id,prop.comment_text) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply)
def log_message(self, sender, receiver, phone, text, mode): session.add( SMS(sender=sender, receiver=receiver, phone=phone, sms_text=text, mode=mode)) session.commit()
def add_record(dct): record = rclass() for key in dct.keys(): setattr(record, key, dct[key]) if __name__ == '__main__': print "%12s%12s" % (key, dct[key]) if gen_mods: record.gen_mods() session.add(record)
def execute(self, message, user, params): params = params.group(1) params = self.timestampre.sub(' ', params).strip() session.add(Quote(text=params)) session.commit() message.reply("Added your shitty quote: " + params)
def execute(self, message, user, params): params = params.group(1) params=self.timestampre.sub(' ',params).strip() session.add(Slogan(text=params)) session.commit() message.reply("Added your shitty slogan: "+params)
def __init__(self, message, m): scanlog(asctime()) try: pnick = "(%s)" % message.get_pnick() except: pnick = "" scanlog("Galaxy status from %s%s" % (message.get_nick(), pnick)) target_x=m.group(1) target_y=m.group(2) target_z=m.group(3) owner_x=m.group(4) owner_y=m.group(5) owner_z=m.group(6) mission=m.group(7) fleetname=m.group(8) # race=m.group(10) fleetsize=m.group(11) eta=m.group(12) if mission == "A": mission = "Attack" elif mission == "D": mission = "Defend" elif mission == "R": mission = "Return" target=Planet.load(target_x,target_y,target_z) if target is None: return owner=Planet.load(owner_x,owner_y,owner_z) if owner is None: return curtick=Updates.current_tick() landing_tick = int(eta) + int(curtick) scanlog("%s:%s:%s %s:%s:%s '%s' %s %s eta %s" % (owner_x,owner_y,owner_z,target_x,target_y,target_z,fleetname,fleetsize,mission,eta)) fleet = FleetScan(owner=owner, target=target, fleet_size=fleetsize, fleet_name=fleetname, landing_tick=landing_tick, mission=mission) fleet.in_cluster = owner_x == target_x fleet.in_galaxy = fleet.in_cluster and owner_y == target_y try: session.add(fleet) session.commit() except IntegrityError,e: session.rollback() print "Exception in galstatus: "+e.__str__() scanlog("Exception in galstatus: "+e.__str__()) traceback.print_exc()
def execute(self, message, user, params): pnicks = params.group(1) access = params.group(2) if not access.isdigit(): try: access = Config.getint("Access",access) except Exception: message.reply("Invalid access level '%s'" % (access,)) return else: access = int(access) if access > user.access: message.reply("You may not add a user with higher access to your own") return added = [] exists = [] for pnick in pnicks.split(): if pnick.lower() == Config.get("Connection","nick").lower(): message.reply("I am already here, shitface.") continue member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access, sponsor=user.name) session.add(member) added.append(pnick) elif not member.active: member.active = True member.access = access member.sponsor = user.name added.append(pnick) elif not member.is_member(): member.access = access member.sponsor = user.name added.append(pnick) else: exists.append(pnick) session.commit() if len(exists): message.reply("Users (%s) already exist" % (",".join(exists),)) # Bot access if len(added): message.reply("Added users (%s) at level %s" % (",".join(added),access)) # P access with netgamers.org (set up to adduser with access 100 to your Home channel from merlin.cfg) if len(added) and access == Config.getint("Access","member"): message.privmsg("adduser %s %s 100" %(Config.get("Channels","home"), ",".join(added),), "P") message.reply("Added users (%s) to %s with lvl 100 access" % (",".join(added), Config.get("Channels","home"))) if len(added) and access >= Config.getint("Access","core"): message.privmsg("adduser %s %s 150" %(Config.get("Channels","home"), ",".join(added),), "P") message.reply("Added users (%s) to %s with lvl 150 access" % (",".join(added), Config.get("Channels","home"))) message.privmsg("adduser %s %s 150" %(Config.get("Channels","core"), ",".join(added),), "P") message.reply("Added users (%s) to %s with lvl 150 access" % (",".join(added), Config.get("Channels","core")))
def log_cookie(self, howmany, user, rec): now = datetime.datetime.now() weeks = (now - datetime.datetime(now.year, 1, 1)).days / 7 session.add( Cookie( year=now.year, week=weeks, howmany=howmany, giver=user, receiver=rec, ))
def new(self, message, user, params): tick = Updates.current_tick() comment = params.group(4) or "" when = int(params.group(1)) waves = params.group(2) or Config.get("Misc", "attwaves") if when < PA.getint("numbers", "protection"): when += tick elif when <= tick: message.alert( "Can not create attacks in the past. You wanted tick %s, but current tick is %s." % ( when, tick, )) return if when > 32767: when = 32767 attack = Attack(landtick=when, comment=comment, waves=int(waves)) session.add(attack) for coord in re.findall(loadable.coord, params.group(3)): if not coord[4]: galaxy = Galaxy.load(coord[0], coord[2]) if galaxy: attack.addGalaxy(galaxy) else: planet = Planet.load(coord[0], coord[2], coord[4]) if planet: attack.addPlanet(planet) session.commit() message.reply(str(attack)) # Request scans if Config.has_option("Misc", "attscans"): scantypes = Config.get("Misc", "attscans") else: scantypes = "" for stype in scantypes: for p in attack.planets: scan = p.scan(stype) if scan and (int(tick) == scan.tick): return else: req = Request(target=p, scantype=stype, dists=0) user.requests.append(req) session.commit() push("request", request_id=req.id, mode="request") if scantypes: message.reply("Scans requested: %s" % (scantypes))
def execute(self, page, uid, pa_id, gid=None): scanlog("Scan: %s (group: %s)" % ( pa_id, gid, )) page = decode(page) m = re.search('>([^>]+) on (\d+)\:(\d+)\:(\d+) in tick (\d+)', page) if not m: scanlog("Expired/non-matchinng scan (id: %s)" % (pa_id, )) return scantype = m.group(1)[0].upper() x = int(m.group(2)) y = int(m.group(3)) z = int(m.group(4)) tick = int(m.group(5)) m = re.search("<p class=\"right scan_time\">Scan time: ([^<]*)</p>", page) scantime = m.group(1) planet = Planet.load( x, y, z, ) try: Q = session.query(Scan).filter(Scan.pa_id == pa_id).filter( Scan.planet_id == None) if Q.count() > 0: scan = Q.first() else: scan = Scan(pa_id=pa_id, scantype=scantype, tick=tick, time=scantime, group_id=gid, scanner_id=uid) session.add(scan) if planet: planet.scans.append(scan) session.commit() scan_id = scan.id except IntegrityError, e: session.rollback() scanlog("Scan %s may already exist: %s" % ( pa_id, str(e), )) return
def execute(self, message, user, params): pnicks = params.group(1) access = params.group(2) if not access.isdigit(): try: access = Config.getint("Access", access) except Exception: message.reply("Invalid access level '%s'" % (access, )) return else: access = int(access) if access > user.access: message.reply( "You may not add a user with higher access to your own") return added = [] exists = [] for pnick in pnicks.split(): if pnick.lower() == Config.get("Connection", "nick").lower(): message.reply("I am already here, shitface.") continue member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access, sponsor=user.name) session.add(member) added.append(pnick) elif not member.active: member.active = True member.access = access member.sponsor = user.name added.append(pnick) elif not member.is_member(): member.access = access member.sponsor = user.name added.append(pnick) else: exists.append(pnick) session.commit() if len(exists): message.reply("Users (%s) already exist" % (",".join(exists), )) if len(added): message.reply("Added users (%s) at level %s" % (",".join(added), access)) if len(added) and access >= Config.getint("Access", "member"): message.privmsg( "adduser %s %s 24" % ( Config.get("Channels", "home"), ",".join(added), ), Config.get("Services", "nick"))
def delete_ships(self, user, taker, fleet, tick, count): if count: fleet.ship_count -= count if fleet.ship_count < 1: session.delete(fleet) else: session.delete(fleet) session.add( FleetLog(taker=taker, user=user, ship=fleet.ship, ship_count=(count or fleet.ship_count), tick=tick))
def __init__(self, message, m): print m.groups() target_x = m.group(1) target_y = m.group(2) target_z = m.group(3) owner_x = m.group(4) owner_y = m.group(5) owner_z = m.group(6) fleetname = m.group(7) race = m.group(9) fleetsize = m.group(10) mission = m.group(11) eta = m.group(12) print "%s:%s:%s %s:%s:%s '%s' %s m:%s e:%s" % ( owner_x, owner_y, owner_z, target_x, target_y, target_z, fleetname, fleetsize, mission, eta) target = Planet.load(target_x, target_y, target_z) if target is None: return owner = Planet.load(owner_x, owner_y, owner_z) if owner is None: return curtick = Updates.current_tick() landing_tick = int(eta) + int(curtick) fleet = FleetScan(owner=owner, target=target, fleet_size=fleetsize, fleet_name=fleetname, landing_tick=landing_tick, mission=mission) fleet.in_cluster = owner_x == target_x fleet.in_galaxy = fleet.in_cluster and owner_y == target_y try: session.add(fleet) session.commit() except IntegrityError, e: session.rollback() print "Exception in galstatus: " + e.__str__() traceback.print_exc()
def get_user(self, name, channel, pnick=None, pnickf=None): # Regular user check if (pnick is None) and (pnickf is None): # This shouldn't happen return None nick = self.Nicks.get(name) if (nick and nick.puser) is not None: # They already have a user associated pnick = nick.puser elif pnickf is not None: # Call the pnick function, might raise PNickParseError try: pnick = pnickf() except PNickParseError: return None user = User.load(name=pnick) if user is None and Config.getboolean("Misc", "autoreg"): if nick and not nick.puser: if "galmate" in Config.options("Access"): access = Config.getint("Access", "galmate") else: access = 0 user = User.load(name=pnick, active=False) if user is None: user = User(name=pnick, access=access) session.add(user) else: user.active = True user.access = access session.commit() if user is None: return None if (nick is not None) and self.mode_is("rapid", "join"): if self.Pusers.get(user.name) is None: # Add the user to the tracker self.Pusers[user.name] = Puser(user.name) if nick.puser is None: # Associate the user and nick nick.puser = user.name self.Pusers[user.name].nicks.add(nick.name) # Return the SQLA User return user
def new(self, message, user, params): tick = Updates.current_tick() comment = params.group(4) or "" when = int(params.group(1)) waves = params.group(2) or Config.get("Misc", "attwaves") if when < PA.getint("numbers", "protection"): when += tick elif when <= tick: message.alert("Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick,)) return if when > 32767: when = 32767 attack = Attack(landtick=when,comment=comment,waves=int(waves)) session.add(attack) for coord in re.findall(loadable.coord, params.group(3)): if not coord[4]: galaxy = Galaxy.load(coord[0],coord[2]) if galaxy: attack.addGalaxy(galaxy) else: planet = Planet.load(coord[0],coord[2],coord[4]) if planet: attack.addPlanet(planet) session.commit() message.reply(str(attack)) # Request scans if Config.has_option("Misc", "attscans"): scantypes = Config.get("Misc", "attscans") else: scantypes = "" for stype in scantypes: for p in attack.planets: scan = p.scan(stype) if scan and (int(tick) == scan.tick): return else: req = Request(target=p, scantype=stype, dists=0) user.requests.append(req) session.commit() push("request", request_id=req.id, mode="request") if scantypes: message.reply("Scans requested: %s" % (scantypes))
def execute(self, message, user, params): chan = params.group(1) if "galmate" in Config.options("Access"): access = Config.getint("Access","galmate") else: access = 0 try: session.add(Channel(name=chan, userlevel=access, maxlevel=access)) session.commit() message.reply("Added your galchannel as %s (if you didn't add me to the channel with at least access 24 first, I'm never going to bother joining)" % (chan,)) message.privmsg("set %s autoinvite on" %(chan,),'P'); message.privmsg("invite %s" %(chan,),'P'); except IntegrityError: session.rollback() message.reply("Channel %s already exists" % (chan,))
def execute(self, message, user, params): pnicks = params.group(1) access = params.group(2) if not access.isdigit(): try: access = Config.getint("Access",access) except Exception: message.reply("Invalid access level '%s'" % (access,)) return else: access = int(access) if access > user.access: message.reply("You may not add a user with higher access to your own") return added = [] exists = [] for pnick in pnicks.split(): member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access, sponsor=user.name) session.add(member) added.append(pnick) elif not member.active: member.active = True member.access = access member.sponsor = user.name added.append(pnick) elif not member.is_member(): member.access = access member.sponsor = user.name added.append(pnick) else: exists.append(pnick) session.commit() if len(exists): message.reply("Users (%s) already exist" % (",".join(exists),)) if len(added): message.reply("Added users (%s) at level %s" % (",".join(added),access)) if len(added) and access >= Config.getint("Access","member"): message.privmsg("adduser %s %s 399" %(Config.get("Channels","home"), ",".join(added),), "P")
def __init__(self, message, m): print m.groups() target_x=m.group(1) target_y=m.group(2) target_z=m.group(3) owner_x=m.group(4) owner_y=m.group(5) owner_z=m.group(6) fleetname=m.group(7) race=m.group(9) fleetsize=m.group(10) mission=m.group(11) eta=m.group(12) print "%s:%s:%s %s:%s:%s '%s' %s m:%s e:%s"%(owner_x,owner_y,owner_z,target_x,target_y,target_z,fleetname,fleetsize,mission,eta) target=Planet.load(target_x,target_y,target_z) if target is None: return owner=Planet.load(owner_x,owner_y,owner_z) if owner is None: return curtick=Updates.current_tick() landing_tick = int(eta) + int(curtick) fleet = FleetScan(owner=owner, target=target, fleet_size=fleetsize, fleet_name=fleetname, landing_tick=landing_tick, mission=mission) fleet.in_cluster = owner_x == target_x fleet.in_galaxy = fleet.in_cluster and owner_y == target_y try: session.add(fleet) session.commit() except IntegrityError,e: session.rollback() print "Exception in galstatus: "+e.__str__() traceback.print_exc()
def execute(self, message, user, params): chan = params.group(1) if "galmate" in Config.options("Access"): access = Config.getint("Access", "galmate") else: access = 0 try: session.add(Channel(name=chan, userlevel=access, maxlevel=access)) session.commit() message.reply( "Added your galchannel as %s (if you didn't add me to the channel with at least access 24 first, I'm never going to bother joining)" % (chan, )) message.privmsg("set %s autoinvite on" % (chan, ), Config.get("Services", "nick")) message.privmsg("invite %s" % (chan, ), Config.get("Services", "nick")) except IntegrityError: session.rollback() message.reply("Channel %s already exists" % (chan, ))
def main(url = Config.get("URL", "ships"), debug=False): stats = urllib2.urlopen(url).read() session.execute(Ship.__table__.delete()) session.execute(text("SELECT setval('ships_id_seq', 1, :false);", bindparams=[false])) for line in sre.findall(stats): ship = Ship() line = list(line) for index, key in enumerate(keys): if line[index] in mapping: line[index] = mapping[line[index]] elif line[index].isdigit(): line[index] = int(line[index]) if line[index] not in ('-', '',): setattr(ship,key,line[index]) ship.total_cost = ship.metal + ship.crystal + ship.eonium if debug: print "%12s%12s%12s%12s" % (ship.name, ship.class_, ship.race, ship.type,) session.add(ship) session.commit() session.close()
def main(url=Config.get("URL", "ships"), debug=False): req = urllib2.Request(url) req.add_header('User-Agent', useragent) stats = urllib2.urlopen(req).read() session.execute(Ship.__table__.delete()) if Config.get("DB", "dbms") == "mysql": session.execute( text("ALTER TABLE ships AUTO_INCREMENT=1;", bindparams=[false])) else: session.execute( text("SELECT setval('ships_id_seq', 1, :false);", bindparams=[false])) for line in sre.findall(stats): ship = Ship() line = list(line) for index, key in enumerate(keys): if line[index] in mapping: line[index] = mapping[line[index]] elif line[index].isdigit(): line[index] = int(line[index]) if line[index] not in ( '-', '', ): setattr(ship, key, line[index]) ship.total_cost = ship.metal + ship.crystal + ship.eonium if debug: print "%12s%12s%12s%12s" % ( ship.name, ship.class_, ship.race, ship.type, ) session.add(ship) session.commit() session.close()
def run(self, message): m = self.match(message, self.commandre) if m is None: if self.match(message, self.helpre) is not None: self.help(message) return command = m.group(2) try: route, subcommand, user, params = self.router(message, command) route(message, user, params) session = Session() session.add( Command( command_prefix=message.get_prefix(), command=self.name, subcommand=subcommand, command_parameters=self.hide_passwords( self.name, message.get_msg()[len(m.group(1)) + 1:].strip()), nick=message.get_nick(), username="" if user is True else user.name, hostname=message.get_hostmask(), target=message.get_chan() if message.in_chan() else message.get_nick(), )) session.commit() session.close() except PNickParseError: message.alert(self.PParseError) except UserError: message.alert(self.AccessError) except PrefError: message.alert(self.PrefError) except ChanParseError, e: message.alert(self.ChanError % e)
def add_ship(dct): ship = Ship() for key in dct.keys(): if dct[key] != "-": if key == "class": k = key + "_" elif key[:4] == "init": k = "init" elif key[:6] == "target": k = "t" + key[-1] else: k = key setattr(ship, k, dct[key]) ship.total_cost = int(ship.metal) + int(ship.crystal) + int(ship.eonium) session.add(ship) if __name__ == '__main__': print "%12s%12s%12s%12s" % ( ship.name, ship.class_, ship.race, ship.type, )
def execute(self, message, user, params): pnick = params.group(1) if "galmate" in Config.options("Access"): access = Config.getint("Access","galmate") else: access = 0 member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access) session.add(member) elif not member.active: member.active = True member.access = access elif member.access < access: member.access = access else: message.reply("User %s already exists" % (pnick,)) return session.commit() message.reply("Added user %s at level %s" % (pnick,access))
def execute(self, message, user, params): pnick = params.group(1) if "galmate" in Config.options("Access"): access = Config.getint("Access", "galmate") else: access = 0 member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access) session.add(member) elif not member.active: member.active = True member.access = access elif member.access < access: member.access = access else: message.reply("User %s already exists" % (pnick, )) return session.commit() message.reply("Added user %s at level %s" % (pnick, access))
def kick(self, message, user, params): person = params.group(1) if person.lower() == Config.get("Connection","nick").lower(): message.reply("I'll peck your eyes out, c**t.") return u = User.load(name=person,access="member") if u is None: message.reply("Stupid %s, you can't kick %s, they're not a member."%(user.name,person)) return if self.is_already_proposed_kick(person): message.reply("Silly %s, there's already a proposal to kick %s."%(user.name,person)) return if u.access > user.access: message.reply("Unfortunately I like %s more than you. So none of that."%(u.name,)) return prop = Kick(id=self.new_prop_id(), proposer=user, kicked=u, comment_text=params.group(2)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) to kick %s." %(user.name, prop.id, person) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply)
def process_request(self, request): try: if request.path[:8] == "/static/": return request.session = None key = request.COOKIES.get(SESSION_KEY) if key: auth = Session.load(key, datetime.datetime.now()) if auth is None: request._COOKIE = None return self.login_page(request, "Your session has expired, please login again.") if request.path == LOGOUT: session.delete(auth) session.commit() request._COOKIE = None return self.login_page(request, "Logged out.") request.session = auth return elif (request.REQUEST.get(USER) and request.REQUEST.get(PASS)): user = User.load(name=request.REQUEST.get(USER), passwd=request.REQUEST.get(PASS)) if user is None: request._COOKIE = None return self.login_page(request, "Invalid user.") else: key = self.generate_key(user) auth = Session(key=key, expire=datetime.datetime.now()+datetime.timedelta(days=1), user=user) session.query(Session).filter(Session.user == user).delete() session.add(auth) session.commit() request.session = auth request._COOKIE = key return else: return self.login_page(request, "Hi! Please login below:") except Exception as exc: exceptions().process_exception(request, exc) return server_error(request)
def new(self, message, user, params): tick = Updates.current_tick() comment = params.group(3) or "" when = int(params.group(1)) if when < PA.getint("numbers", "protection"): eta = when when += tick elif when <= tick: message.alert( "Can not create attacks in the past. You wanted tick %s, but current tick is %s." % ( when, tick, )) return else: eta = when - tick if when > 32767: when = 32767 attack = Attack(landtick=when, comment=comment) session.add(attack) for coord in re.findall(loadable.coord, params.group(2)): if not coord[4]: galaxy = Galaxy.load(coord[0], coord[2]) if galaxy: attack.addGalaxy(galaxy) else: planet = Planet.load(coord[0], coord[2], coord[4]) if planet: attack.addPlanet(planet) session.commit() message.reply(str(attack))
Base.metadata.create_all() print "Setting up default channels" userlevel = Config.get("Access", "member") maxlevel = Config.get("Access", "admin") gallevel = Config.get("Access", "galmate") for chan, name in Config.items("Channels"): try: channel = Channel(name=name) if chan != "public": channel.userlevel = userlevel channel.maxlevel = maxlevel else: channel.userlevel = gallevel channel.maxlevel = gallevel session.add(channel) session.flush() except IntegrityError: print "Channel '%s' already exists" % (channel.name,) session.rollback() else: print "Created '%s' with access (%s|%s)" % (channel.name, channel.userlevel, channel.maxlevel,) session.commit() session.close() if round: print "Migrating data:" try: print " - users/friends" session.execute(text("INSERT INTO users (id, name, alias, passwd, active, access, url, email, phone, pubphone, _smsmode, sponsor, quits, available_cookies, carebears, last_cookie_date, fleetcount) SELECT id, name, alias, passwd, active, access, url, email, phone, pubphone, _smsmode::varchar::smsmode, sponsor, quits, available_cookies, carebears, last_cookie_date, 0 FROM %s.users;" % (round,))) session.execute(text("SELECT setval('users_id_seq',(SELECT max(id) FROM users));"))
def expire(self, message, user, params): id = params.group(1) prop = self.load_prop(id) if prop is None: message.reply("No proposition number %s exists (idiot)."%(id,)) return if not prop.active: message.reply("You can't expire prop %d, it's already expired."%(prop.id,)) return if prop.proposer is not user and not user.is_admin(): message.reply("Only %s may expire proposition %d."%(prop.proposer.name,prop.id)) return if prop.type == "invite" and not self.member_count_below_limit(): message.reply("You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you."%(Config.getint("Alliance", "members"),)) return self.recalculate_carebears(prop) yes, no, veto = self.sum_votes(prop) passed = yes > no and veto <= 0 vote_result = ['no','yes'][passed] reply = self.text_result(vote_result, yes, no, veto) reply+= self.text_summary(prop) message.reply(reply) if prop.type == "invite" and passed: pnick = prop.person access = Config.getint("Access", "member") member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access, sponsor=prop.proposer.name) session.add(member) elif not member.active: member.active = True member.access = access member.sponsor = prop.proposer.name elif not member.is_member(): member.access = access member.sponsor = prop.proposer.name message.privmsg("adduser %s %s 24" %(Config.get("Channels","home"), pnick,), Config.get("Services", "nick")) message.reply("%s has been added to %s and given member level access to me."%(pnick,Config.get("Channels","home"))) if prop.type == "kick" and passed: idiot = prop.kicked if "galmate" in Config.options("Access"): idiot.access = Config.getint("Access","galmate") else: idiot.access = 0 if idiot.planet is not None and idiot.planet.intel is not None: intel = idiot.planet.intel alliance = Alliance.load(Config.get("Alliance","name")) if intel.alliance == alliance: intel.alliance = None message.privmsg("remuser %s %s"%(Config.get("Channels","home"), idiot.name,),Config.get("Services", "nick")) # message.privmsg("ban %s *!*@%s.%s Your sponsor doesn't like you anymore"%(Config.get("Channels","home"), idiot.name, Config.get("Services", "usermask"),),Config.get("Services", "nick")) message.privmsg("note send %s A proposition to kick you from %s has been raised by %s with reason '%s' and passed by a vote of %s to %s."%(idiot.name,Config.get("Alliance","name"),prop.proposer.name,prop.comment_text,yes,no),Config.get("Services", "nick")) message.reply("%s has been reduced to \"galmate\" level and removed from the channel."%(idiot.name,)) if prop.type == "suggestion" and passed: message.reply("Suggestion \"%s\" has passed" %(prop.comment_text)) prop.active = False prop.closed = current_timestamp() prop.vote_result = vote_result session.commit()
except ProgrammingError: print "A public schema already exists, but this is completely normal" session.rollback() else: session.commit() finally: session.close() Base.metadata.create_all() print "Setting up default channels" userlevel = Config.get("Access", "member") maxlevel = Config.get("Access", "admin") for chan, name in Config.items("Channels"): try: session.add(Channel(name=name,userlevel=userlevel,maxlevel=maxlevel)) session.flush() except IntegrityError: print "Channel '%s' already exists" % (name,) session.rollback() else: print "Created '%s' with access (%s|%s)" % (name, userlevel, maxlevel,) session.commit() session.close() if round: print "Migrating users/friends" session.execute(text("INSERT INTO users (id, name, alias, passwd, active, access, email, phone, pubphone, googlevoice, sponsor, quits, available_cookies, carebears, last_cookie_date, fleetcount) SELECT id, name, alias, passwd, active, access, email, phone, pubphone, googlevoice, sponsor, quits, available_cookies, carebears, last_cookie_date, 0 FROM %s.users;" % (round,))) session.execute(text("SELECT setval('users_id_seq',(SELECT max(id) FROM users));")) session.execute(text("INSERT INTO phonefriends (user_id, friend_id) SELECT user_id, friend_id FROM %s.phonefriends;" % (round,))) print "Migrating slogans/quotes"
def delete_ships(self, user, taker, fleet, tick): session.delete(fleet) session.add(FleetLog(taker=taker, user=user, ship=fleet.ship, ship_count=fleet.ship_count, tick=tick))
def log_message(self, sender, receiver, email, text, mode): session.add(SMS(sender=sender, receiver=receiver, phone=email, sms_text=text, mode=mode)) session.commit()
def add_setting(dct): for key in dct.keys(): record = GameSetup(key=key,value=dct[key]) if __name__ == '__main__': print "%12s%12s" % (key, dct[key]) session.add(record)
def execute2(self, message, user, params): mode = params.group(1).lower() if mode == "invite": person = params.group(2) u = User.load(name=person,access="member") if u is not None: message.reply("Stupid %s, that wanker %s is already a member."%(user.name,person)) return if self.is_already_proposed_invite(person): message.reply("Silly %s, there's already a proposal to invite %s."%(user.name,person)) return if not self.member_count_below_limit(): message.reply("You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you."%(Config.getint("Alliance", "members"),)) return anc = user.has_ancestor(person) if anc is True: message.reply("Ew, incest.") return if anc is None: message.reply("Filthy orphans should be castrated.") return prop = Invite(proposer=user, person=person, comment_text=params.group(3)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) to invite %s." %(user.name, prop.id, person) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply) elif mode == "kick": person = params.group(2) if person.lower() == Config.get("Connection","nick").lower(): message.reply("I'll peck your eyes out, c**t.") return u = User.load(name=person,access="member") if u is None: message.reply("Stupid %s, you can't kick %s, they're not a member."%(user.name,person)) return if self.is_already_proposed_kick(person): message.reply("Silly %s, there's already a proposal to kick %s."%(user.name,person)) return if u.access > user.access: message.reply("Unfortunately I like %s more than you. So none of that."%(u.name,)) return prop = Kick(proposer=user, kicked=u, comment_text=params.group(3)) session.add(prop) session.commit() reply = "%s created a new proposition (nr. %d) to kick %s." %(user.name, prop.id, person) reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,) message.reply(reply) elif mode == "expire": id = params.group(2) prop = self.load_prop(id) if prop is None: message.reply("No proposition number %s exists (idiot)."%(id,)) return if prop.proposer is not user and not user.is_admin(): message.reply("Only %s may expire proposition %d."%(prop.proposer.name,id)) return if prop.type == "invite" and not self.member_count_below_limit(): message.reply("You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you."%(Config.getint("Alliance", "members"),)) return self.recalculate_carebears(prop) yes, no, veto = self.sum_votes(prop) passed = yes > no and veto <= 0 vote_result = ['no','yes'][passed] reply = self.text_result(vote_result, yes, no, veto) reply+= self.text_summary(prop) message.reply(reply) if prop.type == "invite" and passed: pnick = prop.person access = Config.getint("Access", "member") member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access, sponsor=prop.proposer.name) session.add(member) elif not member.active: member.active = True member.access = access member.sponsor = prop.proposer.name elif not member.is_member(): member.access = access member.sponsor = prop.proposer.name message.privmsg("adduser %s %s 399" %(Config.get("Channels","home"), pnick,), "P") message.reply("%s has been added to %s and given member level access to me."%(pnick,Config.get("Channels","home"))) if prop.type == "kick" and passed: idiot = prop.kicked if "galmate" in Config.options("Access"): idiot.access = Config.getint("Access","galmate") else: idiot.access = 0 if idiot.planet is not None and idiot.planet.intel is not None: intel = idiot.planet.intel alliance = Alliance.load(Config.get("Alliance","name")) if intel.alliance == alliance: intel.alliance = None message.privmsg("remuser %s %s"%(Config.get("Channels","home"), idiot.name,),'p') message.privmsg("ban %s *!*@%s.users.netgamers.org Your sponsor doesn't like you anymore"%(Config.get("Channels","home"), idiot.name,),'p') message.privmsg("note send %s A proposition to kick you from %s has been raised by %s with reason '%s' and passed by a vote of %s to %s."%(idiot.name,Config.get("Alliance","name"),prop.proposer.name,prop.comment_text,yes,no),'p') message.reply("%s has been reduced to \"galmate\" level and removed from the channel."%(idiot.name,)) prop.active = False prop.closed = current_timestamp() prop.vote_result = vote_result session.commit() elif mode == "cancel": id = params.group(2) prop = self.load_prop(id) if prop is None: message.reply("No proposition number %s exists (idiot)."%(id,)) return if prop.proposer is not user and not user.is_admin(): message.reply("Only %s may expire proposition %d."%(prop.proposer.name,id)) return vote_result = "cancel" reply = self.text_result(vote_result, yes, no, veto) reply+= self.text_summary(prop) message.reply(reply) prop.active = False prop.closed = current_timestamp() prop.vote_result = vote_result session.commit()
Base.metadata.create_all() print "Setting up default channels" userlevel = Config.get("Access", "member") maxlevel = Config.get("Access", "admin") gallevel = Config.get("Access", "galmate") for chan, name in Config.items("Channels"): try: channel = Channel(name=name) if chan != "public": channel.userlevel = userlevel channel.maxlevel = maxlevel else: channel.userlevel = gallevel channel.maxlevel = gallevel session.add(channel) session.flush() except IntegrityError: print "Channel '%s' already exists" % (channel.name, ) session.rollback() else: print "Created '%s' with access (%s|%s)" % ( channel.name, channel.userlevel, channel.maxlevel, ) session.commit() session.close() if round: print "Migrating data:"
def log_cookie(self, howmany, user, rec): now = datetime.datetime.now() weeks = (now - datetime.datetime(now.year,1,1)).days / 7 session.add(Cookie(year=now.year, week=weeks, howmany=howmany, giver=user, receiver=rec,))
def expire(self, message, user, params): id = params.group(1) prop = self.load_prop(id) if prop is None: message.reply("No proposition number %s exists (idiot)." % (id, )) return if not prop.active: message.reply("You can't expire prop %d, it's already expired." % (prop.id, )) return if prop.proposer is not user and not user.is_admin(): message.reply("Only %s may expire proposition %d." % (prop.proposer.name, prop.id)) return if prop.type == "invite" and not self.member_count_below_limit(): message.reply( "You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you." % (Config.getint("Alliance", "members"), )) return self.recalculate_carebears(prop) yes, no, veto = self.sum_votes(prop) passed = yes > no and veto <= 0 vote_result = ['no', 'yes'][passed] reply = self.text_result(vote_result, yes, no, veto) reply += self.text_summary(prop) message.reply(reply) if prop.type == "invite" and passed: pnick = prop.person access = Config.getint("Access", "member") member = User.load(name=pnick, active=False) if member is None: member = User(name=pnick, access=access, sponsor=prop.proposer.name) session.add(member) elif not member.active: member.active = True member.access = access member.sponsor = prop.proposer.name elif not member.is_member(): member.access = access member.sponsor = prop.proposer.name message.privmsg( "adduser %s %s 24" % ( Config.get("Channels", "home"), pnick, ), Config.get("Services", "nick")) message.reply( "%s has been added to %s and given member level access to me." % (pnick, Config.get("Channels", "home"))) if prop.type == "kick" and passed: idiot = prop.kicked if "galmate" in Config.options("Access"): idiot.access = Config.getint("Access", "galmate") else: idiot.access = 0 if idiot.planet is not None and idiot.planet.intel is not None: intel = idiot.planet.intel alliance = Alliance.load(Config.get("Alliance", "name")) if intel.alliance == alliance: intel.alliance = None message.privmsg( "remuser %s %s" % ( Config.get("Channels", "home"), idiot.name, ), Config.get("Services", "nick")) # message.privmsg("ban %s *!*@%s.%s Your sponsor doesn't like you anymore"%(Config.get("Channels","home"), idiot.name, Config.get("Services", "usermask"),),Config.get("Services", "nick")) message.privmsg( "note send %s A proposition to kick you from %s has been raised by %s with reason '%s' and passed by a vote of %s to %s." % (idiot.name, Config.get("Alliance", "name"), prop.proposer.name, prop.comment_text, yes, no), Config.get("Services", "nick")) message.reply( "%s has been reduced to \"galmate\" level and removed from the channel." % (idiot.name, )) if prop.type == "suggestion" and passed: message.reply("Suggestion \"%s\" has passed" % (prop.comment_text)) prop.active = False prop.closed = current_timestamp() prop.vote_result = vote_result session.commit()