OpenWhisk by Example - Auto Retweeting Example in Python

CodeOps Technologies LLP
CodeOps Technologies LLPOrganizer at India Serverless Summit and Bangalore Container Conference.

This article is about using Serverless platform OpenWhisk. The example shows how to do auto retweeting in Python to illustrate an application of serverless approach. Originally published in October 2017 edition of Open Source For You magazine - shared under CC BY SA-3.0 License.

62  |  OCTOBER 2017  |  OPEN SOURCE FOR YOU  |  www.OpenSourceForU.com
Developers How To
I
n the September 2017 issue of OSFY, we demystified
serverless computing. We also discussed its pros and cons,
the technologies involved, use cases, the challenges, etc. So
how about using serverless computing to simplify or automate
your tasks? For example, wouldn’t it be nice to automatically
retweet the tweets that have your favourite hashtags (such as
#serverless or #opensource). That’s the topic we’ll explore
in this article. We are going to implement a bot (let’s call it
TweetBot), in which you can specify the hashtags to retweet
at specified time intervals.
We will start with writing an auto-retweeting code in
Python and get it working on our machine. Later, we will
deploy it in OpenWhisk on IBM Bluemix. For this article,
we assume you already know the fundamentals of Python
programming. You need not know anything about OpenWhisk
or Bluemix — we’ll introduce these to you in this article.
Developing the TweetBot
In order to write the Python code for auto-retweeting,
the prerequisite is that Python 3 must be installed
in your machine.
The Twitter API provides programmatic access to read
and write Twitter data, create a new tweet, read user profile
and follower data, retweet, and more. For this, you must first
create a Twitter application (see https://apps.twitter.com/) and
note down the OAuth credentials for the bot configuration.
“By 2022, most Platform-as-a-Service (PaaS) offerings will evolve to a
fundamentally serverless model, rendering the cloud platform architectures that
are dominant in 2017 as legacy architectures.” - Gartner
The Twitter API in Python can be accessed using the
TwitterFollowBot Python module. Using this module, you
can do much more than just retweet – you can auto-follow
and auto-like. For developing the TwitterBot, you must
install the module into a folder rather than the default bin
directory. For that, use the following command:
pip install --target <target_folder> TwitterFollowBot
Let us now create a program that uses the
TwitterFollowBot Python module to retweet the
latest ‘count’ number of tweets with a specific phrase
(‘#Serverless’ in our case). For that, we need to create a
TwitterFollowBot instance. The TwitterFollowBot uses the
config.txt file in the current directory to configure the bot.
So, let us first configure the bot. To do so, you should
create a config.txt file and fill in the following information
so that the bot can connect to the Twitter API. Here are the
entries for the config.txt file:
OAUTH_TOKEN:			
OAUTH_SECRET:			 API keys from
CONSUMER_KEY:			 the twitter app
CONSUMER_SECRET:
TWITTER_HANDLE: <your twitter handle>
ALREADY_FOLLOWED_FILE:already-followed.txt
Using Python to Automate Retweets
www.OpenSourceForU.com  |  OPEN SOURCE FOR YOU  |  OCTOBER 2017  |  63
DevelopersHow To
FOLLOWERS_FILE:followers.txt
FOLLOWS_FILE:following.txt
USERS_KEEP_FOLLOWING:
USERS_KEEP_UNMUTED:
USERS_KEEP_MUTED:
The files already-followed.txt, followers.txt and following.
txt contain the respective twitter IDs. You must create these
files — you can leave them empty, though. The rest of the
fields may also be left empty.
# Program to retweet five latest tweets based on a hashtag
(#Serverless)
from TwitterFollowBot import TwitterBot
def retweet():
		 # create an instance of the TwitterFollowBot
		 # by default, the bot will look for a configuration
		 file called config.txt
		 # in your current directory
		 my_bot = TwitterBot()
		 # autoretweets the 5(count)
		 latest tweets that matches the hashtag
		 my_bot.auto_rt(“#Serverless”, count = 5)
		 return {‘message’ : ‘retweeted successfully’}
retweet()
That’s the short and sweet code! Let’s save it as test.py
and run it. The output is shown in Figure 1.
When you execute the Python script, it connects to the
Twitter API and retweets. The result throws up a warning
indicating that the followers.txt isn’t updated; you can just
ignore that warning or update the files to get rid of the
warning. The program displays the tweets that are retweeted,
so we know it is working.
After we get the code working in our machine, it is time
to deploy and execute it in the cloud using the serverless
approach. We are going to use Apache OpenWhisk as the
serverless platform. We will use IBM Bluemix as the cloud
platform to deploy the OpenWhisk action(s).
Apache OpenWhisk
Apache OpenWhisk is an open source serverless cloud platform
that executes functions in response to events at any scale.
OpenWhisk was started by IBM and is now incubated
by Apache. Adobe is an important contributor to the
project and has contributed the API Gateway. OpenWhisk
executes functions (called actions) in response to events
(called triggers). Since it is serverless, you just need
to provide your code to be executed; specifically, you
don’t need to concern yourself with how to manage the
life cycle or operations of the underlying containers
that execute the code.
Figure 1: Output for test.py
Figure 2: Key aspects of OpenWhisk
Figure 3: Types of action invocations
You can run OpenWhisk on your laptop, on-premise,
or in the cloud. When running in the cloud, you could use
a Platform-as-a-Service (PaaS) version of the OpenWhisk
provided by IBM Bluemix or you can provision it yourself into
Infrastructure-as-a-Service (IaaS) clouds, such as Bluemix,
Amazon EC2, Microsoft Azure and Google Cloud Platform.
Here are some key aspects of OpenWhisk:
ƒƒ It’s open source. If you want, you can explore the code
and tinker with it, and change it according to your
requirements. Support for a wide range of programming
languages including Node.js 6, Python 3, PHP 7.1 and
Swift 3.1.1 is available.
ƒƒ Actions (serverless functions) can also be custom
executable programs packaged in a Docker container, i.e.,
you can run Docker images in OpenWhisk.
ƒƒ You can run it locally! None of the major serverless
platforms provide this feature. You can build and run
actions locally on your own hardware behind your own
firewall, and then deploy it to execute in the cloud.
Run
locally
Open
source
Wide
range of
languages
Run
Docker
images
Types of
invocations
Blocking
Non-blocking
OpenWhisk
64  |  OCTOBER 2017  |  OPEN SOURCE FOR YOU  |  www.OpenSourceForU.com
Developers How To
TweetBot using OpenWhisk
In order to use TweetBot in a serverless approach, you need
to install OpenWhisk in your machine and have a BlueMix
account. For installing OpenWhisk, refer to https://console.
bluemix.net/openwhisk/cli for the set-up and configuration
information. The beauty of serverless technology is that
you don’t have to rewrite your entire application; just tweak
the plain code that runs in your machine and you’ll be fine!
Surprisingly, our TweetBot requires only one change — it should
have a main function with an input parameter (dictionary
type) and is to be saved as a __main__.py file.
Here is the modified Python code:
# Program to retweet five latest tweets based on a hashtag
(#Serverless)
from TwitterFollowBot import TwitterBot
def retweet(dict):
	 # create an instance of the TwitterFollowBot
	 # by default, the bot will look for a configuration file 	
	 called config.txt
	 # in your current directory
	 my_bot = TwitterBot()
	 # autoretweets the 5(count)
	 latest tweets that matches the hashtag
	 my_bot.auto_rt(“#Serverless”, count = 5)
def main(dict):
	 retweet(dict)
	 return {‘message’ : ‘retweeted successfully’}
Now, save this Python code in a file named __main__.py.
Create the config.txt, already-followed.txt, followers.txt and
following.txt (as earlier), and zip them all with the __main__.py
file and the TwitterFollowBot dependency module files.
Invocation process
Once the wsk CLI (command line interface) is installed and
the zip file is ready, follow the steps given below.
Step 1. Create and update an action: Log in to the IBM
Bluemix account (https://console.bluemix.net/openwhisk/)
and create a new action. You can upload the zip files with
dependencies only via the CLI. The syntax is:
wsk action create <action-name> --kind <language:version>
<file_name>
	 Sample Command:
wsk action create tweetBot --kind python:3 OpenWhisk.zip	
Step 2. Invoke the function (non-blocking mode):
The syntax is:
wsk action invoke <action-name>
	 Sample Command: wsk action invoke tweetBot
Step 3. Check for the result: Since we invoked the function
in a non-blocking mode (because we haven’t added the
‘--blocking’ parameter), the command returned immediately,
but it is executing in the background. The syntax is:
	 wsk activation result <action ID>
	 Sample Command:
	 wsk activation result f4df0d1dcb12488396978d2cda832b09
Step 4. Check out the logs: The syntax is:
	 wsk activation logs <action ID>
	 Sample Command:
	 wsk activation logs f4df0d1dcb12488396978d2cda832b09
Join us at the India Serverless Summit 2017
These are the best of times, and these are the worst of times!
There are so many awesome new technologies to catch
up on. But, we simply can’t. We have seen a progression
of computing models — from virtualisation, IaaS, PaaS,
containers, and now, serverless — all in a matter of a few
years. You certainly don’t want to be left behind. So join us at
the Serverless Summit, India’s first confluence on serverless
technologies, being held on October 27, 2017 at Bengaluru. It
is the best place to hear from industry experts, network with
technology enthusiasts, as well as learn about how to adopt
serverless architecture. The keynote speaker is John Willis,
director of ecosystem development at Docker and a DevOps
guru (widely known for the book ‘The DevOps Handbook’
that he co-authored). Open Source For You is the media
partner and the Cloud Native Computing Foundation is the
community partner for this summit. For more details, please
visit the website www.inserverless.com.
Automate the invocation	
The moment the action was invoked, your Twitter account
would have retweeted the five latest tweets that have the
hashtag ‘#Serverless’ in it. However, this is still a manual
invocation. For maximum impact, it would be better to
Figure 4: Invocation process
Figure 5: Result of the command
Create Update Invoke
www.OpenSourceForU.com  |  OPEN SOURCE FOR YOU  |  OCTOBER 2017  |  65
DevelopersHow To
By: Ganesh Samarthyam and Srushith Repakula
The authors work at CodeOps Technologies, which is a
software technology, consulting and training company
based in Bengaluru.
Figure 6: Types of triggers
automate the invocation process as well, so that you can
configure the action and forget it once and for all.
A periodic trigger would be the best option. It triggers
the action based on a specific time, and will retweet the latest
tweets with ‘#Serverless’ in it. One can either choose a pattern
or write a cron expression.
The pattern shown in Figure 7 will invoke the TweetBot
action every week day (Monday to Friday) every six hours,
keeping your Twitter account live without your intervention!
Words of caution
Before we end this article, here are a couple of things you
should be careful about:
1.	 OpenWhisk is open source and free, but to deploy it, we
use IBM Bluemix which isn’t free. The TweetBot action
will seamlessly run in the free tier, but for any other
application, please estimate the monthly costs. The pricing
calculator (https://console.bluemix.net/openwhisk/learn/
pricing) could be handy.
2.	 This action uses the Twitter API in the background via
the TwitterFollowBot module. Misusing this may lead to
the banning of your Twitter app, so please make sure you
clearly read the Twitter automation rules (https://support.
twitter.com/articles/76915).
In this article, we discussed a TweetBot that can be
written to automatically retweet the latest tweets with certain
given hashtags. We wrote the actions (serverless functions) in
Python, and deployed them in OpenWhisk on IBM Bluemix.
We also used triggers to automatically invoke the actions
at specified time intervals. With this introduction, we invite
you to further explore OpenWhisk as well as other exciting
serverless technologies.
[1]	 Apache OpenWhisk: https://openwhisk.incubator.
apache.org/
[2]	 IBM Bluemix Functions: https://console.bluemix.net/
openwhisk/
[3]	 Twitter API: https://dev.twitter.com/rest/public
References
Figure 7: Periodic trigger time settings
triggers when
Cloudant database is
updated
triggers when
a REST endpoint is
posted to
triggers when a
push notification
is sent to
your mobile
triggers when a new
message is written to
the queue
triggers when a
GitHub repository
is updated
Cloudant
GitHub
Message
hub
Mobile
push
Periodic Custom
trigger
triggers based
on time
Triggers
www.electronicsb2b.com
Log on to www.electronicsb2b.com and be in touch with the Electronics B2B Fraternity 24x7
Read more
stories on
Security in
• CCTV camera market is expected to double by 2015
• The latest in biometric devices
• CCTV Camera manufacturers can look forward to a bright future
• Video Analytics Systems Turning a CCTV into a proactive tool
• Security cameras evolving with new technologies
• The latest in dome cameras
• The latest in weather-proof and vandal-resistant security cameras
TOPSECURITY STORIES
ELECTRONICS
INDUSTRY IS AT A

Recommended

Vancouver style referencing guide by
Vancouver style referencing guideVancouver style referencing guide
Vancouver style referencing guidesamitbisen
1.8K views7 slides
APA (American Psychological Association) Citation and Referencing by
APA (American Psychological Association) Citation and ReferencingAPA (American Psychological Association) Citation and Referencing
APA (American Psychological Association) Citation and ReferencingBakht Munir
425 views37 slides
Tprs workshop by
Tprs workshopTprs workshop
Tprs workshopjchanglmsa
4.7K views142 slides
Slideshare reference lists and citations apa by
Slideshare reference lists and citations apaSlideshare reference lists and citations apa
Slideshare reference lists and citations apanjprentice
5.8K views25 slides
Paraphrasing by
ParaphrasingParaphrasing
ParaphrasingLaura Gardner
6.5K views13 slides
2008 dbq 12-3-12 2 by
2008 dbq   12-3-12 22008 dbq   12-3-12 2
2008 dbq 12-3-12 2Ashley Birmingham
7.7K views18 slides

More Related Content

What's hot

Deciding on a medical research topic: your first challenge by
Deciding on a medical research topic: your first challengeDeciding on a medical research topic: your first challenge
Deciding on a medical research topic: your first challengeAzmi Mohd Tamil
2.4K views20 slides
Citation 101 by
Citation 101Citation 101
Citation 101Pilgrim Library
3.8K views18 slides
English grammar-understanding-basics by
English grammar-understanding-basicsEnglish grammar-understanding-basics
English grammar-understanding-basicsAhmad JUtt
209 views286 slides
Bibliography presentation.ppt by
Bibliography  presentation.pptBibliography  presentation.ppt
Bibliography presentation.pptBurning_Ice
18.5K views16 slides
Medication error by
Medication errorMedication error
Medication errorPriti Gupta
5.6K views10 slides
Week4b pptslides apa referencing by
Week4b pptslides  apa referencingWeek4b pptslides  apa referencing
Week4b pptslides apa referencingHafizul Mukhlis
2.6K views38 slides

What's hot(18)

Deciding on a medical research topic: your first challenge by Azmi Mohd Tamil
Deciding on a medical research topic: your first challengeDeciding on a medical research topic: your first challenge
Deciding on a medical research topic: your first challenge
Azmi Mohd Tamil2.4K views
English grammar-understanding-basics by Ahmad JUtt
English grammar-understanding-basicsEnglish grammar-understanding-basics
English grammar-understanding-basics
Ahmad JUtt209 views
Bibliography presentation.ppt by Burning_Ice
Bibliography  presentation.pptBibliography  presentation.ppt
Bibliography presentation.ppt
Burning_Ice18.5K views
Medication error by Priti Gupta
Medication errorMedication error
Medication error
Priti Gupta5.6K views
Week4b pptslides apa referencing by Hafizul Mukhlis
Week4b pptslides  apa referencingWeek4b pptslides  apa referencing
Week4b pptslides apa referencing
Hafizul Mukhlis2.6K views
Prefixes and suffixes worksheet by Marlinapinilla
Prefixes and suffixes worksheetPrefixes and suffixes worksheet
Prefixes and suffixes worksheet
Marlinapinilla345 views
Annotated bibliographies by khornberger
Annotated bibliographiesAnnotated bibliographies
Annotated bibliographies
khornberger8.1K views
Popular & Scholarly Articles by abutton1
Popular & Scholarly ArticlesPopular & Scholarly Articles
Popular & Scholarly Articles
abutton17.2K views
Writing References in APA Style(7th edition) by Sushma Sushma
Writing References in APA Style(7th edition) Writing References in APA Style(7th edition)
Writing References in APA Style(7th edition)
Sushma Sushma374 views
Clinical practice guidelines by abenedicto
Clinical practice guidelinesClinical practice guidelines
Clinical practice guidelines
abenedicto16.4K views

Similar to OpenWhisk by Example - Auto Retweeting Example in Python

Five steps to get tweets sent by a list of users by
Five steps to get tweets sent by a list of usersFive steps to get tweets sent by a list of users
Five steps to get tweets sent by a list of usersWeiai Wayne Xu
4.2K views26 slides
Going open source with small teams by
Going open source with small teamsGoing open source with small teams
Going open source with small teamsJamie Thomas
764 views36 slides
python programming.pptx by
python programming.pptxpython programming.pptx
python programming.pptxKaviya452563
116 views29 slides
Streamlining React Component Development and Sharing with bit.pptx by
Streamlining React Component Development and Sharing with bit.pptxStreamlining React Component Development and Sharing with bit.pptx
Streamlining React Component Development and Sharing with bit.pptxShubhamJayswal6
27 views13 slides
Flask jwt authentication tutorial by
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
363 views38 slides
Safetty systems intro_embedded_c by
Safetty systems intro_embedded_cSafetty systems intro_embedded_c
Safetty systems intro_embedded_cMaria Cida Rosa
35 views54 slides

Similar to OpenWhisk by Example - Auto Retweeting Example in Python(20)

Five steps to get tweets sent by a list of users by Weiai Wayne Xu
Five steps to get tweets sent by a list of usersFive steps to get tweets sent by a list of users
Five steps to get tweets sent by a list of users
Weiai Wayne Xu4.2K views
Going open source with small teams by Jamie Thomas
Going open source with small teamsGoing open source with small teams
Going open source with small teams
Jamie Thomas764 views
python programming.pptx by Kaviya452563
python programming.pptxpython programming.pptx
python programming.pptx
Kaviya452563116 views
Streamlining React Component Development and Sharing with bit.pptx by ShubhamJayswal6
Streamlining React Component Development and Sharing with bit.pptxStreamlining React Component Development and Sharing with bit.pptx
Streamlining React Component Development and Sharing with bit.pptx
ShubhamJayswal627 views
Flask jwt authentication tutorial by Katy Slemon
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorial
Katy Slemon363 views
Setting up the hyperledger composer in ubuntu by kesavan N B
Setting up the hyperledger composer in ubuntuSetting up the hyperledger composer in ubuntu
Setting up the hyperledger composer in ubuntu
kesavan N B1.4K views
Using Data Science & Serverless Python to find apartment in Toronto by Daniel Zivkovic
Using Data Science & Serverless Python to find apartment in TorontoUsing Data Science & Serverless Python to find apartment in Toronto
Using Data Science & Serverless Python to find apartment in Toronto
Daniel Zivkovic220 views
Vladimir Ulogov - Beyond the Loadable Module by Zabbix
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
Zabbix3K views
Introduction to Google App Engine with Python by Brian Lyttle
Introduction to Google App Engine with PythonIntroduction to Google App Engine with Python
Introduction to Google App Engine with Python
Brian Lyttle11.9K views
Analysis of merge requests in GitLab using PVS-Studio for C# by Andrey Karpov
Analysis of merge requests in GitLab using PVS-Studio for C#Analysis of merge requests in GitLab using PVS-Studio for C#
Analysis of merge requests in GitLab using PVS-Studio for C#
Andrey Karpov41 views
Expanding XPages with Bootstrap Plugins for Ultimate Usability by Teamstudio
Expanding XPages with Bootstrap Plugins for Ultimate UsabilityExpanding XPages with Bootstrap Plugins for Ultimate Usability
Expanding XPages with Bootstrap Plugins for Ultimate Usability
Teamstudio2.7K views
Hacking the Explored App by Adding Custom Code (UI5con 2016) by Nabi Zamani
Hacking the Explored App by Adding Custom Code (UI5con 2016)Hacking the Explored App by Adding Custom Code (UI5con 2016)
Hacking the Explored App by Adding Custom Code (UI5con 2016)
Nabi Zamani2.1K views
Usage Note of SWIG for PHP by William Lee
Usage Note of SWIG for PHPUsage Note of SWIG for PHP
Usage Note of SWIG for PHP
William Lee2.3K views
The Nightmare Fuzzing Suite and Blind Code Coverage Fuzzer by Joxean Koret
The Nightmare Fuzzing Suite and Blind Code Coverage FuzzerThe Nightmare Fuzzing Suite and Blind Code Coverage Fuzzer
The Nightmare Fuzzing Suite and Blind Code Coverage Fuzzer
Joxean Koret10.7K views
Introduction to Behavior Driven Development by Robin O'Brien
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development
Robin O'Brien1.3K views
PVS-Studio in the Clouds: Azure DevOps by Andrey Karpov
PVS-Studio in the Clouds: Azure DevOpsPVS-Studio in the Clouds: Azure DevOps
PVS-Studio in the Clouds: Azure DevOps
Andrey Karpov51 views
Behavior & Specification Driven Development in PHP - #OpenWest by Joshua Warren
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
Joshua Warren1.4K views

More from CodeOps Technologies LLP

AWS Serverless Event-driven Architecture - in lastminute.com meetup by
AWS Serverless Event-driven Architecture - in lastminute.com meetupAWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetupCodeOps Technologies LLP
16 views16 slides
Understanding azure batch service by
Understanding azure batch serviceUnderstanding azure batch service
Understanding azure batch serviceCodeOps Technologies LLP
2.7K views21 slides
DEVOPS AND MACHINE LEARNING by
DEVOPS AND MACHINE LEARNINGDEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNINGCodeOps Technologies LLP
2.6K views42 slides
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS by
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONSSERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONSCodeOps Technologies LLP
2.8K views33 slides
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS by
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONSBUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONSCodeOps Technologies LLP
2.6K views13 slides
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES by
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICESAPPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICESCodeOps Technologies LLP
2.7K views2 slides

More from CodeOps Technologies LLP(20)

CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S... by CodeOps Technologies LLP
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS by CodeOps Technologies LLP
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESSWRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja by CodeOps Technologies LLP
Deploy Microservices To Kubernetes Without Secrets by Reenu SalujaDeploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ... by CodeOps Technologies LLP
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ... by CodeOps Technologies LLP
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...

Recently uploaded

Introduction to Maven by
Introduction to MavenIntroduction to Maven
Introduction to MavenJohn Valentino
6 views10 slides
Fleet Management Software in India by
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India Fleetable
11 views1 slide
tecnologia18.docx by
tecnologia18.docxtecnologia18.docx
tecnologia18.docxnosi6702
5 views5 slides
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Donato Onofri
860 views34 slides
EV Charging App Case by
EV Charging App Case EV Charging App Case
EV Charging App Case iCoderz Solutions
5 views1 slide
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...Marc Müller
40 views62 slides

Recently uploaded(20)

Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable11 views
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri860 views
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller40 views
FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan5 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j8 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta6 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254556 views
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app7 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...

OpenWhisk by Example - Auto Retweeting Example in Python

  • 1. 62  |  OCTOBER 2017  |  OPEN SOURCE FOR YOU  |  www.OpenSourceForU.com Developers How To I n the September 2017 issue of OSFY, we demystified serverless computing. We also discussed its pros and cons, the technologies involved, use cases, the challenges, etc. So how about using serverless computing to simplify or automate your tasks? For example, wouldn’t it be nice to automatically retweet the tweets that have your favourite hashtags (such as #serverless or #opensource). That’s the topic we’ll explore in this article. We are going to implement a bot (let’s call it TweetBot), in which you can specify the hashtags to retweet at specified time intervals. We will start with writing an auto-retweeting code in Python and get it working on our machine. Later, we will deploy it in OpenWhisk on IBM Bluemix. For this article, we assume you already know the fundamentals of Python programming. You need not know anything about OpenWhisk or Bluemix — we’ll introduce these to you in this article. Developing the TweetBot In order to write the Python code for auto-retweeting, the prerequisite is that Python 3 must be installed in your machine. The Twitter API provides programmatic access to read and write Twitter data, create a new tweet, read user profile and follower data, retweet, and more. For this, you must first create a Twitter application (see https://apps.twitter.com/) and note down the OAuth credentials for the bot configuration. “By 2022, most Platform-as-a-Service (PaaS) offerings will evolve to a fundamentally serverless model, rendering the cloud platform architectures that are dominant in 2017 as legacy architectures.” - Gartner The Twitter API in Python can be accessed using the TwitterFollowBot Python module. Using this module, you can do much more than just retweet – you can auto-follow and auto-like. For developing the TwitterBot, you must install the module into a folder rather than the default bin directory. For that, use the following command: pip install --target <target_folder> TwitterFollowBot Let us now create a program that uses the TwitterFollowBot Python module to retweet the latest ‘count’ number of tweets with a specific phrase (‘#Serverless’ in our case). For that, we need to create a TwitterFollowBot instance. The TwitterFollowBot uses the config.txt file in the current directory to configure the bot. So, let us first configure the bot. To do so, you should create a config.txt file and fill in the following information so that the bot can connect to the Twitter API. Here are the entries for the config.txt file: OAUTH_TOKEN: OAUTH_SECRET: API keys from CONSUMER_KEY: the twitter app CONSUMER_SECRET: TWITTER_HANDLE: <your twitter handle> ALREADY_FOLLOWED_FILE:already-followed.txt Using Python to Automate Retweets
  • 2. www.OpenSourceForU.com  |  OPEN SOURCE FOR YOU  |  OCTOBER 2017  |  63 DevelopersHow To FOLLOWERS_FILE:followers.txt FOLLOWS_FILE:following.txt USERS_KEEP_FOLLOWING: USERS_KEEP_UNMUTED: USERS_KEEP_MUTED: The files already-followed.txt, followers.txt and following. txt contain the respective twitter IDs. You must create these files — you can leave them empty, though. The rest of the fields may also be left empty. # Program to retweet five latest tweets based on a hashtag (#Serverless) from TwitterFollowBot import TwitterBot def retweet(): # create an instance of the TwitterFollowBot # by default, the bot will look for a configuration file called config.txt # in your current directory my_bot = TwitterBot() # autoretweets the 5(count) latest tweets that matches the hashtag my_bot.auto_rt(“#Serverless”, count = 5) return {‘message’ : ‘retweeted successfully’} retweet() That’s the short and sweet code! Let’s save it as test.py and run it. The output is shown in Figure 1. When you execute the Python script, it connects to the Twitter API and retweets. The result throws up a warning indicating that the followers.txt isn’t updated; you can just ignore that warning or update the files to get rid of the warning. The program displays the tweets that are retweeted, so we know it is working. After we get the code working in our machine, it is time to deploy and execute it in the cloud using the serverless approach. We are going to use Apache OpenWhisk as the serverless platform. We will use IBM Bluemix as the cloud platform to deploy the OpenWhisk action(s). Apache OpenWhisk Apache OpenWhisk is an open source serverless cloud platform that executes functions in response to events at any scale. OpenWhisk was started by IBM and is now incubated by Apache. Adobe is an important contributor to the project and has contributed the API Gateway. OpenWhisk executes functions (called actions) in response to events (called triggers). Since it is serverless, you just need to provide your code to be executed; specifically, you don’t need to concern yourself with how to manage the life cycle or operations of the underlying containers that execute the code. Figure 1: Output for test.py Figure 2: Key aspects of OpenWhisk Figure 3: Types of action invocations You can run OpenWhisk on your laptop, on-premise, or in the cloud. When running in the cloud, you could use a Platform-as-a-Service (PaaS) version of the OpenWhisk provided by IBM Bluemix or you can provision it yourself into Infrastructure-as-a-Service (IaaS) clouds, such as Bluemix, Amazon EC2, Microsoft Azure and Google Cloud Platform. Here are some key aspects of OpenWhisk: ƒƒ It’s open source. If you want, you can explore the code and tinker with it, and change it according to your requirements. Support for a wide range of programming languages including Node.js 6, Python 3, PHP 7.1 and Swift 3.1.1 is available. ƒƒ Actions (serverless functions) can also be custom executable programs packaged in a Docker container, i.e., you can run Docker images in OpenWhisk. ƒƒ You can run it locally! None of the major serverless platforms provide this feature. You can build and run actions locally on your own hardware behind your own firewall, and then deploy it to execute in the cloud. Run locally Open source Wide range of languages Run Docker images Types of invocations Blocking Non-blocking OpenWhisk
  • 3. 64  |  OCTOBER 2017  |  OPEN SOURCE FOR YOU  |  www.OpenSourceForU.com Developers How To TweetBot using OpenWhisk In order to use TweetBot in a serverless approach, you need to install OpenWhisk in your machine and have a BlueMix account. For installing OpenWhisk, refer to https://console. bluemix.net/openwhisk/cli for the set-up and configuration information. The beauty of serverless technology is that you don’t have to rewrite your entire application; just tweak the plain code that runs in your machine and you’ll be fine! Surprisingly, our TweetBot requires only one change — it should have a main function with an input parameter (dictionary type) and is to be saved as a __main__.py file. Here is the modified Python code: # Program to retweet five latest tweets based on a hashtag (#Serverless) from TwitterFollowBot import TwitterBot def retweet(dict): # create an instance of the TwitterFollowBot # by default, the bot will look for a configuration file called config.txt # in your current directory my_bot = TwitterBot() # autoretweets the 5(count) latest tweets that matches the hashtag my_bot.auto_rt(“#Serverless”, count = 5) def main(dict): retweet(dict) return {‘message’ : ‘retweeted successfully’} Now, save this Python code in a file named __main__.py. Create the config.txt, already-followed.txt, followers.txt and following.txt (as earlier), and zip them all with the __main__.py file and the TwitterFollowBot dependency module files. Invocation process Once the wsk CLI (command line interface) is installed and the zip file is ready, follow the steps given below. Step 1. Create and update an action: Log in to the IBM Bluemix account (https://console.bluemix.net/openwhisk/) and create a new action. You can upload the zip files with dependencies only via the CLI. The syntax is: wsk action create <action-name> --kind <language:version> <file_name> Sample Command: wsk action create tweetBot --kind python:3 OpenWhisk.zip Step 2. Invoke the function (non-blocking mode): The syntax is: wsk action invoke <action-name> Sample Command: wsk action invoke tweetBot Step 3. Check for the result: Since we invoked the function in a non-blocking mode (because we haven’t added the ‘--blocking’ parameter), the command returned immediately, but it is executing in the background. The syntax is: wsk activation result <action ID> Sample Command: wsk activation result f4df0d1dcb12488396978d2cda832b09 Step 4. Check out the logs: The syntax is: wsk activation logs <action ID> Sample Command: wsk activation logs f4df0d1dcb12488396978d2cda832b09 Join us at the India Serverless Summit 2017 These are the best of times, and these are the worst of times! There are so many awesome new technologies to catch up on. But, we simply can’t. We have seen a progression of computing models — from virtualisation, IaaS, PaaS, containers, and now, serverless — all in a matter of a few years. You certainly don’t want to be left behind. So join us at the Serverless Summit, India’s first confluence on serverless technologies, being held on October 27, 2017 at Bengaluru. It is the best place to hear from industry experts, network with technology enthusiasts, as well as learn about how to adopt serverless architecture. The keynote speaker is John Willis, director of ecosystem development at Docker and a DevOps guru (widely known for the book ‘The DevOps Handbook’ that he co-authored). Open Source For You is the media partner and the Cloud Native Computing Foundation is the community partner for this summit. For more details, please visit the website www.inserverless.com. Automate the invocation The moment the action was invoked, your Twitter account would have retweeted the five latest tweets that have the hashtag ‘#Serverless’ in it. However, this is still a manual invocation. For maximum impact, it would be better to Figure 4: Invocation process Figure 5: Result of the command Create Update Invoke
  • 4. www.OpenSourceForU.com  |  OPEN SOURCE FOR YOU  |  OCTOBER 2017  |  65 DevelopersHow To By: Ganesh Samarthyam and Srushith Repakula The authors work at CodeOps Technologies, which is a software technology, consulting and training company based in Bengaluru. Figure 6: Types of triggers automate the invocation process as well, so that you can configure the action and forget it once and for all. A periodic trigger would be the best option. It triggers the action based on a specific time, and will retweet the latest tweets with ‘#Serverless’ in it. One can either choose a pattern or write a cron expression. The pattern shown in Figure 7 will invoke the TweetBot action every week day (Monday to Friday) every six hours, keeping your Twitter account live without your intervention! Words of caution Before we end this article, here are a couple of things you should be careful about: 1. OpenWhisk is open source and free, but to deploy it, we use IBM Bluemix which isn’t free. The TweetBot action will seamlessly run in the free tier, but for any other application, please estimate the monthly costs. The pricing calculator (https://console.bluemix.net/openwhisk/learn/ pricing) could be handy. 2. This action uses the Twitter API in the background via the TwitterFollowBot module. Misusing this may lead to the banning of your Twitter app, so please make sure you clearly read the Twitter automation rules (https://support. twitter.com/articles/76915). In this article, we discussed a TweetBot that can be written to automatically retweet the latest tweets with certain given hashtags. We wrote the actions (serverless functions) in Python, and deployed them in OpenWhisk on IBM Bluemix. We also used triggers to automatically invoke the actions at specified time intervals. With this introduction, we invite you to further explore OpenWhisk as well as other exciting serverless technologies. [1] Apache OpenWhisk: https://openwhisk.incubator. apache.org/ [2] IBM Bluemix Functions: https://console.bluemix.net/ openwhisk/ [3] Twitter API: https://dev.twitter.com/rest/public References Figure 7: Periodic trigger time settings triggers when Cloudant database is updated triggers when a REST endpoint is posted to triggers when a push notification is sent to your mobile triggers when a new message is written to the queue triggers when a GitHub repository is updated Cloudant GitHub Message hub Mobile push Periodic Custom trigger triggers based on time Triggers www.electronicsb2b.com Log on to www.electronicsb2b.com and be in touch with the Electronics B2B Fraternity 24x7 Read more stories on Security in • CCTV camera market is expected to double by 2015 • The latest in biometric devices • CCTV Camera manufacturers can look forward to a bright future • Video Analytics Systems Turning a CCTV into a proactive tool • Security cameras evolving with new technologies • The latest in dome cameras • The latest in weather-proof and vandal-resistant security cameras TOPSECURITY STORIES ELECTRONICS INDUSTRY IS AT A