Welcome!

Agile Computing Authors: Liz McMillan, Yeshim Deniz, Elizabeth White, Zakia Bouachraoui, Pat Romanski

Blog Feed Post

Listen To Twitter With The PoshMouth PowerShell Service!

PoshMouth A few weeks ago I was scanning through my daily PowerTips from PowerShell.com and came across one that covered Using COM Objects to Say Hi. In this tip, they describe how to use the Microsoft Speech API (SAPI) to convert text to play through the the windows audio system.  Of course I started tinkering around to see how SAPI sounded with various text strings.

Once the novelty of that wore off, the next thing I thought of was how I could extend my PowerShell Twitter library PoshTweet with the SAPI library.  I quickly built a little script that called the PoshTweet Get-TwitterFriendsTimeline and passed the status values to this call and it just worked!

While that was a great proof of concept, it's not very practical.  I quickly wrote up the following set of requirements of how I would "like" this little project to come out.

  1. It should work as a centralized service.
  2. The audio should be persistent.
  3. It should be a controlled system.  Running off the public timeline would likely kill my system.

So I bring to you: PoshMouth!

Centralized Service

True to my PowerShell roots, I opted to build the service in PowerShell.  The main body of the script is as follows:

Set-TwitterCredentials -user $TwitterUser -pass $TwitterPass

# Start Application Loop
While($true)
{
    # Query the current users rate limit status
    [xml]$rls = Get-TwitterRateLimitStatus -raw $true;
    $remaining_hits = $rls.hash.{remaining-hits}.get_InnerText();
    [DateTime]$reset_time = $rls.hash.{reset-time}.get_InnerText();

    Write-DebugMessage "------------------------------------------------------";
    Write-DebugMessage "Remaining Hits: $remaining_hits...";
    Write-DebugMessage "Reset Time    : $reset_time";
    Write-DebugMessage "------------------------------------------------------";
    if ( $remaining_hits -gt 0 )
    {
        # First pull up all friends timelines
        [xml]$x = Get-TwitterFriendsTimeline -raw $true -since_id (Get-LastStatusId);
        Process-StatusEntries $x;

        # Sleep until next poll
        Write-DebugMessage "Sleeping for $DELAY seconds...";
        Start-Sleep -Seconds $DELAY;
    }
    else
    {
        # Determine how many seconds needed
        $ts = $reset_time - [DateTime]::Now;
        $wait_time = [int]$ts.TotalSeconds + 1;
        # Sleep until new rate limit is allocated
        Write-DebugMessage "Waiting $wait_time seconds for new Rate Limit...";
        Start-Sleep -Seconds $wait_time;
    }
}

Basically the API Rate Limit is queried to determine if calls can be made.  If so, then Get-TwitterFriendsTimeline function is called to request the current timeline.  Then each entry is processed with the following code:

function Process-StatusEntries()
{
  param($status = $null);
  if ( $status )
  {
    $status.statuses.status | ForEach-Object -Process {
     # Ignore tweets from this account.
    if ( ! $_.user.screen_name.ToLower().Equals($TwitterUser) )
    {
       # If audio already exists, we'll assume it's already been processed.
       if ( ! (Audio-Exists $_.id) )
      {
         Write-DebugMessage "Processing Tweet # $($_.id)...";   
        $mp3file = Create-AudioFile $_;
         $url = Publish-AudioFile $mp3file;
         Tweet-Notification -status $_ -mp3file $url;
         Set-LastStatusId -id $_.id;
     }
     }
   }
}
}

I had to check the screen_name to make sure it didn't match the twitter account this was running under or an infinite loop could occur where I convert PoshMouth's tweets of tweets of tweets...

If the audio already exists in the local repository, then the tweet is skipped.  Otherwise, a MP3 is created and published to a web server.  Finally an @reply tweet is made to the original posters username with a link to the target mp3 file.

Persistent Audio

As you noticed above, to make the audio persistent, I needed to save the audio stream to a file on the system.  The Speech API allows for saving to an uncompressed .WAV file via the SAPI.SpFileStream object.  Since .WAV's are so passe, I figured I'd throw a little LAME action in there and convert that .WAV to a more appropriate .MP3 file.  The following code does the dirty work.

function Convert-TextToWAV()
{
    param([string]$text = $null, [string]$wavfile = $null);
    if ( $text -and $wavfile )
    {
        $SSMCreateForWrite = 3;
        $DoEvents = 0;
        $SVSFlagsAsync = 1;
        # remove file if it exists
        #Remove-Item -ErrorAction SilentlyContinue $wavfile;
        $spFs = New-Object -ComObject SAPI.SpFileStream
        $spFs.Open($wavfile, $SSMCreateForWrite, $DoEvents)
        $voice = New-Object -ComObject SAPI.SpVoice;
        $voice.AudioOutputStream = $spFs;
        $voice.Speak($text, $SVFlagsAsync);
        $spFs.Close()
    }
}
function Convert-WAVToMP3()
{
    param([string]$wavfile = $null, [string]$mp3file = $null);
    if ( $wavfile -and $mp3file )
    {
        & $LAME_EXE -S $wavfile $mp3file;
    }
}
function Convert-TextToMP3()
{
    param([string]$text = $null, [string]$mp3file = $null);
    if ( $text -and $mp3file )
    {
        $wavfile = Get-TempFile "foo.wav";
        Convert-TextToWAV $text $wavfile;
        Convert-WAVToMP3 $wavfile $mp3file;
        Remove-Item $wavfile;
    }
}
function Create-AudioFile()
{
    param($status = $null);
    if ( $status )
    {
        $created_at = $status.created_at;
        $id = $status.id;
        $text = $status.text;
        $user_id = $status.user.id;
        $user_name = $status.user.name;
        $screen_name = $status.user.screen_name;
        $audio_file = Get-AudioFile $id;
        [void](Convert-TextToMP3 $text $audio_file);
    }
    return $audio_file;
}

The Create-AudioFile function will take the status output from Twitter, and Convert the text to a .MP3 on the local system with the SAPI SpFileStream object along with the publicly available LAME audio library.

Controlled System

The process for converting a tweet to MP3 and uploading to our media server takes about 3-5 seconds.  If I allowed everyone that followed the Twitter account, this could grow way beyond the ability for my little script to handle.  I'd need to build some sort of asynchronous setup to allow for parallel encoding and uploading.  This, in addition to the fact that within 5 minutes of creating the account, I already had 3 followers trying to sell me on weight-loss products, I knew this wasn't an option.  To limit this, I decided to set it up to only create audio files for accounts that my account was following.  This way I could easily control for whom the audio is getting created.

Putting It All Together

So how can you start getting your tweets automagically audioized?  Here's the process:

  1. Start following the @TweetMouth account on Twitter.
  2. Sit back and wait for me to follow you.
  3. Watch for @replies from @TweetMouth.  Click on the tinyurl link and you can hear your tweet in all it's Windows Sound System glory!

Getting the Bits

PoshMouthBot.zip - A zip containing the latest PoshMouthBot.ps1 and PoshTweet.ps1 scripts.

If you decide to build and run your own version of PoshMouthBot, you'll need to use your own twitter account and have access to a distribution server for the MP3 files.  Most of this is controlled from global variables at the top of the PoshMouthBot.ps1 script. 

Enjoy and happy Tweeting!

-Joe

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

IoT & Smart Cities Stories
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.