Ejemplo n.º 1
0
	def _checkMinMAxValue(self, num):
		accept = self.PASSED

		if self.min_value is not None:
			if float(num) < self.min_value:
				accept = self.MIN

		if self.max_value is not None:
			if float(num) > self.max_value:
				accept = self.MAX
		
		if accept is not self.PASSED:
			logger.warning(f"Set value ({num}) not within accepted range")
		
		return accept
Ejemplo n.º 2
0
def sendtelegram(chatid, msg):
    #    try:
    splitted_text = telebot.util.split_string(msg, 4096)
    for text in splitted_text:
        try:
            bot.send_message(chatid, text, parse_mode="markdown")
        except telebot.apihelper.ApiHTTPException as e:
            logger.warning(
                "ConnectionError - Sending again after 5 seconds!!!")
            logger.warning("HTTP Error Code: {}".format(e.result))
            sleep(5)
            bot.send_message(chatid, text, parse_mode="markdown")
        except:
            logger.error(
                "ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(chatid))
            logger.error("Error: {}".format(sys.exc_info()[0]))
Ejemplo n.º 3
0
def user_ok(bot, connection, allowmode, tggroup, chat_id):
    cursor = connection.cursor()

    # check if user is blocked
    cursor.execute("select count(*) from userblock where chatid = '%s'" %
                   (chat_id))
    if cursor.fetchone()[0] == 1:
        return False

    if not allowmode:
        return True

    # check if user is in allow Table
    cursor.execute("select count(*) from userallow where chatid = '%s'" %
                   (chat_id))
    if cursor.fetchone()[0] == 1:
        return True

    # check TGGroup
    if tggroup:
        try:
            if chat_id in tg_cache:
                time_delta = datetime.now() - tg_cache[chat_id]
                if time_delta.total_seconds() / 60 < tg_cache_timeout:
                    return True
                else:
                    tg_cache.pop(chat_id)

            result = bot.get_chat_member(tggroup, chat_id)
            if result.status in is_member:
                tg_cache[chat_id] = datetime.now()
                return True
        except telebot.apihelper.ApiHTTPException as e:
            logger.warning("HTTP Error Code: {}".format(e.result))
        except:
            logger.error(
                "ERROR IN GETTING MEMBER FROM GROUP {}".format(tggroup))
            logger.error("Error: {}".format(sys.exc_info()[0]))

    return False
Ejemplo n.º 4
0
def sendmonster(bot, config, connection, pkmn_loc, geoprovider, geofences,
                allowmode):
    cursor = connection.cursor()

    botid = bot.get_me().id
    venuetitle = config['venuetitle']
    venuemsg = str(config['venuemsg'])
    ivmsg = str(config['ivmsg'])
    tggroup = config.get('tggroup', '')

    while True:
        message = pkmn_queue.get()

        pkmn_id = (message['pokemon_id'])

        # set monster info
        #
        try:
            pkmn_name = pkmn_loc[str(pkmn_id)]["name"]
        except:
            pkmn_name = "{} NOTFOUND".format(str(pkmn_id))
            logger.warning("{} not found in monster.json".format(str(pkmn_id)))

        # check if in geofence
        #
        if geofences:
            inside = False
            for geofence in geofences.keys():
                mypath = mplPath.Path(geofences[geofence])
                if mypath.contains_points(
                    [tuple((message['latitude'], message['longitude']))]):
                    inside = True
                    break
            if not inside:
                logger.info("{}({}) outside geofence".format(
                    pkmn_name, pkmn_id))
                continue

        pkmn_despawn = datetime.datetime.fromtimestamp(
            int(message['disappear_time'])).strftime('%H:%M:%S')
        logger.info("{}({}) until {} @ {},{}".format(pkmn_name, pkmn_id,
                                                     pkmn_despawn,
                                                     message['latitude'],
                                                     message['longitude']))

        # calculate IV if encounting
        #
        try:
            pkmn_iv = float((
                (message['individual_attack'] + message['individual_defense'] +
                 message['individual_stamina']) * 100 / 45)).__round__(2)
            logger.info(
                "IV:{:.2f} CP:{:4d} ATT:{:2d} DEF:{:2d} STA:{:2d}".format(
                    pkmn_iv, message['cp'], message['individual_attack'],
                    message['individual_defense'],
                    message['individual_stamina']))
        except:
            pkmn_iv = "None"
            message['individual_attack'] = "??"
            message['individual_defense'] = "??"
            message['individual_stamina'] = "??"
            message['cp'] = "??"
            message['pokemon_level'] = "??"

        if not 'boosted_weather' in message:
            message['boosted_weather'] = 0

        # add missing data to message
        message['iv'] = pkmn_iv
        message['name'] = pkmn_name
        message['despawn'] = pkmn_despawn
        message['geo_ok'] = False

        # get all chatids for the monster
        # no blocked chat id
        #
        connection.ping(reconnect=True)
        cursor.execute(
            "select chatid,iv,level from userassign where pkmnid = '%s' and \
                        chatid in (select chatid from user where botid = '%s')"
            % (pkmn_id, botid))
        result_pkmn = cursor.fetchall()

        if len(result_pkmn) > 0:

            # send monster message to all
            #
            for chat_id, iv, level in result_pkmn:

                if not user_ok(bot, connection, allowmode, tggroup, chat_id):
                    logger.info(
                        "ChatID {} not allowed for this Bot but has assignments"
                        .format(chat_id))
                    continue

                # get the user details
                cursor.execute(
                    "select lat,lon,dist from user where chatid = '%s'" %
                    (chat_id))
                latlon = cursor.fetchone()
                lat = float(latlon[0])
                lon = float(latlon[1])
                dist = float(latlon[2])

                # check distance
                dist_ok = True
                if dist > 0:
                    pkmn_dist = distance.distance(
                        (lat, lon),
                        (message['latitude'], message['longitude'])).kilometers
                    if pkmn_dist > dist:
                        dist_ok = False
                        logger.info(
                            "{} long distance: dist: {}  pkmn_dist: {}".format(
                                chat_id, dist, pkmn_dist))

                # check level
                if message['pokemon_level'] == '??':
                    level_ok = True
                elif int(message['pokemon_level']) >= level:
                    level_ok = True
                else:
                    level_ok = False

                if not (dist_ok and level_ok):
                    continue

                if message['iv'] == "None":
                    if iv == -1:
                        # get geo only if not set
                        if not message['geo_ok']:
                            geo = geo_reverse(geoprovider, message['latitude'],
                                              message['longitude'])
                            message['road'] = "{} {}".format(geo[0], geo[1])
                            message['postcode'] = geo[2]
                            message['town'] = geo[3]
                            message['geo_ok'] = True

                        venuetitle1 = textsub(venuetitle, message)
                        venuemsg1 = textsub(venuemsg, message)
                        try:
                            bot.send_venue(chat_id, message['latitude'],
                                           message['longitude'], venuetitle1,
                                           venuemsg1)
                            logger.info(
                                "Send Telegram message to {} Monster {}({})".
                                format(chat_id, pkmn_name, pkmn_id))
                        except telebot.apihelper.ApiTelegramException as e:
                            if e.result_json['error_code'] == 403:
                                bot_was_blocked(connection, botid, chat_id)
                        except telebot.apihelper.ApiHTTPException as e:
                            logger.error("Connection Error")
                            logger.error("HTTP Error Code: {}".format(
                                e.result))
                        except:
                            logger.error(
                                "ERROR IN SENDING TELEGRAM MESSAGE TO {}".
                                format(chat_id))
                            logger.error("Error: {}".format(sys.exc_info()[0]))
                    else:
                        logger.info(
                            "No message send to {}. SearchIV set but Monster {}({}) not encountered"
                            .format(chat_id, pkmn_name, pkmn_id))
                elif message['iv'] >= iv:
                    try:
                        # get geo only if not set
                        if not message['geo_ok']:
                            geo = geo_reverse(geoprovider, message['latitude'],
                                              message['longitude'])
                            message['road'] = "{} {}".format(geo[0], geo[1])
                            message['postcode'] = geo[2]
                            message['town'] = geo[3]
                            message['geo_ok'] = True

                        ivmsg1 = textsub(ivmsg, message)

                        bot.send_message(chat_id, ivmsg1)
                        bot.send_location(chat_id, message['latitude'],
                                          message['longitude'])
                        logger.info(
                            "Send Telegram IV message to {} Monster {}({})".
                            format(chat_id, pkmn_name, pkmn_id))
                    except telebot.apihelper.ApiTelegramException as e:
                        if e.result_json['error_code'] == 403:
                            bot_was_blocked(connection, botid, chat_id)
                    except telebot.apihelper.ApiHTTPException as e:
                        logger.error("Connection Error")
                        logger.error("HTTP Error Code: {}".format(e.result))
                    except:
                        logger.error(
                            "ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(
                                chat_id))
                        logger.error("Error: {}".format(sys.exc_info()[0]))
                else:
                    logger.info(
                        "No message send to {}. SearchIV to low for Monster {}({})"
                        .format(chat_id, pkmn_name, pkmn_id))
Ejemplo n.º 5
0
##################
# set geofence
geofence = False
if geofencefile:
    try:
        with open(geofencefile, "r") as fencefile:
            geofence = {}
            for i in fencefile:
                if re.search("\[.*\]", i):
                    name = i.split()[0]
                    geofence[name] = []
                else:
                    geofence[name].append(tuple(map(float, i.split(','))))
    except:
        logger.warning("Can not open geofence file {}".format(geofencefile))
        logger.warning("Error: {}".format(sys.exc_info()[0]))
        logger.warning("setting geofence to False")


##################
#
def sendtelegram(chatid, msg):
    #    try:
    splitted_text = telebot.util.split_string(msg, 4096)
    for text in splitted_text:
        try:
            bot.send_message(chatid, text, parse_mode="markdown")
        except telebot.apihelper.ApiHTTPException as e:
            logger.warning(
                "ConnectionError - Sending again after 5 seconds!!!")