Bitcoin Twitter Bot

I got very interested in Bitcoin during my freshman year of high school. I wanted an application or service that could send me a notification every hour with the price of Bitcoin and how much it had gone up/down in the past few hours. To my surprise, no such application existed. So (as my first Python project) I wrote a script that gathers the price of Bitcoin currently as well as 1 hour ago, 5 hours ago and 24 hours ago using Crypto Compare's Free API. The script then calculates the percent change and formulates a tweet with the information I wanted to receive. The code is now on a Raspberry Pi running 24 hours a day without having to keep my personal computer open and connected to WiFi. The code is below and the Twitter feed is embedded to the right. The Python libraries used in the program include: Requests, Schedule, Tweepy, and Pandas.

Code (Python)

import requests

import pandas as pd

import tweepy

import schedule


print('RUNNING')


def upload():

# Create empty list for historical data

historicalCloseData = []

# Define API URL and request JSON

historicalURL = "https://min-api.cryptocompare.com/data/v2/histohour?fsym=BTC&tsym=USD&limit=25"

historicalData = requests.get(historicalURL)

# Create pandas df to handle data

ipdata = historicalData.json()

dataFrame = pd.DataFrame(ipdata['Data']['Data'])

# Iterate through close column and append values to list

for closeColumn in dataFrame['close']:

historicalCloseData.append(closeColumn)


# Fetch Time

EST_datetime_data = requests.get('http://worldtimeapi.org/api/timezone/Etc/GMT+6.json')

EST_datetime = (EST_datetime_data.json()['datetime'])

EST_time = (EST_datetime[11:16])


# Define Emoji Unicode (For RasPi)

broken_heart = ('\U0001F494' + ' -')

green_heart = ('\U0001F49A' + ' +')


# Find current price and prices from 1, 5 and 24 hours ago

current = (historicalCloseData[24])

price1hr = (historicalCloseData[23])

price5hr = (historicalCloseData[19])

price24hr = (historicalCloseData[0])


# Calculate 1 hour values

difference_1hr = float(current) - float(price1hr) # Calculates difference

percent_of_whole_1hr = float(current) / float(price1hr) # Calculates pre decimal number

percent_in_decimal_1hr = float(percent_of_whole_1hr) - 1 # Converts two decimal

percent_1hr = float(percent_in_decimal_1hr) * 100 # Converts from decimal to percent

rounded_dif_1hr = (round(difference_1hr, 2)) # Rounds difference

rounded_percent_1hr = (round(percent_1hr, 2)) # Rounds Percent

# Calculate 5 hour values

difference_5hr = float(current) - float(price5hr) # Calculates difference

percent_of_whole_5hr = float(current) / float(price5hr) # Calculates pre decimal number

percent_in_decimal_5hr = float(percent_of_whole_5hr) - 1 # Converts two decimal

percent_5hr = float(percent_in_decimal_5hr) * 100 # Converts from decimal to percent

rounded_dif_5hr = (round(difference_5hr, 2)) # Rounds difference

rounded_percent_5hr = (round(percent_5hr, 2)) # Rounds Percent

# Calculate 24 hours values

difference_24hr = float(current) - float(price24hr) # Calculates difference

percent_of_whole_24hr = float(current) / float(price24hr) # Calculates pre decimal number

percent_in_decimal_24hr = float(percent_of_whole_24hr) - 1 # Converts two decimal

percent_24hr = float(percent_in_decimal_24hr) * 100 # Converts from decimal to percent

rounded_dif_24hr = (round(difference_24hr, 2)) # Rounds difference

rounded_percent_24hr = (round(percent_24hr, 2)) # Rounds Percent



# Handle Increase/Decrease

if float(difference_1hr) > 0:

tweet_1hr = ("Bitcoin: " + '$' + str(current) + '\n' + green_heart + str(

rounded_dif_1hr) + " last 1 Hour " "(+" + str(rounded_percent_1hr) + "%)")

else:

tweet_1hr = ("Bitcoin: " + '$' + str(current) + '\n' + broken_heart + str(abs(rounded_dif_1hr))

+ " last 1 Hour " "(" + str(rounded_percent_1hr) + "%)")

if float(difference_5hr) > 0:

tweet_5hr = (green_heart + str(rounded_dif_5hr) + " last 5 Hours " "(+" + str(rounded_percent_5hr) + "%)")

else:

tweet_5hr = broken_heart + (

str(abs(rounded_dif_5hr)) + " last 5 Hours " + "(" + str(rounded_percent_5hr) + "%)")

if float(difference_24hr) > 0:

tweet_24hr = (green_heart + str(rounded_dif_24hr) + " last 24 Hours " "(+" + str(rounded_percent_24hr) + "%)")

else:

tweet_24hr = broken_heart + (

str(abs(rounded_dif_24hr)) + " last 24 Hours " "(" + str(rounded_percent_24hr) + "%)")


# Configure Tweepy

API_KEY = "******************************"

API_SECRET = "******************************"

ACCESS_TOKEN = "******************************-******************************"

ACCESS_TOKEN_SECRET = "******************************"

hashtags = "#BitcoinPriceUpdates #Bitcoin #HourlyCrypto #CryptoUpdates #Crypto"

# Create tweet string

tweet_whole = tweet_1hr + '\n' + tweet_5hr + '\n' + tweet_24hr + '\n' + hashtags + '\n' + 'Powered By CryptoCompare API'

# Authenticate tweepy

auth = tweepy.OAuthHandler(API_KEY, API_SECRET)

auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

# Send tweet

api.update_status(tweet_whole)

print('\n' + 'NEW UPDATE:' + EST_time)



# Run function every hour

try:

#schedule.every().day.at('22:51').do(upload) # TEST TWEET

schedule.every().hour.at(':00').do(upload)

while True:

schedule.run_pending()

time.sleep(1)

# If it fails, send my personal twitter a DM and send out the missed tweet

except:

print("SCRIPT EXCEPTION. SENDING MESSAGE. RESTART SCRIPT")

api.send_direct_message("****************", "SCRIPT EXCEPTION. BOT RESTARTED. RESTART SCRIPT.")

upload()

# Reschedule everything

finally:

schedule.every().hour.at(':00').do(upload)

while True:

schedule.run_pending()

time.sleep(1)