================================================================================
RSSBot Explained
News feeds are generally handled using RSS feeds. RSS is an open format that
allows websites to quickly show which articles have been updated recently.
To learn more about RSS, visit: https://rss.softwaregarden.com/aboutrss.html
In RSSBot, we use the XML::RSS::Parser module from CPAN:
use XML::RSS::Parser;
Many of your favorite websites have RSS feeds. Use a search engine to find
them. In this example, we will use IRCNow's Almanack:
my $url = 'https://wiki.ircnow.org/index.php?n=Site.AllRecentChanges?action=rss';
You can replace this URL with the RSS feed from your favorite website to
change the news that your bot displays.
We recommend you download an RSS feed and open it with a text editor to
see what the RSS format looks like. Here is one sample:
Ircnow / Servers
https://wiki.ircnow.org/index.php?n=Ircnow.Servers
mkf2021-08-29T15:27:58ZSun, 29 Aug 2021 15:27:58 GMT
Let's take a look at inside the subroutine said:
sub said {
my $self = shift;
my $arguments = shift;
if ($arguments->{body} =~ /^!rss/) {
my $p = XML::RSS::Parser->new;
my $feed = $p->parse_uri($url);
foreach my $i ( $feed->query('//item') ) {
my $title = $i->query('title');
my $contributor = $i->query('dc:contributor');
my $link = $i->query('link');
$self->say(
channel => $arguments->{channel},
body => $title->text_content.' - '.$contributor->text_content.': '.$link->text_content,
);
}
}
}
First, we check if a user types a message that begins with !rss
if ($arguments->{body} =~ /^!rss/) {
If the user does, then we create a new Parser object and assign this to $p:
my $p = XML::RSS::Parser->new;
Next, we parse (analyze) the feed using $p, and assign this to $feed:
my $feed = $p->parse_uri($url);
RSS feeds contain a list of news items, and we need to process each item
one at a time. For this task, we will use a foreach loop. We are going
to query (ask) $feed for all items, then use the foreach loop to iterate
through each item. We assign each item to $i.
foreach my $i ( $feed->query('//item') ) {
Next, we query $i to find the title, contributor, and link of each item.
We assign these values to $title, $contributor, and $link.
my $title = $i->query('title');
my $contributor = $i->query('dc:contributor');
my $link = $i->query('link');
For each item, we send a message to the channel with the title, contributor,
and link.
$self->say(
channel => $arguments->{channel},
body => $title->text_content.' - '.$contributor->text_content.': '.$link->text_content,
);
================================================================================
Further Reading
XML::RSS::Parser module: https://metacpan.org/pod/XML::RSS::Parser
================================================================================
Learn about Loops
View the file ~/control to learn about control structures for perl.
================================================================================