Power Users: More on Automation.
Last week we provided an example of having a Perl script use ProjectForum's web interface to add a user to a page. Here's a similar example, this time where the script posts a comment to a forum page. The first part is pretty similar, setting up some variables with the information the program needs, and then logging in as site administrator to ensure our script has full access to the entire site.
my $siteurl = "http://127.0.0.1:3455/"; # base URL of the site
my $siteadminpass = "abc123" ; # site administration password
my $urlprefix = "1" ; # URL prefix of the group we're posting to
my $pagename = "Home" ; # name of page we're posting to
my $username = "Joe User" ; # name of user posting
my $message = "This is my post" ; # what to post
use HTML::Form;
use LWP;
my $ua = LWP::UserAgent->new;
$ua->cookie_jar( {} );
# signin as admin, which will set the cfadmintoken cookie
my $response = $ua->get($siteurl . "admin/adminsignin.html");
my $form = HTML::Form->parse($response->decoded_content, $response->base);
$form->value("adminpasswd", $siteadminpass);
$ua->request($form->click());
This next bit is what actually does the posting; it's a bit tricky in that we have to find the right form to post to (there are normally two, the search form and the comment posting form):
# now go to the page and do the post
$response = $ua->get($siteurl . $urlprefix . "/" . $pagename);
my @forms = HTML::Form->parse($response->decoded_content, $response->base);
for ($i=0;$i<@forms;$i++) {
my $form = @forms[$i];
my $attrs = %$form->{'attr'};
if (%$attrs->{'name'} eq "commentform") {
$form->value('comments', "[" . $username . "]: " . $message);
$ua->request($form->click());
}
}
The value of this isn't in these simple self-contained examples of course, but when you embed them into some other script. A few simple examples:
- You have some other program that runs every day to produce some summary sales data; it can then use this script to post the results to a ProjectForum page.
- Your ecommerce system can automatically post a record of every transaction into your forum.
- You can hook up your email (e.g. with postfix) so that when you receive email at a certain address, it runs a script which automatically posts that email into your forum. Your email script might use the subject of the email to decide exactly which page in the forum the email gets posted to.

Comments