{"id":35111,"date":"2018-07-24T08:12:44","date_gmt":"2018-07-24T08:12:44","guid":{"rendered":"https:\/\/fedoramagazine.org\/?p=21991"},"modified":"2018-07-24T08:12:44","modified_gmt":"2018-07-24T08:12:44","slug":"learn-how-to-build-your-own-twitter-bot-with-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2018\/07\/24\/learn-how-to-build-your-own-twitter-bot-with-python\/","title":{"rendered":"Learn how to build your own Twitter bot with Python"},"content":{"rendered":"<p>Twitter allows one to <a href=\"https:\/\/twitter.com\">share<\/a> blog posts and articles with the world. Using Python and the <em>tweepy<\/em> library makes it easy to create a Twitter bot that takes care of all the tweeting for you. This article shows you how to build such a bot. Hopefully you can take the concepts here and apply them to other projects that use online services.<\/p>\n<p><span id=\"more-21991\"><\/span><\/p>\n<h3>Getting started<\/h3>\n<p>To create a Twitter bot the <a href=\"https:\/\/tweepy.readthedocs.io\/en\/v3.5.0\/\"><em>tweepy<\/em><\/a> library comes handy. It manages the Twitter API calls and provides a simple interface.<\/p>\n<p>The following commands use <em>Pipenv<\/em> to install <em>tweepy<\/em> into a virtual environment. If you don&#8217;t have Pipenv installed, check out our previous article,\u00a0<a href=\"https:\/\/fedoramagazine.org\/install-pipenv-fedora\/\">How to install Pipenv on Fedora<\/a>.<\/p>\n<pre>$ mkdir twitterbot $ cd twitterbot $ pipenv --three $ pipenv install tweepy $ pipenv shell<\/pre>\n<h3>Tweepy &#8211; Getting started<\/h3>\n<p>To use the Twitter API the bot needs to authenticate against Twitter. For that,\u00a0<em>tweepy<\/em> uses the OAuth authentication standard. You can get credentials by creating a new application at <a href=\"https:\/\/apps.twitter.com\/\">https:\/\/apps.twitter.com\/<\/a>.<\/p>\n<h4>Create a new Twitter application<\/h4>\n<p>After you fill in the following form and click on the <em>Create your Twitter application<\/em>\u00a0button, you have access to the application credentials. <em>Tweepy<\/em> requires the <em>Consumer Key (API Key)<\/em> and the <em>Consumer Secret (API Secret)<\/em>, both available from the <em>Keys and Access Tokens.<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-22019\" src=\"http:\/\/www.sickgaming.net\/blog\/wp-content\/uploads\/2018\/07\/learn-how-to-build-your-own-twitter-bot-with-python.png\" alt=\"\" width=\"1238\" height=\"890\" \/><\/p>\n<p>After scrolling down the page, generate an <em>Access Token<\/em>\u00a0and an <em>Access Token Secret <\/em>using the <em>Create my access token<\/em>\u00a0button<em>.<\/em><\/p>\n<h4>Using Tweepy &#8211; print your timeline<\/h4>\n<p>Now that you have all the credentials needed, open a new file and write the following Python code.<\/p>\n<div>\n<pre>import tweepy auth = tweepy.OAuthHandler(\"your_consumer_key\", \"your_consumer_key_secret\") auth.set_access_token(\"your_access_token\", \"your_access_token_secret\") api = tweepy.API(auth) public_tweets = api.home_timeline() for tweet in public_tweets: print(tweet.text)<\/pre>\n<p>After making sure that you are using the Pipenv virtual environment, run your program.<\/p>\n<\/div>\n<div><\/div>\n<pre>$ python tweet.py<\/pre>\n<p>The above program calls the <em>home_timeline <\/em> API method to retrieve the 20 most recent tweets from your timeline. Now that the bot is able to use <em>tweepy\u00a0<\/em> to get data from Twitter, try changing the code to send a tweet.<\/p>\n<h4>Using Tweepy &#8211; send a tweet<\/h4>\n<p>To send a tweet, the API method <em>update_status<\/em> comes in handy. The usage is simple:<\/p>\n<pre>api.update_status(\"The awesome text you would like to tweet\")<\/pre>\n<p>The <em>tweepy\u00a0<\/em>library has many other methods that can be useful for a Twitter bot. For the full details of the API, check the <a href=\"http:\/\/docs.tweepy.org\/en\/v3.5.0\/api.html#id1\">documentation<\/a>.<\/p>\n<h3>A magazine bot<\/h3>\n<p>Let&#8217;s create a bot that searches for Fedora Magazine tweets and automatically retweets them.<\/p>\n<p>To avoid retweeting the same tweet multiple times, the bot stores the tweet ID of the last retweet. Two helper functions,\u00a0<em>store_last_id<\/em> and <em>get_last_id,<\/em> will be used to save and retrieve this ID.<\/p>\n<p>Then the bot uses the\u00a0<em>tweepy <\/em>search API to find the Fedora Magazine tweets that are more recent than the stored ID.<\/p>\n<pre>import tweepy def store_last_id(tweet_id): \"\"\" Store a tweet id in a file \"\"\" with open(\"lastid\", \"w\") as fp: fp.write(str(tweet_id)) def get_last_id(): \"\"\" Read the last retweeted id from a file \"\"\" with open(\"lastid\", \"r\") as fp: return fp.read() if __name__ == '__main__': auth = tweepy.OAuthHandler(\"your_consumer_key\", \"your_consumer_key_secret\") auth.set_access_token(\"your_access_token\", \"your_access_token_secret\") api = tweepy.API(auth) try: last_id = get_last_id() except FileNotFoundError: print(\"No retweet yet\") last_id = None for tweet in tweepy.Cursor(api.search, q=\"fedoramagazine.org\", since_id=last_id).items(): if tweet.user.name == 'Fedora Project': store_last_id(tweet.id) tweet.retweet() print(f'\"{tweet.text}\" was retweeted'<\/pre>\n<p>In order to retweet only tweets from the Fedora Magazine, the bot searches for tweets that contain <em>fedoramagazine.org<\/em>\u00a0and are published by the &#8220;Fedora Project&#8221; Twitter account.<\/p>\n<h3>Conclusion<\/h3>\n<p>In this article you saw how\u00a0 to create a Twitter application using the <em>tweepy<\/em> Python library to automate reading, sending and searching tweets. You can now use your creativity to create a Twitter bot of your own.<\/p>\n<p>The source code of the example in this article is available on <a href=\"https:\/\/github.com\/cverna\/magabot\">Github<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Twitter allows one to share blog posts and articles with the world. Using Python and the tweepy library makes it easy to create a Twitter bot that takes care of all the tweeting for you. This article shows you how to build such a bot. Hopefully you can take the concepts here and apply them [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":35112,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[48],"tags":[45,42,46,47],"class_list":["post-35111","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-fedora-os","tag-fedora","tag-for-developers","tag-magazine","tag-news"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/35111","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=35111"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/35111\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/35112"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=35111"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=35111"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=35111"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}