Example #1
0
def get_pipeline(data):
    outputs.append([data['channel'], "One moment please..."])
    wbdb = WarbotDB()
    pwc = PWClient(USERNAME, PASS, logger=logger)
    notifying_beiges = wbdb.beige_checks.find({"state": "notify"})
    watching_beiges = wbdb.beige_checks.find({"state": "watch"})

    total = notifying_beiges.count() + watching_beiges.count()
    if total > 1:
        outputs.append([data['channel'], "Processing "+str(total)+" records in the pipeline..."])
    else:
        return "The pipeline looks empty from here!"
    output_strings = []
    if notifying_beiges.count() > 0:
        output_strings.append("*Next turn notifications*")
    for record in notifying_beiges:
        user = get_username_from_user_id(record["requesting_user_slack_id"])
        output_strings.append("I am notifying "+user+" next turn about nation "+record["nation_name"] + "("+record["nation_id"]+")")

    if watching_beiges.count() > 0:
        output_strings.append("*Upcoming reminders*")
    for record in watching_beiges:
        try:
            nation = pwc.get_nation_obj_from_ID(record["nation_id"])
            user = get_username_from_user_id(record["requesting_user_slack_id"])
            output_strings.append("I am watching nation "+record["nation_name"] + "("+str(record["nation_id"])+") for "+user+". Has *"+str(nation.beige_turns_left)+"* turns left in beiege.")
        except NationDoesNotExistError as e:
            user = get_username_from_user_id(record["requesting_user_slack_id"])
            output_strings.append("I am watching nation "+record["nation_name"] + "("+str(record["nation_id"])+") for "+user+". However, *_the nation no longer exists!_*")
    return "\n".join(output_strings)
Example #2
0
def notify_end_of_beige(slack_uid, slack_username, action):
    pwc = PWClient(USERNAME, PASS, logger=logger)
    wardb = WarbotDB()

    print "enter notify_end_of_beige"
    nation_ids = [int(s) for s in action.split() if s.isdigit()]
    nations_added = []
    nations_already_watched = []
    not_in_beige = []
    for nation_id in nation_ids:
        try:
            nation = pwc.get_nation_obj_from_ID(nation_id)
        except:
            trace = traceback.format_exc()
            print "Skipping this nation, exception below:"
            print trace
            continue
        if nation.beige_turns_left is not None:
            if wardb.create_personal_beige_watch_record(slack_uid, nation_id, nation.name, nation.beige_turns_left):
                nations_added.append(nation.name)
            else:
                nations_already_watched.append(nation.name)
        else:
            not_in_beige.append(nation.name)
    if len(nations_added) > 0:
        text = "OK, " + str(slack_username) + ", I'll notify you when " + ", ".join(nations_added) + " leaves beige"
    else:
        text = "I didn't find any nations to add in your query! Try `warbot help` if you need!"

    if len(nations_already_watched) > 0:
        text += "\nYou're already watching " + ", ".join(nations_already_watched) + ", ya doof!"
    if len(not_in_beige) > 0:
        text += "\nbtw, it looks like " + ", ".join(not_in_beige) + " aren't in beige ya dingus"

    return text
Example #3
0
def register_user(slack_uid, slack_username, action):
    pwc = PWClient(USERNAME, PASS, logger=logger)
    wardb = WarbotDB()

    nation_ids = [int(s) for s in action.split() if s.isdigit()]
    if len(nation_ids) != 1:
        return error_message()
    nation_id = nation_ids[0]

    print "Getting nation to register: ", nation_id

    nation_obj = pwc.get_nation_obj_from_ID(nation_id)
    name = nation_obj.name

    wardb.update_user_map(slack_uid, slack_username, nation_id, name)

    return "OK, "+slack_username+", I've registered your nation as "+name
Example #4
0
    def _init_pwc(self):
        if 'PWUSER' in os.environ:
            USERNAME = os.environ['PWUSER']
            PASS = os.environ['PWPASS']
        else:
            with open("/var/www/falcon/auth") as uf:
                USERNAME = uf.readline().strip()
                PASS = uf.readline().strip()
        if self.__username is None:
            self.__username = USERNAME
        if self.__password is None:
            self.__password = PASS

        self.pwc = PWClient(self.__username, self.__password)
Example #5
0
        html_string += "\t<th>"+i+"</th>\n"
    html_string += "</tr>\n"
    for l in matrix:
        html_string += list_to_tr(l)
    html_string += "</table>"
    return html_string


logger = logging.getLogger("pwc")
fhandler1 = logging.FileHandler("city_check.out", mode='w')
logger.addHandler(fhandler1)
logger.setLevel(logging.DEBUG)

USERNAME = os.environ['PW_USER']
PASS = os.environ['PW_PASS']
pwc = PWClient(USERNAME, PASS, logger=logger)

infos = []
for nation in pwc.get_list_of_alliance_members_from_alliance_name("Charming Friends"):
    today = datetime.now()
    min_days = 9000
    most_recent_city = None
    for city in nation.cities:
        diff = today - city.founded
        if diff.days < min_days:
            min_days = diff.days
            most_recent_city = city.name
    info = [nation.name, len(nation.cities), ''.join(most_recent_city.splitlines()), min_days]
    if min_days > 10:
        infos.append(info)
Example #6
0
from pw_client import PWClient

__author__ = 'shawkins'

money_string = '<b style="color: #28d020;">$</b>'
img_dict = {'steel': 'https://politicsandwar.com/img/resources/steel.png', 'oil': 'https://politicsandwar.com/img/resources/oil.png', 'aluminum': 'https://politicsandwar.com/img/resources/aluminum.png', 'lead': 'https://politicsandwar.com/img/resources/lead.png', 'bauxite': 'https://politicsandwar.com/img/resources/bauxite.png', 'food': 'https://politicsandwar.com/img/icons/16/steak_meat.png', 'money': 'https://politicsandwar.com/img/resources/money.png', 'munition': 'https://politicsandwar.com/img/resources/munitions.png', 'uranium': 'https://politicsandwar.com/img/resources/uranium.png', 'coal': 'https://politicsandwar.com/img/resources/coal.png', 'iron': 'https://politicsandwar.com/img/resources/iron.png', 'gasoline': 'https://politicsandwar.com/img/resources/gasoline.png'}
realstring_dict = {'steel': 'steel', 'oil': 'oil', 'lead': 'lead', 'aluminum': 'aluminum', 'munition': 'munitions', 'food': 'food', 'bauxite': 'bauxite', 'uranium': 'uranium', 'coal': 'coal', 'iron': 'iron', 'gasoline': 'gasoline'}

logger = logging.getLogger("pwc")
fhandler1 = logging.FileHandler("city_check.out", mode='w')
logger.addHandler(fhandler1)
logger.setLevel(logging.DEBUG)

USERNAME = os.environ['PW_USER']
PASS = os.environ['PW_PASS']
pwc = PWClient(USERNAME, PASS, logger=logger)

img_url = "https://politicsandwar.com/img/resources/"

records = pwc.get_alliance_tax_records_from_id(1356, only_last_turn=True)

totals = {}
for record in records:
    for resource_key in record['resources'].keys():
        if resource_key not in totals.keys():
            totals[resource_key] = 0
        totals[resource_key] += record['resources'][resource_key]

html_string = "<h1>Total amounts collected last turn</h1>\n"
html_string += "<table>\n"
    html.append(basic_text3)

    return ETree.tostring(html)

# recipients:  [email protected], [email protected]

logger = logging.getLogger("pwc")
fhandler1 = logging.FileHandler("beige_watch.out", mode='w')
shandler = logging.StreamHandler(sys.stdout)
logger.addHandler(fhandler1)
logger.addHandler(shandler)
logger.setLevel(logging.INFO)

USERNAME = os.environ['PWUSER']
PASS = os.environ['PWPASS']
pwc = PWClient(USERNAME, PASS, logger=logger)

beiges_to_expire = []

for beige in pwc.generate_all_nations_with_color('beige'):
    try:
        time_to_beige_exit = pwc.get_next_turn_in_datetime(pwc.calculate_beige_exit_time(beige.nation_id))- pwc.get_current_date_in_datetime()
        if time_to_beige_exit <= datetime.timedelta(hours=2, minutes=30):
            beiges_to_expire.append(beige)
            logger.info("")
            logger.info(str(beige.nation_id) + " "+ str(beige.color) + " to expire in "+str(time_to_beige_exit))
            logger.info("")
        else :
            print beige.nation_id,",",
    except WhyIsNationInBeige:
        logger.info("\nshit this nation is in beige, why?? " + str(beige.nation_id))
Example #8
0
    if ascending:
        asc_desc = "ASC"
    else:
        asc_desc = "DESC"
    return "https://politicsandwar.com/index.php?id=90&display=world&resource1=" + good + "&buysell=" + buysell +\
           "&ob=price&od=" + asc_desc + "&maximum=15&minimum=0&search=Go"


logger = logging.getLogger("pwc")
fhandler1 = logging.FileHandler("city_check.out", mode='w')
logger.addHandler(fhandler1)
logger.setLevel(logging.DEBUG)

USERNAME = os.environ['PW_USER']
PASS = os.environ['PW_PASS']
pwc = PWClient(USERNAME, PASS, logger=logger)
pwdb = LeanPWDB()

sky_blue = Color("#2b8dcc")
dark_blue = Color("#0d2b3e")

light_orange = Color("#FF7B0C")
dark_orange = Color("#7F4108")

orange_gradient = list(dark_orange.range_to(light_orange, 100))
blue_gradient = list(dark_blue.range_to(sky_blue, 100))

resource_dict = {}
for item_type in realstring_dict.keys():
    resource_dict[item_type] = {"buy": 0,
                                "sell": 0}
Example #9
0
class PWDB:
    def __init__(self, username=None, password=None, skip_pwclient=False):
        self.pwc = None
        self.__username = username
        self.__password = password

        if 'PWDBUSER' in os.environ:
            db_user = os.environ['PWDBUSER']
            db_pw = os.environ['PWDBPASS']
        else:
            with open("/var/www/falcon/dbauth") as uf:
                db_user = uf.readline().strip()
                db_pw = uf.readline().strip()
        if not skip_pwclient:
            self._init_pwc()

        self.mongo_client = MongoClient(host="falcon.spencer-hawkins.com")
        self.mongo_client.tax_db.authenticate(db_user, db_pw)
        self.tax_db = self.mongo_client.tax_db
        assert isinstance(self.tax_db, Database)

        self.nations = self.tax_db.nations
        assert isinstance(self.nations, Collection)

        self.tax_record_db = self.mongo_client.tax_record_db
        assert isinstance(self.tax_db, Database)

        self.falcon_records = self.tax_record_db.new_col
        assert isinstance(self.nations, Collection)

        self.falcon_withdraw_records = self.tax_record_db.falcon_withdraw_records
        assert isinstance(self.nations, Collection)

        self.graph_counter = self.tax_db.graph_counter
        assert isinstance(self.nations, Collection)

        self.falcon_counter = self.tax_record_db.falcon_counter
        assert isinstance(self.nations, Collection)

    def _init_pwc(self):
        if 'PWUSER' in os.environ:
            USERNAME = os.environ['PWUSER']
            PASS = os.environ['PWPASS']
        else:
            with open("/var/www/falcon/auth") as uf:
                USERNAME = uf.readline().strip()
                PASS = uf.readline().strip()
        if self.__username is None:
            self.__username = USERNAME
        if self.__password is None:
            self.__password = PASS

        self.pwc = PWClient(self.__username, self.__password)


    def nation_exists(self, nation_id):
        result = self.nations.find({'nation_id':nation_id})
        count = result.count()

        if count > 1:
            raise Exception("Malformed database!!! More than one nation exists at ID", nation_id)
        return count == 1

    def make_nation(self, nation_id):
        if self.nation_exists(nation_id):
            return False

        nation_obj = { 'nation_id': str(nation_id),
                       collected_key: self.pwc.get_current_date_in_datetime(),
                       owed_key: {},
                       turns_since_collected_key: 0,
                       total_paid_key: {}}

        if MAINTENANCE_MODE:
            nation_obj['maintenance'] = True

        return self.nations.insert_one(nation_obj).inserted_id

    def get_nation(self, nation_id, or_create=True):
        result = self.nations.find_one({'nation_id':str(nation_id)})
        if or_create:
            if result is None:
                self.make_nation(str(nation_id))  # Stick it in the DB
                result = self.get_nation(str(nation_id))  # lol, try again
        return result

    def list_members(self):
        # this function is mostly useless
        return [nation['nation_id'] for nation in self.nations.find()]

    def set_nation_attrib(self, nation_id, attrib, value):
        nation = self.get_nation(nation_id)
        nation[attrib] = value
        if not MAINTENANCE_MODE:
            self.nations.update({'nation_id':nation_id}, {"$set":nation}, upsert=True)


    def set_nation(self, nation_id, nation_dict):
        if not MAINTENANCE_MODE:
            self.nations.update({'nation_id':nation_id}, {"$set":nation_dict}, upsert=True)

    def increase_graph_counter(self):
        gcount = self.graph_counter.find_one()
        prev_num = gcount['graph_count']
        gcount['graph_count'] += 1
        self.graph_counter.update({'graph_count':prev_num}, {"$set":gcount})
        return prev_num + 1

    def increase_falcon_counter(self):
        fcount = self.falcon_counter.find_one()
        prev_num = fcount['falcon_record_count']
        fcount['falcon_record_count'] += 1
        self.falcon_counter.update({'falcon_record_count':prev_num}, {"$set":fcount})
        return prev_num + 1

    def increase_falcon_withdraw_counter(self):
        fcount = self.falcon_counter.find_one()
        prev_num = fcount['falcon_withdraw_count']
        fcount['falcon_withdraw_count'] += 1
        self.falcon_counter.update({'falcon_withdraw_count':prev_num}, {"$set":fcount})
        return prev_num + 1

    def create_record(self, time, gamedate, data):
        gametime_record = self.get_record_at_time(gamedate)
        record_obj = {
            'ticket':   self.increase_falcon_counter(),
            'realtime': time,
            'gametime': gamedate
        }
        record_obj.update(data)
        gametime_record['records'][record_obj['nation_id']] = record_obj
        self.falcon_records.update({'gametime': gamedate}, {"$set": gametime_record}, upsert=True)

    def create_withdraw_record(self, time, gamedate, data):
        ticket_no = self.increase_falcon_withdraw_counter()
        record_obj = {
            'ticket':   ticket_no,
            'realtime': time,
            'gametime': gamedate
        }
        record_obj.update(data)
        self.falcon_withdraw_records.insert_one(record_obj)
        return ticket_no

    def get_record_at_time(self, gametime, or_create=True):
        record = self.falcon_records.find_one({'gametime': gametime})
        if record is None and or_create:
            record = {'gametime':gametime, 'records': {}}
        return record

    def get_recent_withdraw_records(self, time_since):
        pass

    def get_recent_tax_records(self, time_since):
        time = datetime.now() - time_since
        return self.falcon_records.find({'gametime':{"$gt":time}})