0
votes

I'm building a coinbase bot in python that uses twilio to fetch my coinbase portfolio, and send an SMS to my phone with the current balance. What I am trying, but struggling to do now, is to conduct coinbase transactions based on the message I send back to the twilio number.

For twilio to receive my messages, I had to set up a small flask server and funnel the environment to a public ngrok url, which I then attach in my twilio account settings as a webhook url to receive messages.

Here's my flask:

msg_app.py

from twilio.rest import Client as twilioClient
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from pyngrok import ngrok


app = Flask(__name__)


@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    """Fetch message response to extract order data"""
    body = request.values.get('Body', None)

    resp = MessagingResponse()

    resp.message('test')

    return str(resp)


if __name__ == "__main__":
    app.run(debug=True)

Pretty much, I'll cd into the directory holding this script (msg_app.py), and run msg_app.py run to start the server. I'll then run ngrok http 5000 (5000 being the local host port) in a different cmd prompt, to start the funnel.

If I sent a message on my phone to the Twilio number, like 'Hello', I'll get test back as a response, but how, in my bot script, can I get that 'Hello' message, so I can then invoke logic based off the content of that message? Here's my bot, for example:

coinbase_bot.py

import dotenv
import selenium
import coinbase
import requests
from coinbase.wallet.client import Client
from dotenv import load_dotenv
import os
import sys
import re
from twilio.rest import Client as twilioClient
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
import msg_app
from msg_app import sms_reply


sys.path.insert(0, os.environ['USERPROFILE'])

dotenv_path = os.environ['USERPROFILE'] + '\prod.env'
load_dotenv(dotenv_path, override=True)

api_key = os.getenv('coinbase_api_key')
api_secret = os.getenv('coinbase_api_secret')

# TWILIO

account_sid = os.getenv('twilio_account_sid')
auth_token = os.getenv('twilio_auth_token')
twilio_number = os.getenv('twilio_number')

# Clients

coinbase_client = Client(api_key, api_secret)
twilio_client = twilioClient(account_sid, auth_token)

# user = coinbase_client.get_current_user()
accounts = coinbase_client.get_accounts()
currencies = coinbase_client.get_currencies()
id = accounts['data'][0]['id']

class Bot:

    def __init__(self, accounts):
        self.accounts = accounts
        self.account_id = self.accounts['data'][0]['id']
        # self.method_id =

    def get_current_price(self, ticker):

        for coin in accounts['data']:
            if coin['currency'] == ticker:
                value = "$" + str(coin['native_balance']['amount'])

        self.value = value

        return self.value

    def send_notification(self):

        price = self.get_current_price('LRC')

        self.message = twilio_client.messages.create(
            body='The price of your portfolio is currently: ' + str(price),
            from_=twilio_number,
            to='+1555555555')

    def fetch_payment_method(self):

        payment_method = coinbase_client.get_buys(self.account_id)
        self.method_id = payment_method[0]['payment_method']['id']
        # set up twilio, to end notification when price is below certain amount

    def execute_sales(self, account_id, amount, currency, method_id):

        coinbase_client.sell(account_id=account_id, amount=amount,
                             currency=currency, method_id=method_id)

    def receive(self, msg):

        self.ticker = "".join(re.findall(r'[A-Z]{3}', msg))
        self.amount_to_sell = "".join(re.findall(r'[0-9]', msg))

        b.execute_sales(account_id=self.account_id, currency=self.ticker,
                        amount=amount_to_sell, method_id=self.method_id)

        # based on SMS response, method executes trade
b = Bot(accounts)

I'd like to run the receive function to execute a sale based on message content. Can I do this? I was trying to extract the body content from the flask script like: body = request.values.get('Body', None) and somehow send this result back to the bot. But, since msg_app is like the server script, how can I call that script inside my bot, without messing up the server?

Maybe I should wrap the bot in a while loop, and put receive in a try/except clause?

Or, maybe I have limited understanding of how all this works. Hope I was clear.

1

1 Answers

0
votes

You need to use a Twilio client in the flask app. Read the following article, it has the necessary things covered to receive sms content. https://www.twilio.com/blog/real-time-sms-dashboard-python-flask-twilio-sync