SlideShare a Scribd company logo
1 of 62
Download to read offline
May 2017
Building A Twitter Bot With Basic Python
About us
We train developers and data
scientists through 1-on-1
mentorship and career prep
About me
• Saul Diez-Guerra
• CTO @ Thinkful
• Github: diezguerra
• Twitter: @definitely
The plan for the night
• You all are going to build a twitter bot!
• The goal is not for it to be perfect, but for you

to realize it"s well within your reach to build
and learn how to make stuff happen!
• And we"ll have fun trolling Twitter.
Bot
• Your bot will make a search on Twitter for a
given phrase.
• It will receive a list of tweets.
• And it will reply to each of those tweets with a
predefined message.
Uses of the bot
• MARKETING
• Target topics
• Target company"s followers
• COMMUNITY
MANAGEMENT
• Answer repetitive questions
• Interact with users
• JUST FOR FUN
Goals
• Build a real project.
• Set up our computer to work with Python.
• Learn some cool Python concepts.
• No previous knowledge required.
Not goals
• This is not a step-by-step intro to Python.
• Also not an exhaustive review of Twitter"s
API.
The alot shepherd
Alot
A —> lot
@lovebot_2000 by Alex Berke
Other creative uses…
Down to business
Getting Codeanywhere working
• codeanywhere.com will help us avoid setting
up our laptops and instead get to the meaty
part right away
• Create an account
• Get a Python 3 (CentOS 6.5) container going
• Toward the end we’ll get people their own
Python install and local code editor
Twitter
Twitter API
• Provides programmatic access to read and
write Twitter data
• Docs: https://dev.twitter.com/rest/public
• Important to check the limits and
restrictions
• We will use tweepy to interact with Twitter’s
API
$ sudo pip install tweepy
If it fails
$ sudo pip install tweepy --ignore-installed
Create a Twitter
account
If you don’t have one already
IMPORTANT: You must provide your phone number!
Otherwise you won’t be able to create an app
• When you have your twitter account go to:
• apps.twitter.com
• Click on “Create new app”
Website field must start with: http://
• Go to the “Keys and access tokens” tab.
• There you will have your “Consumer key”
and “Consumer secret” that we will use in a
few moments.
• You need to “Create your access token”
• At the bottom of the screen
BOT
Codeanywhere
twitterbot/
bot.py
# replace the words in red with the keys that
# we saw before on apps.twitter.com
keys = {
"consumer_key": "CONSUMER_KEY",
"consumer_secret": "CONSUMER_SECRET",
"access_token": "ACCESS_TOKEN",
"access_token_secret": "ACCESS_TOKEN_SECRET"
}
Dictionary
• An unordered set of "key: value" pairs.
• Curly braces to define: {}.
• Read a value: keys["consumer_key"]
• Assign a value to a key: 

keys["extra_value"] = "hey"
import tweepy
# we create the api object
auth = tweepy.OAuthHandler(
keys["consumer_key"],
keys["consumer_secret"])
auth.set_access_token(
keys["access_token"],
keys["access_token_secret"])
api = tweepy.API(auth)
search = ""sad alot""
tweet_list = api.search(
q=search,
count=1,
lang="en"
)
Double quotes inside single quotes
to search for that exact phrase
Functions
• A function is a block of organized, reusable
code.
• Functions have to be defined.
• Functions can return a value.
def search(q, count, lang):
# do something
return value
for tweet in tweet_list:
# do something
# don"t copy this just yet
screen_name = tweet.user.screen_name
message = "@{username} {message}".format(
username=screen_name,
message="Alot confused, Alot not understand feelings"
)
try:
api.update_status(
status=message,
in_reply_to_status_id=tweet.id
)
print(message)
except tweepy.TweepError as e:
print(e.message[0]["code"])
print(e.args[0][0]["code"])
For loop
• Used when you have a piece of code which
you want to repeat n number of times.
• For each tweet in tweet_list, do something.
Indentation
• To indicate a block of code, you must indent
each line by the same amount.
• For each tweet in tweet_list, do something.
for tweet in tweet_list:
screen_name = tweet.user.screen_name
message = "@{username} {message}".format(
username=screen_name,
message="Alot confused, Alot not understand feelings"
)
String format
• Replacement fields are delimited by braces {}
• Returns a copy of the string where each
replacement field is replaced with the string
value of the corresponding argument
# same indentation as before
try:
api.update_status(
status=message,
in_reply_to_status_id=tweet.id
)
print message
except tweepy.TweepError as error:
print error.message
Try/Except
• When a Python script encounters a situation
that it cannot cope with, it raises an
exception.
• If you have some suspicious code that may
raise an exception, you can defend your
program by placing the suspicious code in a
try: block.
• Also include an except: statement, followed
by a block of code which handles the
problem
# bot.py
import tweepy
keys = {
"consumer_key": "CONSUMER_KEY",
"consumer_secret": "CONSUMER_SECRET",
"access_token": "ACCESS_TOKEN",
"access_token_secret": "ACCESS_TOKEN_SECRET",
}
auth = tweepy.OAuthHandler(keys["consumer_key"], keys["consumer_secret"])
auth.set_access_token(keys["access_token"], keys["access_token_secret"])
api = tweepy.API(auth)
search = ""sad alot”"
tweet_list = api.search(
q=search, # frase to search
count=1, # number of tweets to return
lang=“en” # language to search (optional)
)
for tweet in tweet_list:
screen_name = tweet.user.screen_name
message = ".@{username} {message}".format(
username=screen_name,
message="Alot confused, a lot not understand feelings"
)
try:
api.update_status(
status=message,
in_reply_to_status_id=tweet.id
)
print message
except tweepy.TweepError as e:
print e.message
$ python bot.py
Let’s build on what we have
Tyding up
• Move re-usable actions to functions
• Move functions to different modules
• Extra: avoid replying to RTs
Developing on your laptop
• Installing Atom on your laptop
• Finding the Terminal or Powershell
• Installing Python on your laptop
• Securing a copy of pip
Installing Atom
https://atom.io/
Installing Python
https://conda.io/miniconda.html
Open Terminal or Powershell and run:
$ conda create -n twitterbot python
$ source activate twitterbot
$ python
Don"t type the dollar sign, that just means that the command
should be run in the shell
Installing pip
Pip
• Package management system
• Installs packages, libraries…
• Usages:
• $ pip install django
• $ pip install -r requirements.txt
Windows
No need. Conda installed it!
MAC
$ sudo easy_install pip
LINUX
$ sudo apt-get install python-pip
Our Program
You’ll learn concepts, practice with drills, and build
capstone projects — all guided by a personal mentor
Our Mentors
Mentors have, on average, 10+ years of experience
Web Development Syllabus
• Frontend Development (HTML, CSS, Javascript)
• Frontend “Frameworks” (React.js)
• Backend Development (Node.js)
• Electives (Python, Ruby, Swift, Angular, UX)
• Computer Science Fundamentals
• Technical interviews + Career prep
Try us out!
Try the program for two
weeks, includes six mentor
sessions - $50
Learn HTML/CSS/JavaScript
Option to continue onto web
development bootcamp
Come talk to me if you"re
interested (or email me at
noel@thinkful.com)
Questions?
Email Noel at noel@thinkful.com

More Related Content

Viewers also liked

Técnicas de estudio
Técnicas de estudioTécnicas de estudio
Técnicas de estudio
alfonsogg75
 

Viewers also liked (18)

Звичайні дроби
Звичайні дробиЗвичайні дроби
Звичайні дроби
 
Ad vlsi pass-transistor logic_yalagoud_patil
Ad vlsi pass-transistor logic_yalagoud_patilAd vlsi pass-transistor logic_yalagoud_patil
Ad vlsi pass-transistor logic_yalagoud_patil
 
Actividad 4; bloque 1. bullying
Actividad 4; bloque 1. bullyingActividad 4; bloque 1. bullying
Actividad 4; bloque 1. bullying
 
Merged
MergedMerged
Merged
 
Crs vs gds
Crs vs gdsCrs vs gds
Crs vs gds
 
2017 03 open-access_public
2017 03 open-access_public2017 03 open-access_public
2017 03 open-access_public
 
Shannon Kelly group presentation
Shannon Kelly group presentationShannon Kelly group presentation
Shannon Kelly group presentation
 
Técnicas de estudio
Técnicas de estudioTécnicas de estudio
Técnicas de estudio
 
NJ Future Redevelopment Forum 2017 Shin
NJ Future Redevelopment Forum 2017 ShinNJ Future Redevelopment Forum 2017 Shin
NJ Future Redevelopment Forum 2017 Shin
 
بروتينات وانزيمات الغذاء
بروتينات وانزيمات الغذاءبروتينات وانزيمات الغذاء
بروتينات وانزيمات الغذاء
 
Why learn python in 2017?
Why learn python in 2017?Why learn python in 2017?
Why learn python in 2017?
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
 
Mixing Python and Java
Mixing Python and JavaMixing Python and Java
Mixing Python and Java
 
Python in the Hadoop Ecosystem (Rock Health presentation)
Python in the Hadoop Ecosystem (Rock Health presentation)Python in the Hadoop Ecosystem (Rock Health presentation)
Python in the Hadoop Ecosystem (Rock Health presentation)
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Linux 101 - GNU/Linux Nedir ? Nasıl Kurulur?
Linux 101 - GNU/Linux Nedir ? Nasıl Kurulur?Linux 101 - GNU/Linux Nedir ? Nasıl Kurulur?
Linux 101 - GNU/Linux Nedir ? Nasıl Kurulur?
 
Campanha Lux_TCC
Campanha Lux_TCCCampanha Lux_TCC
Campanha Lux_TCC
 
Mon compte généralités
Mon compte   généralitésMon compte   généralités
Mon compte généralités
 

Similar to Build a Twitter Bot with Basic Python

Introduction to Python.pdf
Introduction to Python.pdfIntroduction to Python.pdf
Introduction to Python.pdf
Rahul Mogal
 

Similar to Build a Twitter Bot with Basic Python (20)

Five steps to get tweets sent by a list of users
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
 
OpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in PythonOpenWhisk by Example - Auto Retweeting Example in Python
OpenWhisk by Example - Auto Retweeting Example in Python
 
Magento 2 Best Practice Workfow // David Lambauer // Meet Magento 2017 // Lei...
Magento 2 Best Practice Workfow // David Lambauer // Meet Magento 2017 // Lei...Magento 2 Best Practice Workfow // David Lambauer // Meet Magento 2017 // Lei...
Magento 2 Best Practice Workfow // David Lambauer // Meet Magento 2017 // Lei...
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 
Collect twitter data using python
Collect twitter data using pythonCollect twitter data using python
Collect twitter data using python
 
python programming.pptx
python programming.pptxpython programming.pptx
python programming.pptx
 
Unleashing Twitter Data for Fun and Insight
Unleashing Twitter Data for Fun and InsightUnleashing Twitter Data for Fun and Insight
Unleashing Twitter Data for Fun and Insight
 
Unleashing twitter data for fun and insight
Unleashing twitter data for fun and insightUnleashing twitter data for fun and insight
Unleashing twitter data for fun and insight
 
Curiosity Bits Tutorial: Mining Twitter User Profile on Python V2
Curiosity Bits Tutorial: Mining Twitter User Profile on Python V2Curiosity Bits Tutorial: Mining Twitter User Profile on Python V2
Curiosity Bits Tutorial: Mining Twitter User Profile on Python V2
 
Collect twitter data using python
Collect twitter data using pythonCollect twitter data using python
Collect twitter data using python
 
Introduction to Python.pdf
Introduction to Python.pdfIntroduction to Python.pdf
Introduction to Python.pdf
 
TwtBot9/28/17SD
TwtBot9/28/17SDTwtBot9/28/17SD
TwtBot9/28/17SD
 
Getting started with titanium
Getting started with titaniumGetting started with titanium
Getting started with titanium
 
Build your first Chatbot
Build your first ChatbotBuild your first Chatbot
Build your first Chatbot
 
Getting started with Appcelerator Titanium
Getting started with Appcelerator TitaniumGetting started with Appcelerator Titanium
Getting started with Appcelerator Titanium
 
Tbjsphx918
Tbjsphx918Tbjsphx918
Tbjsphx918
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Idea2app
Idea2appIdea2app
Idea2app
 
Analyzing social media with Python and other tools (2/4)
Analyzing social media with Python and other tools (2/4) Analyzing social media with Python and other tools (2/4)
Analyzing social media with Python and other tools (2/4)
 
PyCourse - Self driving python course
PyCourse - Self driving python coursePyCourse - Self driving python course
PyCourse - Self driving python course
 

More from Thinkful

LA 1/16/18 Intro to Javascript: Fundamentals
LA 1/16/18 Intro to Javascript: FundamentalsLA 1/16/18 Intro to Javascript: Fundamentals
LA 1/16/18 Intro to Javascript: Fundamentals
Thinkful
 
Getting started-jan-9-2018
Getting started-jan-9-2018Getting started-jan-9-2018
Getting started-jan-9-2018
Thinkful
 

More from Thinkful (20)

893ff61f-1fb8-4e15-a379-775dfdbcee77-7-14-25-46-115-141-308-324-370
893ff61f-1fb8-4e15-a379-775dfdbcee77-7-14-25-46-115-141-308-324-370893ff61f-1fb8-4e15-a379-775dfdbcee77-7-14-25-46-115-141-308-324-370
893ff61f-1fb8-4e15-a379-775dfdbcee77-7-14-25-46-115-141-308-324-370
 
LA 1/31/18 Intro to JavaScript: Fundamentals
LA 1/31/18 Intro to JavaScript: FundamentalsLA 1/31/18 Intro to JavaScript: Fundamentals
LA 1/31/18 Intro to JavaScript: Fundamentals
 
LA 1/31/18 Intro to JavaScript: Fundamentals
LA 1/31/18 Intro to JavaScript: FundamentalsLA 1/31/18 Intro to JavaScript: Fundamentals
LA 1/31/18 Intro to JavaScript: Fundamentals
 
Itjsf129
Itjsf129Itjsf129
Itjsf129
 
Twit botsd1.30.18
Twit botsd1.30.18Twit botsd1.30.18
Twit botsd1.30.18
 
Build your-own-instagram-filters-with-javascript-202-335 (1)
Build your-own-instagram-filters-with-javascript-202-335 (1)Build your-own-instagram-filters-with-javascript-202-335 (1)
Build your-own-instagram-filters-with-javascript-202-335 (1)
 
Baggwjs124
Baggwjs124Baggwjs124
Baggwjs124
 
Become a Data Scientist: A Thinkful Info Session
Become a Data Scientist: A Thinkful Info SessionBecome a Data Scientist: A Thinkful Info Session
Become a Data Scientist: A Thinkful Info Session
 
Vpet sd-1.25.18
Vpet sd-1.25.18Vpet sd-1.25.18
Vpet sd-1.25.18
 
LA 1/18/18 Become A Web Developer: A Thinkful Info Session
LA 1/18/18 Become A Web Developer: A Thinkful Info SessionLA 1/18/18 Become A Web Developer: A Thinkful Info Session
LA 1/18/18 Become A Web Developer: A Thinkful Info Session
 
How to Choose a Programming Language
How to Choose a Programming LanguageHow to Choose a Programming Language
How to Choose a Programming Language
 
Batbwjs117
Batbwjs117Batbwjs117
Batbwjs117
 
1/16/18 Intro to JS Workshop
1/16/18 Intro to JS Workshop1/16/18 Intro to JS Workshop
1/16/18 Intro to JS Workshop
 
LA 1/16/18 Intro to Javascript: Fundamentals
LA 1/16/18 Intro to Javascript: FundamentalsLA 1/16/18 Intro to Javascript: Fundamentals
LA 1/16/18 Intro to Javascript: Fundamentals
 
(LA 1/16/18) Intro to JavaScript: Fundamentals
(LA 1/16/18) Intro to JavaScript: Fundamentals(LA 1/16/18) Intro to JavaScript: Fundamentals
(LA 1/16/18) Intro to JavaScript: Fundamentals
 
Websitesd1.15.17.
Websitesd1.15.17.Websitesd1.15.17.
Websitesd1.15.17.
 
Bavpwjs110
Bavpwjs110Bavpwjs110
Bavpwjs110
 
Byowwhc110
Byowwhc110Byowwhc110
Byowwhc110
 
Getting started-jan-9-2018
Getting started-jan-9-2018Getting started-jan-9-2018
Getting started-jan-9-2018
 
Introjs1.9.18tf
Introjs1.9.18tfIntrojs1.9.18tf
Introjs1.9.18tf
 

Recently uploaded

Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Lovely Professional University
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
drjose256
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
Madan Karki
 

Recently uploaded (20)

Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Software Engineering - Modelling Concepts + Class Modelling + Building the An...
Software Engineering - Modelling Concepts + Class Modelling + Building the An...Software Engineering - Modelling Concepts + Class Modelling + Building the An...
Software Engineering - Modelling Concepts + Class Modelling + Building the An...
 
Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2Research Methodolgy & Intellectual Property Rights Series 2
Research Methodolgy & Intellectual Property Rights Series 2
 
Multivibrator and its types defination and usges.pptx
Multivibrator and its types defination and usges.pptxMultivibrator and its types defination and usges.pptx
Multivibrator and its types defination and usges.pptx
 
Quiz application system project report..pdf
Quiz application system project report..pdfQuiz application system project report..pdf
Quiz application system project report..pdf
 
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
Tembisa Central Terminating Pills +27838792658 PHOMOLONG Top Abortion Pills F...
 
How to Design and spec harmonic filter.pdf
How to Design and spec harmonic filter.pdfHow to Design and spec harmonic filter.pdf
How to Design and spec harmonic filter.pdf
 
Supermarket billing system project report..pdf
Supermarket billing system project report..pdfSupermarket billing system project report..pdf
Supermarket billing system project report..pdf
 
Insurance management system project report.pdf
Insurance management system project report.pdfInsurance management system project report.pdf
Insurance management system project report.pdf
 
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdfALCOHOL PRODUCTION- Beer Brewing Process.pdf
ALCOHOL PRODUCTION- Beer Brewing Process.pdf
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
BORESCOPE INSPECTION for engins CFM56.pdf
BORESCOPE INSPECTION for engins CFM56.pdfBORESCOPE INSPECTION for engins CFM56.pdf
BORESCOPE INSPECTION for engins CFM56.pdf
 
AI in Healthcare Innovative use cases and applications.pdf
AI in Healthcare Innovative use cases and applications.pdfAI in Healthcare Innovative use cases and applications.pdf
AI in Healthcare Innovative use cases and applications.pdf
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
Intelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent ActsIntelligent Agents, A discovery on How A Rational Agent Acts
Intelligent Agents, A discovery on How A Rational Agent Acts
 
Artificial Intelligence Bayesian Reasoning
Artificial Intelligence Bayesian ReasoningArtificial Intelligence Bayesian Reasoning
Artificial Intelligence Bayesian Reasoning
 
Introduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and ApplicationsIntroduction to Heat Exchangers: Principle, Types and Applications
Introduction to Heat Exchangers: Principle, Types and Applications
 
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message QueuesLinux Systems Programming: Semaphores, Shared Memory, and Message Queues
Linux Systems Programming: Semaphores, Shared Memory, and Message Queues
 
Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 

Build a Twitter Bot with Basic Python

  • 1. May 2017 Building A Twitter Bot With Basic Python
  • 2. About us We train developers and data scientists through 1-on-1 mentorship and career prep
  • 3. About me • Saul Diez-Guerra • CTO @ Thinkful • Github: diezguerra • Twitter: @definitely
  • 4. The plan for the night • You all are going to build a twitter bot! • The goal is not for it to be perfect, but for you
 to realize it"s well within your reach to build and learn how to make stuff happen! • And we"ll have fun trolling Twitter.
  • 5. Bot • Your bot will make a search on Twitter for a given phrase. • It will receive a list of tweets. • And it will reply to each of those tweets with a predefined message.
  • 6. Uses of the bot • MARKETING • Target topics • Target company"s followers • COMMUNITY MANAGEMENT • Answer repetitive questions • Interact with users • JUST FOR FUN
  • 7. Goals • Build a real project. • Set up our computer to work with Python. • Learn some cool Python concepts. • No previous knowledge required.
  • 8. Not goals • This is not a step-by-step intro to Python. • Also not an exhaustive review of Twitter"s API.
  • 10. Alot
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20. @lovebot_2000 by Alex Berke Other creative uses…
  • 22. Getting Codeanywhere working • codeanywhere.com will help us avoid setting up our laptops and instead get to the meaty part right away • Create an account • Get a Python 3 (CentOS 6.5) container going • Toward the end we’ll get people their own Python install and local code editor
  • 24. Twitter API • Provides programmatic access to read and write Twitter data • Docs: https://dev.twitter.com/rest/public • Important to check the limits and restrictions • We will use tweepy to interact with Twitter’s API
  • 25. $ sudo pip install tweepy
  • 26. If it fails $ sudo pip install tweepy --ignore-installed
  • 27. Create a Twitter account If you don’t have one already IMPORTANT: You must provide your phone number! Otherwise you won’t be able to create an app
  • 28. • When you have your twitter account go to: • apps.twitter.com • Click on “Create new app”
  • 29. Website field must start with: http://
  • 30. • Go to the “Keys and access tokens” tab. • There you will have your “Consumer key” and “Consumer secret” that we will use in a few moments. • You need to “Create your access token” • At the bottom of the screen
  • 31. BOT
  • 33. # replace the words in red with the keys that # we saw before on apps.twitter.com keys = { "consumer_key": "CONSUMER_KEY", "consumer_secret": "CONSUMER_SECRET", "access_token": "ACCESS_TOKEN", "access_token_secret": "ACCESS_TOKEN_SECRET" }
  • 34. Dictionary • An unordered set of "key: value" pairs. • Curly braces to define: {}. • Read a value: keys["consumer_key"] • Assign a value to a key: 
 keys["extra_value"] = "hey"
  • 35. import tweepy # we create the api object auth = tweepy.OAuthHandler( keys["consumer_key"], keys["consumer_secret"]) auth.set_access_token( keys["access_token"], keys["access_token_secret"]) api = tweepy.API(auth)
  • 36. search = ""sad alot"" tweet_list = api.search( q=search, count=1, lang="en" ) Double quotes inside single quotes to search for that exact phrase
  • 37. Functions • A function is a block of organized, reusable code. • Functions have to be defined. • Functions can return a value. def search(q, count, lang): # do something return value
  • 38. for tweet in tweet_list: # do something # don"t copy this just yet screen_name = tweet.user.screen_name message = "@{username} {message}".format( username=screen_name, message="Alot confused, Alot not understand feelings" ) try: api.update_status( status=message, in_reply_to_status_id=tweet.id ) print(message) except tweepy.TweepError as e: print(e.message[0]["code"]) print(e.args[0][0]["code"])
  • 39. For loop • Used when you have a piece of code which you want to repeat n number of times. • For each tweet in tweet_list, do something.
  • 40. Indentation • To indicate a block of code, you must indent each line by the same amount. • For each tweet in tweet_list, do something.
  • 41. for tweet in tweet_list: screen_name = tweet.user.screen_name message = "@{username} {message}".format( username=screen_name, message="Alot confused, Alot not understand feelings" )
  • 42. String format • Replacement fields are delimited by braces {} • Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument
  • 43. # same indentation as before try: api.update_status( status=message, in_reply_to_status_id=tweet.id ) print message except tweepy.TweepError as error: print error.message
  • 44. Try/Except • When a Python script encounters a situation that it cannot cope with, it raises an exception. • If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. • Also include an except: statement, followed by a block of code which handles the problem
  • 45. # bot.py import tweepy keys = { "consumer_key": "CONSUMER_KEY", "consumer_secret": "CONSUMER_SECRET", "access_token": "ACCESS_TOKEN", "access_token_secret": "ACCESS_TOKEN_SECRET", } auth = tweepy.OAuthHandler(keys["consumer_key"], keys["consumer_secret"]) auth.set_access_token(keys["access_token"], keys["access_token_secret"]) api = tweepy.API(auth) search = ""sad alot”" tweet_list = api.search( q=search, # frase to search count=1, # number of tweets to return lang=“en” # language to search (optional) ) for tweet in tweet_list: screen_name = tweet.user.screen_name message = ".@{username} {message}".format( username=screen_name, message="Alot confused, a lot not understand feelings" ) try: api.update_status( status=message, in_reply_to_status_id=tweet.id ) print message except tweepy.TweepError as e: print e.message
  • 47. Let’s build on what we have
  • 48. Tyding up • Move re-usable actions to functions • Move functions to different modules • Extra: avoid replying to RTs
  • 49. Developing on your laptop • Installing Atom on your laptop • Finding the Terminal or Powershell • Installing Python on your laptop • Securing a copy of pip
  • 52. Open Terminal or Powershell and run: $ conda create -n twitterbot python $ source activate twitterbot $ python Don"t type the dollar sign, that just means that the command should be run in the shell
  • 54. Pip • Package management system • Installs packages, libraries… • Usages: • $ pip install django • $ pip install -r requirements.txt
  • 55. Windows No need. Conda installed it!
  • 57. LINUX $ sudo apt-get install python-pip
  • 58. Our Program You’ll learn concepts, practice with drills, and build capstone projects — all guided by a personal mentor
  • 59. Our Mentors Mentors have, on average, 10+ years of experience
  • 60. Web Development Syllabus • Frontend Development (HTML, CSS, Javascript) • Frontend “Frameworks” (React.js) • Backend Development (Node.js) • Electives (Python, Ruby, Swift, Angular, UX) • Computer Science Fundamentals • Technical interviews + Career prep
  • 61. Try us out! Try the program for two weeks, includes six mentor sessions - $50 Learn HTML/CSS/JavaScript Option to continue onto web development bootcamp Come talk to me if you"re interested (or email me at noel@thinkful.com)
  • 62. Questions? Email Noel at noel@thinkful.com