In the absence of true integrated plugins in WordPress to perform scripted actions (updating certain fields of a WooCommerce item page), here’s an improvised PowerShell script that performs this rudimentary function. This is a slight improvement over the method of manually updating prices of certain cryptocurrencies; although, this should only be considered an intermediary development before devising a much more robust method that could run ‘headless’ in Python rather than PowerShell. Better yet, direct database updates would be the final solution for best performance and security.
# updateCoinPrices.ps1
# version: 0.01
# $bitcoinUri='https://api.coinstats.app/public/v1/coins/bitcoin?currency=USD'
# $etherUri='https://api.coinstats.app/public/v1/coins/ethereum?currency=USD'
# $dogeUri='https://api.coinstats.app/public/v1/coins/dogecoin?currency=USD'
$coinName='nano'
$coinApi='https://api.coinstats.app/public/v1/coins/nano?currency=USD'
$coinPage='https://dragoncoin.com/wp-admin/post.php?post=3302&action=edit'
$username='SERVICEACCOUNTUSERNAMEHERE'
$password='SOMEVERYCOMPLEXPASSWORDHERE'
$expectedPageTitle='Edit product ‹ Dragon Coin — WordPress'
$coinFieldId='_regular_price'
$buttonId='publish'
$updateSeconds=120
$markupPercent=10
$decimalPoints=2
$timesToDeterminePause=3
function autologinFirefox{
param(
$url,
$username,
$password,
$usernameElementId='user_login',
$passwordElementId='user_pass',
$submitButtonId='wp-submit',
$exitWhenDone=$false
)
$ErrorActionPreference = 'continue'
# Initial validation
if(!$url){write-warning "No URL specified.";return $false}
function includeSelenium{
Import-Module Selenium -ea SilentlyContinue
if (!(get-module selenium -EA SilentlyContinue)){
try{
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
if(!(Get-PackageProvider Nuget -ea SilentlyContinue)){Install-PackageProvider -Name NuGet -Force}
# Defining $ENV:ChocotaleyInstall so that it would be called by refreshenv
$ENV:ChocolateyInstall = Convert-Path "$((Get-Command choco).Path)\..\.."
Import-Module "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
Install-Module Selenium -Force -Confirm:$False
Update-SessionEnvironment
Import-Module Selenium
return $true
}catch{
write-warning $_
return $false
}
}else{
return $true
}
}
function includeFirefox{
$firefoxInstalled=get-command "C:\Program Files\Mozilla Firefox\firefox.exe"
if (!$firefoxInstalled){
try{
if (!(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))}
choco install firefox --ignore-checksums -y
return $true
}catch{
write-warning $_
return $false
}
}else{
return $true
}
}
function invokeSelenium($url,$userName,$password,$usernameElementId,$passwordElementId,$submitButtonId){
$ErrorActionPreference = "Stop"
function closeSelenium($selenium){
if($selenium){
$selenium.close()
$selenium.quit()
}
}
function noLogin($url){
$seleniumFirefox = New-Object "OpenQA.Selenium.firefox.FirefoxDriver"
$seleniumFirefox.Navigate().GoToURL($url)
$title=$seleniumFirefox.Title
write-host "Page reached: '$title'"
$trustedSiteError=$title -match '^Error'
if($trustedSiteError){
write-host "An site trust issue has been detected. Adding root domain to the trusted sites list to resolve this issue."
addDomainToTrustedSites $url
closeSelenium $seleniumIe
return $false
}
else{
return $seleniumFirefox
}
}
function login($url,$username,$password,$usernameElementId,$passwordElementId,$submitButtonId){
$seleniumFirefox = New-Object "OpenQA.Selenium.firefox.FirefoxDriver"
$seleniumFirefox.Navigate().GoToURL($url)
$userField=$seleniumFirefox.FindElementById($usernameElementId)
$userField.clear()
$userField.SendKeys($username)
$passwordField=$seleniumFirefox.FindElementById($passwordElementId)
$passwordField.SendKeys('')
$passwordField.clear()
$passwordField.SendKeys($password)
$submitButton=$seleniumFirefox.FindElementById($submitButtonId)
$submitButton.Click()
$title=$seleniumFirefox.Title
write-host "Page reached: '$title'"
$trustedSiteError=$title -match '^Error'
if($trustedSiteError){
write-warning "A site trust issue has been detected."
closeSelenium $seleniumFirefox
return $false
}else{
return $seleniumFirefox
}
}
try{
$isLogin=$userName,$password,$usernameElementId,$passwordElementId,$submitButtonId|?{!(!$_)}
if($isLogin){
write-host "Login to $url as $userName..."
$firefox=login $url $userName $password $usernameElementId $passwordElementId $submitButtonId
}else{
write-host "Accesing $url without login..."
$firefox=nologin $url
}
return $firefox
}
catch{
Write-Warning $Error[0].Exception.Message
return $false
}
}
try{
write-host "Username`t: $username`r`nPassword`t: $(!(!$password))`r`nusernameElementId`t: $usernameElementId`r`npasswordElementId`t: $passwordElementId`r`nsubmitButtonId`t: $submitButtonId"
if(!(includeSelenium)){
write-warning "cannot proceed without selenium"
return $null
}
if(!(includeFirefox)){
write-warning "cannot proceed without Firefox"
return $null
}
$null=get-process firefox -ea silentlycontinue|stop-process -force -ea silentlycontinue
if(get-module selenium -ea SilentlyContinue){
$isLogin=$userName,$password,$usernameElementId,$passwordElementId,$submitButtonId|?{!(!$_)}
if($isLogin){
$selenium=invokeSelenium $url $userName $password $usernameElementId $passwordElementId $submitButtonId
}else{
write-host "No username or password are given. Proceeding to access only the provided URL."
$selenium=invokeSelenium $url
}
}else{
write-warning "Please manually verify that the Selenium module is installed before retrying this function."
}
if($selenium){
if($exitWhenDone){
return $true
}else{
return $selenium
}
}else{
write-warning "There were errors preventing a successful login."
return $false
}
}
catch {
write-warning "$_"
return $false
}
}
function getCoinPrice{
param(
$commodityName='name',
$commodityUri
)
$priceData=Invoke-RestMethod $commodityUri
$price=$priceData.coin.price
write-host "$(get-date) --- $commodityName price is $price"
return [hashtable]@{
$commodityName=$price
}
}
function updateFieldValues{
param(
$browser,
$fieldId,
$value,
$countMax=3
)
$erroractionpreference='stop'
$success=$false
$count=0
do{
try{
$field=$browser.FindElementById($fieldId)
$field.clear()
$field.SendKeys($value)
$success=$true
}catch{
write-warning $_
$count++
sleep 1
}
}until($success -or ($count -ge $countMax))
}
function updateCoinPage{
param(
$coinName='nano',
$coinApi='https://api.coinstats.app/public/v1/coins/nano?currency=USD',
$coinPage='https://dragoncoin.com/wp-admin/post.php?post=3302&action=edit',
$username,
$password,
$expectedPageTitle='Edit product ‹ Dragon Coin — WordPress',
$coinFieldId='_regular_price',
$buttonId='publish',
$markupPercent=15,
$decimalPoints=2,
$updateSeconds=120,
$timesToDeterminePause=3
)
function getFirefoxSession{
param(
$url,
$username,
$password
)
$firefoxSession=autologinFirefox $url $username $password
$title=$firefoxSession.Title
if($title -notlike $expectedPageTitle){
$null=get-process firefox | stop-process -force
$firefox=autoLoginFirefox $coinPage $username $password
if($firefox.Title -ne $expectedPageTitle){$firefoxSession.Navigate().GoToURL($url)}
clear-Host
write-host "Connected to $url"
}
return $firefoxSession
}
$countDown=0
Do{
if($countDown -lt $timesToDeterminePause){
$changesDetected=$false
$title=$firefox.Title
if($title -notlike $expectedPageTitle){
$firefox=getFirefoxSession $coinPage $username $password
}
$coinPrice=[math]::round($(getCoinPrice $coinName $coinApi).$coinName*$(1+($markupPercent/100)),$decimalPoints)
if(!$coinPrice){
write-warning "Cannot update if $coinName price value is Null"
}elseif($previousCoinPrice -ne $coinPrice){
updateFieldValues $firefox $coinFieldId $coinPrice
$changesDetected=$true
}else{
write-host "$coinName prices haven't changed."
}
if($changesDetected){
$submitButton=$firefox.findElementById($buttonId)
if($submitButton.enabled){
try{
$submitButton.Click()
write-host "$(get-date) --- $coinName price has been updated to $coinPrice"
}catch{
write-warning $_
}
$countDown=0
}else{
write-warning "Firefox session is not working. Timing out 5 minutes..."
Start-Sleep 300
}
}else{
$countDown++
}
$previousCoinPrice=$coinPrice
write-host "time-out $updateSeconds seconds until next iteration"
Start-Sleep -s $updateSeconds
}else{
Start-Sleep -s $updateSeconds
$countDown=0
}
}until($false)
}
updateCoinPage -coinName $coinName `
-coinApi $coinApi `
-coinPage $coinPage `
-username $username `
-password $password `
-expectedPageTitle $expectedPageTitle `
-coinFieldId $coinFieldId `
-buttonId $buttonId `
-markupPercent $markupPercent `
-decimalPoints $decimalPoints `
-updateSeconds $updateSeconds `
-timesToDeterminePause $timesToDeterminePause
Categories: