Building a Twitter Bot to Automate Posting Cryptocurrency News with Python [A Step-by-Step Guide]

Photo by Yucel Moran on Unsplash

Imagine your own custom Twitter Bot posting real-time market updates for your favorite cryptocurrencies. It is possible with Python, Tweepy, and LunarCRUSH. Below we will outline a step-by-step process utilizing Python. The bot pulls information from LunarCRUSH. The metrics for Bitcoin, Ethereum, Litecoin stored as formatted variables and tweeted out automatically every 30 minutes.

Setting up a Twitter Development Account and Tweepy

Let’s start off by installing Tweepy. It’s simple enough through terminal using the pip command:
pip install tweepy
Twitter for Developers provides access to the Twitter API in order to Publish and analyze Tweets, optimize ads, and create unique customer experiences. Check out the Twitter API documentation here. You can perform multiple tasks through this API. See below some of them:

Post and retrieve tweetsFollow and unfollow usersPost direct messages

Before you are able to use the Twitter API endpoints, create a developer account and generate your API keys. You can apply for a developer account directly here. You must answer questions on how you plan to use the API and accept the Twitter Developer Agreement, and then you will be granted access to the Developer Dashboard.
Once you are approved access to the Developers for Twitter, log in to the developer site and create your App. This step will automatically generate your consumer API keys and access tokens, remember, you should keep them secret:

The developer account should be linked to the Twitter account where you want to have the bot active. From the Twitter Development platform, you are able to edit the app permissions. In my example, I have granted my app permission to read, write and send direct messages.

Introduction to LunarCRUSH — Social Listening For Crypto

In order to start pulling in cryptocurrency social insights, you must head over to LunarCRUSH.com and set up an account.

In the left-hand navigation, head to Developers and select API Docs.

Generate V2 API Key

Once you are in the API Docs, generate your V2 API Key.

Building a Twitter bot with Python, Tweepy, LunarCRUSH

Let’s start building our Twitter bot. As mentioned previously, you will use the Tweepy library which works seamlessly with Twitter API and LunarCRUSH API / LunarSTREAM™.

First, import tweepy. Tweepy makes it easier to authenticate to the API through our Twitter App secret keys.

Below is an extract of code, do this by creating a OAuthHandler instance to handle our login bypassing the consumer key and consumer secret as arguments.

In order to be able to make requests to the API, send back an access token. Use the auth.set_access_token method to store the access request token for our session.

Now, you are ready to control our Twitter Account with Python. Note that I have included ‘XXX’ instead of my real secret keys. Replace ‘XXX’ with your secret keys that you can obtain in your Twitter Developers Dashboard.
import tweepy
import urllib.request
import ssl
import json
import time
ssl._create_default_https_context = ssl._create_unverified_context
# Oauth keys
consumer_key ="XXX"
consumer_secret ="XXX"
access_token ="XXX"
access_token_secret ="XXX"
# Authentication with Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

Our variable api is where you store the auth settings. You will use it to make requests to the Twitter API.

The idea of this twitter bot is to publish a different tweet, every x amount of minutes with specific cryptocurrency coin / token metrics. This can be easily done using LunarCRUSH API & LUNARSTREAM™.

Let’s add our LunarCRUSH API Keys to the code. Simply add:

api_key = "XXX"

Now you are authenticated with LunarCRUSH API. It is time to decide which Cryptocurrencies you would like to integrate into your tweets. Use coin_list to store the different crypto symbols. For instance, ‘LTC’ is Litecoin, ‘ETH’ is Ethereum, and ‘BTC’ is Bitcoin.

# Allows adding as many coins as desired
coin_list = [
    "LTC",
    "ETH",
    "BTC"
]
coins = ','.join(coin_list)

A list of the fields desired from the API — key is the LunarCRUSH key, and the value is the field name outputted to Twitter.

{"LUNAR_CRUSH_KEY": "RENDERED_NAME"}

For example, to add tweet_replies:

{"tweet_replies": "Tweet Replies: "},

you would add this to the list below.

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. — 

Python Data Structures Docs

Now you can map which values you would like to pull from LunarCRUSH API. As the program becomes more complex, this should be written in a more robust manner.

map = [
    {"name":""},
    {"symbol": ""},
    {"price": " Price: "},
    {"percent_change_24h": " - 24 Hour Percent Change: "},
    {"market_cap": " Market Cap: "},
    {"volume_24h": " 24 Hour Volume: "},
    {"url_shares": " URL Shares: "},
    {"reddit_posts": " Reddit Posts: "},
    {"tweets": " Tweets: "},
    {"galaxy_score": " Galaxy Score: "},
    {"volatility": " Volatility: "},
    {"social_volume": " Social Volume: "},
    {"news": " News: "},
    {"close": " Close: "},
]
def final_render(asset_tweet, value, key, asset):
    if key == 'symbol':
        asset_tweet += " (" + asset[key] + ")"
    elif key == 'percent_change_24h':
        asset_tweet += value + str(asset[key]) + "%"
    else:
        asset_tweet += value + str(asset[key])
    return asset_tweet

Now, iterate over each of the fields from LunarCRUSH which gets the value from LunarCRUSH and renders it with the field name.

def main():
url = "https://api.lunarcrush.com/v2?data=assets&key=" + api_key + "&symbol=" + coins
    assets = json.loads(urllib.request.urlopen(url).read())
for asset in assets['data']:
        asset_tweet = ""
        for field in map:
            key = list(field.keys())[0]
            value = list(field.values())[0]
            asset_tweet = final_render(asset_tweet, value, key, asset)
        print(asset_tweet)
        print(len(asset_tweet))
        # Posts tweets
        api.update_status(status=asset_tweet)
# Runs main() every 30 minutes
while True:
    main()
    time.sleep(1800)

Complete Python Code

import urllib.request
import ssl
import json
import time
import tweepy
ssl._create_default_https_context = ssl._create_unverified_context
# Oauth keys
consumer_key ="XXX"
consumer_secret ="XXX"
access_token ="XXX"
access_token_secret ="XXX"
# Authentication with Twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#LunarCRUSH API Key
api_key = "XXX"
# Allows adding as many coins as desired
coin_list = [
    "LTC",
    "ETH",
    "BTC"
]
coins = ','.join(coin_list)
# A list of the fields desired from the API - key is the Lunar Crush key, and the value is the field name outputted to Twitter
# {"LUNAR_CRUSH_KEY": "RENDERED_NAME"}
# For example, to add tweet_replies, you would add:
# {"tweet_replies": "Tweet Replies: "},
# to the list below.
map = [
    {"name":""},
    {"symbol": ""},
    {"price": " Price: "},
    {"percent_change_24h": " - 24 Hour Percent Change: "},
    {"market_cap": " Market Cap: "},
    {"volume_24h": " 24 Hour Volume: "},
    {"url_shares": " URL Shares: "},
    {"reddit_posts": " Reddit Posts: "},
    {"tweets": " Tweets: "},
    {"galaxy_score": " Galaxy Score: "},
    {"volatility": " Volatility: "},
    {"social_volume": " Social Volume: "},
    {"news": " News: "},
    {"close": " Close: "},
]
def final_render(asset_tweet, value, key, asset):
    # As the program becomes more complex, this should be written in a more robust manner
    if key == 'symbol':
        asset_tweet += " (" + asset[key] + ")"
    elif key == 'percent_change_24h':
        asset_tweet += value + str(asset[key]) + "%"
    else:
        asset_tweet += value + str(asset[key])
    return asset_tweet
# Iterates over each of the fields from Lunar Crush, gets the value from Lunar Crush and renders it with the field name
def main():
url = "https://api.lunarcrush.com/v2?data=assets&key=" + api_key + "&symbol=" + coins
    assets = json.loads(urllib.request.urlopen(url).read())
for asset in assets['data']:
        asset_tweet = ""
        for field in map:
            key = list(field.keys())[0]
            value = list(field.values())[0]
            asset_tweet = final_render(asset_tweet, value, key, asset)
        print(asset_tweet)
        print(len(asset_tweet))
        # Posts tweets
        api.update_status(status=asset_tweet)
# Runs main() every 30 minutes
while True:
    main()
    time.sleep(1800)

Example Crypto Twitter Bot Tweet

Additional Functionalities to Include in a LunarCRUSH + Python Twitter Bot

Not only can you post tweets; our LunarCRUSH Python Tweepy Twitter Bot can perform additional functionalities.

For example:

Pull information about a particular Twitter user — User methods

Configuration Options

It is possible to configure the bot to extract additional features. For example:

?key={API_KEY_HERE} - Required to render the widgets.
?symbol=BTC - Change the symbol that is displayed in the widgets.
?interval=1 Week - Change the time interval being displayed in the charts (default is 1 Week).
?price_correlation=true|false - Show a price line in addition to the selected metric (default = false)
?metric=galaxy_score - Change the timeseries metric being displayed (Metric widget only).
?animation=true|false - Show or hide component animations (default = true)
?theme={See themes section for instructions}
?scrolling=true|false (default = true) - Enable or disable scrolling on the widget inner content. Use this if you want to set scrolling=false on the iframe with a fixed height but still want to allow scrolling within the widget.

You have the ability to configure and add all available metrics from LunarCRUSH:

market_cap (Market Cap)
galaxy_score (Galaxy Score)
price_score (Price Score)
average_sentiment (Average Sentiment)
social_impact_score (Social Impact Score)
market_cap (Market Cap)
galaxy_score (Galaxy Score)
price_score (Price Score)
average_sentiment (Average Sentiment)
social_impact_score (Social Impact Score)
correlation_rank (Correlation Rank)
volatility (Volatility)
social_score (Social Volume)
social_volume (Social Volume)
twitter_volume (Twitter Volume)
reddit_volume (Reddit Volume)
news_volume (News Volume)
search_volume (Search Volume)
spam_volume (Spam Volume)
bullish_sentiment (Bullish Sentiment)
bearish_sentiment (Bearish Sentiment)

Metrics Widgets
average_sentiment (Average Sentiment)
correlation_rank (Correlation Rank)
galaxy_score (Galaxy Score)
market_cap (Market Cap)
market_cap_rank (Market Cap Rank)
news_articles (News Volume)
popular_tweet (Popular Tweets)
price_btc (Price BTC)
price_score (Price Score)
priceclose (Price Close)
pricehigh (Price High)
pricelow (Price Low)
priceopen (Price Open)
reddit_comment (Reddit Comments)
reddit_post (Reddit Posts)
reddit_post_reddit_comment (Reddit Volume)
search_average (Search Volume)
social_impact_score (Social Impact Score)
social_score (Social Volume)
tweet (Twitter Volume)
tweet_sentiment1 (Very Bearish Sentiment)
tweet_sentiment2 (Bearish Sentiment)
tweet_sentiment2_tweet_sentiment (Negative Sentiment)
tweet_sentiment3 (Neutral Sentiment)
tweet_sentiment4 (Bullish Sentiment)
tweet_sentiment5 (Very Bullish Sentiment)
tweet_sentiment4_sentiment5 (Positive Sentiment)
tweet_sentiment_impact1 (Very Bearish Sentiment Impact)
tweet_sentiment_impact2 (Bearish Sentiment Impact)
tweet_sentiment_impact3 (Neutral Sentiment Impact)
tweet_sentiment_impact4 (Bullish Sentiment Impact)
tweet_sentiment_impact5 (Very Bullish Sentiment Impact)
tweet_spam (Spam Volume)
volatility (Volatility)
volumefrom (Market Volume Open)
volumeto (Market Volume Close)

Final Thoughts

Within a few lines of code, your easily configurable Twitter bot now pulls data from LunarCRUSH and automatically engages your audience with real-time reliable social insights.

There are a few things that can be done to improve the code, such as additional LunarCRUSH parameters to tweet robust cryptocurrency data or visually appealing tweets with images and hashtags.

Please let me know in the comments if you have any questions or suggestions.

read original article here