Adsense Script - Financial
Monitor Adsense Financial account activity and receive email updates.
I created this adsense monitor because I wanted a way to automatically track my contextual advertising
account activity. My current contextual advertiser is Google AdSense (great program!) so the
utility is designed around AdSense.
This utility will log into your adsense account, retrieve your stats and write
them to a database. I have made this open source so you can personally examine the source. The adsense monitor resides on
your computer and communicates only with Google. It is well documented,
easy to understand and does not violate your adsense TOS.
I contacted Google and asked if they would have a problem with publishing the
adsense tracking utility. They stated that as long as you do not set the monitor
to log in every 5 minutes, publishing it would not be a problem. The default
is set to update your adsense database every 30 minutes. I found there is at least 30 minutes
between updates, so changing the default would probably not benefit you.
We are constantly updating this utility, so check back often. When Google changes their layout, I
adjust the adsense monitor so it keeps working. If you want to receive an update when this happens, drop me
an email and ask to be added to the adsense monitor update list.
The following files are included in the AdenseMonitor.zip file:
Changes.txt - Change log
ReadMe.txt - Documentation
OSSMTP.dll - For email updates
* Download the zip file, then extract it to a folder. Also copy the code at the bottom of this paragraph, paste it into notepade, then save it as adsense.vbs Some systems show an empty zip if you open it from a web page.
In a nutshell, you simply change the database path and enter your adsense username and
password.
|
Adsense tracking script - cut
and paste code below. |
Option Explicit
' ==============================================
' ========= USER CONFIGURED VARIABLES ==========
' ==============================================
UserName = "yourUserName@somewhere.com"
Password = "yourAdsensePassword"
' Leave blank unless your database file "adsense.mdb" is not located
' in the same directory as the script.
DatabasePath = ""
' Enter your time zone offset if necessary.
' Pacific Time [Default] = 0, Eastern Time = 3
TimeZoneOffset = 0
' Remove the apostrophe (') in the next four lines and add your
' information if you want email notification
'UseMail = "yes"
'MailFrom = "Adsense Tracker <YourName@YourAddress.com>"
'SendTo = "rcpt@mydomain.com" ' Separate multiple addresses with a comma
(,)
'Server = "webmail.mydomain.com"
' Remove the apostrophe (') in the next four lines and
' add your information if your email server requires authentication
'Authentication = "yes"
'POPServer = "mailserver.mydomain.com"
'AutUsername = "test" ' POP server username
'AutPassword = "password" ' POP server password
' Insert an apostrophe (') in the 7th line down prevent an image
' of the actual output from Google from being created. You can also
modify the filename.
' Example: "c:\wwwroot\image.htm" or "image.htm"
' Good for dropping an image in a protected dir on your webserver. This
' eliminates having to log in from home or an untrusted location with
adsense
' account information. Gives payment history and funds.
ImagePathAndFilename = "esadmo-image.htm"
' ======================================================
' == NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
' ======================================================
' Adsense.vbs v2.5
' Copyright Adsense-Monitor.com
' Distributed under the GNU General Public License (GPL)
' Updated 11-16-2004
'
' Visit http://www.adsense-monitor.com to get the latest version of this
script!
'
'
' INSTRUCTIONS:
' 1. Set the user variables in the configuration section as desired.
' 2. Run the script to test it. It creates a new database file and
' registers the SMTP component automatically if needed.
' 3. Use Scheduled Tasks in Control Panel to schedule the script
' to run every 30 minutes.
'
' NOTES:
' 1. If you schedule this program to run, make sure it's has at least
' a 15 minute interval. Adsense servers do not update statistics much
' faster than 30 minutes.
' 2. You may need Microsoft's MSXML 4.0 - http://www.xmlblueprint.com/MSXML.htm
' 3. You may need Windows scripting, which can be found at:
' http://msdn.microsoft.com/library/default.asp?url=/nhp/default.asp?contentid=28001169
' 4. You may need to download MDAC 2.8 from
http://www.microsoft.com/data/download.htm
' 5. For email, we use the OstroSoft SMTP component, it's the OSSMTP.DLL
file included with this zipped script
' If for some reason you need to manually install OSSMTP.dll, simply
copy the file into the system32
' directory and type regsvr32 ossmtp.dll from a command prompt.
' * |Full installation for OstroSoft SMTP component (in case your system
' |doesn't have VB run-time libraries) is available for download at
' |http://www.ostrosoft.com/download/full/smtp_component.exe
'
' Declare variables
Dim UserName, Password, DatabasePath, DataToPost
Dim objFSO, strURL1, strURL2, strURL3, objWshShell, objHTTP
Dim FullPageData, PageData, PaymentHistory
Dim LimitingText, StartOfIm, EndOfIm, Impressions
Dim StartOfC, EndOfC, Clicks
Dim StartOfCtr, EndOfCtr, Clickrate
Dim StartOfCPM, EndOfCPM, CPM
Dim StartOfE, EndOfE, Earnings, Flag
Dim objConn, objRS, adOpenDynamic, adLockPessimistic
Dim UseMail, MailFrom, SendTo, Server, Authentication
Dim POPServer, AutUsername, AutPassword, oSMTPSession
Dim TheCurrentDate, StartOfMT, EndOfMT, MonthlyTotal
Dim ErrorFlag, ErrorCode, ImagePathAndFilename
Dim TimeZoneOffset, AdjustedTime
Dim MonthlyPoint, RecordStart
Dim StripJPGstart, StripJPGend, T
' Install the SMTP component if it's not already installed
InstallSMTPComponentIfNeeded
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get current path to database file
If DatabasePath = "" Then
DatabasePath = objFSO.GetParentFolderName(WScript.ScriptFullName)
DatabasePath = objFSO.BuildPath(DatabasePath, "adsense.mdb")
End If
' Try to create the database if it doesn't exist
CreateAdsenseAccessDatabaseIfNotExist DatabasePath
' Check that the database file exists
If Not objFSO.FileExists(DatabasePath) Then
WScript.Echo "Error running adsense script." & _
" The database file '" & DatabasePath & "' does not exist."
WScript.Quit
End If
Set objFSO = Nothing
' Make HTTPS request to Adsense server and retrieve the login page.
strURL1 = "https://www.google.com/adsense/login.do"
strURL2 = "strURL2 = "https://www.google.com/adsense/reports-aggregate?product=afc&dateRange.dateRangeType=simple&dateRange.simpleDate=thismonth&dateRange.customDate.start.month=11&dateRange.customDate.start.day=17&dateRange.customDate.start.year=2004&dateRange.customDate.end.month=11&dateRange.customDate.end.day=17&dateRange.customDate.end.year=2004&groupByPref=date&reportType=property&null=Display+Report" "
strURL3 = "https://www.google.com/adsense/reports-payment"
Set objWshShell = CreateObject("WScript.Shell")
Set objHTTP = CreateObject("MSXML2.XMLHTTP")
' Create request URI
DataToPost="username=" & UserName & "&password=" & Password
' Perform request for Main Page
On Error Resume Next
objHTTP.Open "POST", strURL1, FALSE
objHTTP.SetRequestHeader "lastCached", now()
objHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.Send DataToPost
ErrorCode = err.number
On Error GoTo 0
If ErrorCode <> 0 Then
WScript.Echo "I could not contact Google" & vbCrLf & "Check internet
connection"
WScript.Quit
End If
' Perform request for Monthly Stats
objHTTP.Open "get", strURL2, FALSE
objHTTP.SetRequestHeader "lastCached", now()
objHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.Send
FullPageData = objHTTP.ResponseText
FullPageData = Right(FullPageData,Len(FullPageData)-Instr(FullPageData,"<body>")-5)
PageData = Replace(FullPageData," "," ")
' Perform request
objHTTP.Open "get", strURL3, FALSE
objHTTP.SetRequestHeader "lastCached", now()
objHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.Send
PaymentHistory = objHTTP.ResponseText
FullPageData = FullPageData & "<BR><BR>" &
Right(PaymentHistory,Len(PaymentHistory)-Instr(PaymentHistory,"<body>")-5)
FullPageData = Right(FullPageData,Len(FullPageData)-InStr(FullPageData,"</form>
</table>") + 18)
FullPageData = Right(FullPageData,Len(FullPageData)-InStr(FullPageData,"</form>
</table>") + 18)
FullPageData = Right(FullPageData,Len(FullPageData)-InStr(FullPageData,"</div>")
+ 4)
Do While InStr(FullPageData,"<img") <> 0
StripJPGstart = InStr(FullPageData,"<img")
StripJPGend = InStr(StripJPGstart,FullPageData,"</a>")
FullPageData = Left(FullPageData,StripJPGstart + 1) +
Right(FullPageData,Len(FullPageData) - StripJPGend)
Loop
Set objWshShell = Nothing
Set objHTTP = Nothing
' Parse the returned HTML and extract the statistics
TimeZoneOffset = TimeZoneOffset * 60 ' convert offset to minutes
AdjustedTime = DateAdd("n",-TimeZoneOffset,Now) ' use minutes instead of
hours to adjust local time
TheCurrentDate = Day(AdjustedTime) & ", " & Year(AdjustedTime)
MonthlyPoint = "<tr class=""totals"">"
PageData = Right(PageData,Len(PageData)-Instr(PageData,TheCurrentDate))
StartofToday = Instr(PageData,TheCurrentDate) ' if this returns zero,
today's stats do not yet exist in the report.
PageData = Right(PageData,Len(PageData)-Instr(PageData,TheCurrentDate))
'Grab today's stats
RecordStart = "<td style=""text-align:right"">" ' This is 29 in length
StartOfIm = Instr(PageData, RecordStart) + 29
EndOfIm = Instr(StartOfIm, PageData, "</td>") - 1
Impressions = Trim(Mid(PageData,StartOfIm,(EndOfIm - StartOfIm)))
If InStr("0123456789",Left(Impressions,1)) AND StartofToday > 0 Then
StartOfC = Instr(EndOfIm, PageData,RecordStart) + 29
EndOfC = Instr(StartOfC, PageData,"</td>") - 1
Clicks = Trim(Mid(PageData,StartOfC,(EndOfC-StartOfC)))
StartOfCtr = Instr(StartOfC, PageData,RecordStart) + 29
EndOfCtr = Instr(StartOfCtr, PageData,"</td>") - 1
Clickrate = Trim(Mid(PageData,StartOfCtr,(EndOfCtr-StartOfCtr)))
Clickrate = Replace(Clickrate, "%", "")
StartOfCPM = InStr(StartOfCtr, PageData,RecordStart) + 29 '
EndOfCPM = Instr(StartOfCPM, PageData,"</td>") - 1 '
CPM = Trim(Mid(PageData,StartOfCPM,(EndOfCPM-StartOfCPM)))'
CPM = Replace(CPM, "%", "") '
StartOfE = Instr(StartOfCPM, PageData,RecordStart) + 29
EndOfE = Instr(StartOfE, PageData,"</td>") - 1
Earnings = Trim(Mid(PageData,StartOfE,(EndOfE-StartOfE)))
Earnings = Replace(Earnings, "$", "")
'Truncate monthly total then skip 3 totals until we get monthly $
StartOfMT = InStr(EndOfE, PageData, MonthlyPoint) + 19
PageData = Right(PageData,Len(PageData)-StartOfMT)
StartOfMT = Instr(PageData,RecordStart) + 29
For T = 4 to 1 Step -1
StartOfMT = Instr(StartOfMT,PageData,RecordStart) + 29
Next
EndOfMT = Instr(StartOfMT, PageData,"</td>") - 1
MonthlyTotal = Trim(Mid(PageData,StartOfMT, (EndOfMT-StartOfMT)))
MonthlyTotal = Replace(MonthlyTotal, "$", "")
Flag = " "
Else
Impressions = "0"
Clicks = "0"
ClickRate = "0"
Earnings = "0"
MonthlyTotal = "0"
Flag = "- No Data -"
End If
' Insert the data into the databaes
Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objConn.Open "PROVIDER=MICROSOFT.JET.OLEDB.4.0;DATA SOURCE=" &
DatabasePath
adOpenDynamic = 2
adLockPessimistic = 2
objRS.Open "adsense", objConn, adOpenDynamic, adLockPessimistic
objRS.AddNew
objRS("QueryDate") = Now
objRS("Impressions") = Impressions
objRS("Clicks") = Clicks
objRS("Clickrate") = ClickRate
objRS("Earnings") = Earnings
objRS("MonthlyTotal") = MonthlyTotal
objRS("Flag") = Flag
objRS.Update
objRS.Close
Set objRS = Nothing
objConn.Close
Set objConn = Nothing
' Send an email if necessary
If UseMail = "yes" Then SendEmail MailFrom, SendTo, Server,
Authentication, POPServer, AutUserName, AutPassword
' Write image to a file if necessary
If ImagePathAndFileName <> "" Then
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(ImagePathAndFilename, True)
MyFile.WriteLine("<html><head><Title>Adsense-Monitor.com Adsense
Tracking Script</Title></head><body><h1 align='center'>Adsense Tracking
Script</h1><center>Check for <a href=""http://www.adsense-monitor.com"">Adsense</a>
Script Updates<hr><br>Created at " & Now() & "</center>" & vbCrLf &
FullPageData)
MyFile.Close
End if
' ======================================================
' ================ Subroutine Section ================
' ======================================================
' Register the OSSMTP dll if it isn't installed.
' Requires the script to be run as administrator.
Sub InstallSMTPComponentIfNeeded()
Dim oSMTPSession, objFSO, objWshShell
Dim strComponentPath, adSystemFolder, strCommand
' Test if the component is installed
On Error Resume Next
Set oSMTPSession = CreateObject("OSSMTP.SMTPSession")
ErrorCode = Err.Number
On Error Goto 0
' If no error, then the object is installed and quit.
If ErrorCode = 0 Then
Set oSMTPSession = Nothing
Exit Sub
End If
' If any other error besides "can't create object error"
' Then raise the error
If ErrorCode <> 429 Then
Err.Raise ErrorCode
End If
' Otherwise, install the object
Set objFSO = CreateObject("Scripting.FileSystemObject")
strComponentPath = objFSO.GetParentFolderName(WScript.ScriptFullName)
strComponentPath = objFSO.BuildPath(strComponentPath, "OSSMTP.dll")
' Check if the file exists
If Not objFSO.FileExists(strComponentPath) Then
WScript.Echo "Error, the required component file '" & _
strComponentPath & "' was not found. Can not install."
WScript.Quit
End If
' Copy the file to the system directory
adSystemFolder = 1
objFSO.CopyFile strComponentPath, _
objFSO.BuildPath(objFSO.GetSpecialFolder(adSystemFolder), "OSSMTP.dll")
' Register the component
strComponentPath =
objFSO.BuildPath(objFSO.GetSpecialFolder(adSystemFolder), _
"OSSMTP.dll")
strCommand = "regsvr32 /s " & Chr(34) & strComponentPath & Chr(34)
Set objWshShell = CreateObject("WScript.Shell")
objWshShell.Run strCommand, 0, True
' wait a second to let it properly install
WScript.Sleep(1000)
Set objWshShell = Nothing
Set objFSO = Nothing
End Sub
' Create the adsense statistics database
Sub CreateAdsenseAccessDatabaseIfNotExist(strDBPath)
Dim objCatalog, objTable, objIndex, objColumn
Dim objFSO
Dim adInteger, adDate, adVarWChar, adDouble
' If the file exists, just return
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDBPath) Then
Exit Sub
Set objFSO = Nothing
End If
' Create the reference database
Set objCatalog = CreateObject("ADOX.Catalog")
objCatalog.Create "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strDBPath
' Add table
Set objTable = CreateObject("ADOX.Table")
objTable.Name = "AdSense"
adInteger = 3
adDate = 7
adDouble = 5
adVarWChar = 202
' Append columns
Set objColumn = CreateObject("ADOX.Column")
objColumn.Name = "AdsenseID"
objColumn.Type = adInteger
Set objColumn.ParentCatalog = objCatalog
objColumn.Properties("AutoIncrement") = True
objTable.Columns.Append objColumn
Set objColumn = Nothing
objTable.Columns.Append "QueryDate", adDate
objTable.Columns.Append "Impressions", adInteger
objTable.Columns.Append "Clicks", adInteger
objTable.Columns.Append "ClickRate", adDouble
objTable.Columns.Append "Earnings", adDouble
objTable.Columns.Append "MonthlyTotal", adDouble
objTable.Columns.Append "Flag", adVarWChar, 100
' Add indexes
Set objIndex = CreateObject("ADOX.Index")
objIndex.Name = "IDX_AdsenseID"
objIndex.Columns.Append "AdsenseID"
objIndex.Unique = True
objIndex.PrimaryKey = True
objIndex.IndexNulls = False
objTable.Indexes.Append objIndex
Set objIndex = Nothing
Set objIndex = CreateObject("ADOX.Index")
objIndex.Name = "IDX_QueryDate"
objIndex.Columns.Append "QueryDate"
objIndex.Unique = False
objIndex.PrimaryKey = False
objIndex.IndexNulls = False
objTable.Indexes.Append objIndex
Set objIndex = Nothing
' Append the table
objCatalog.Tables.Append objTable
Set objTable = Nothing
' Clean up
Set objCatalog = Nothing
Set objTable = Nothing
End Sub
' Send Mail
Sub SendEmail(MailFrom, SendTo, Server, Authentication, POPServer,
AutUserName, AutPassword)
Set oSMTPSession = CreateObject("OSSMTP.SMTPSession")
With oSMTPSession
.MailFrom = MailFrom
.SendTo = SendTo
.Server = Server
.Port = 25
.MessageSubject = "Adsense Update"
.MessageText = "Adsense Statistics as of " & Now & vbCrLf & _
" Account: " & UserName & vbCrLf & _
" Earnings $" & Earnings & _
" Monthly Earnings $" & MonthlyTotal & _
" Impressions: " & Impressions & vbCrLf & _
" Clicks: " & Clicks & " CTR: " & clickrate
' Authenticate if your mail server requires it
If Authentication = "yes" Then
.AuthenticationType = 1 'POP3 authentication
.POPServer = POPServer
.Username = AutUserName
.Password = AutPassword
End If
' If SMTP Component incorrectly detects message date/time,
' you can over-write it using TimeStamp property
'.TimeStamp = "20 Oct 2003 19:22:50"
' SMTP Component defaults to "US-ASCII" character set,
' to change it use Charset property
'.Charset = "GB2312"
.SendEmail
End With
Set oSMTPSession = Nothing
End Sub |
NOTICE: There is no benefit to running the job at intervals of less than 30 minutes.
If you want intervals of less than 15 minutes, I suggest you check with Google first.
* Free add-on modules *
Track Adsense Clicks! Find out who clicked on your ad and when.
AdSense Report Creator creates a HTML
report from the database created by adsense.vbs. Each report file is named
MMDDYY.htm, so you have a report for each day.
Shailesh Humbad's Adsense Database Viewer
Windows TIP to prevent script from prompting you for OK.
The default scripting engine for Windows 2000 is Wscript. If you use
Cscript, you will not be prompted when an error occurs.
To change the default, type:
cscript //h:cscript //s
Typing cscript /? generates:
Microsoft (R) Windows Script Host Version 5.1 for Windows
Copyright (C) Microsoft Corporation 1996-1999. All rights reserved.
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from
displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WS job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at
execution time
//S Save current command line options for this user
//T:nn Time out in seconds: Maximum time a script is permitted
to run
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
Disclaimer: I am not responsible, implied or otherwise, for any damage resulting from use of this utility. Use at your own risk.
|