Building a LocalBitcoins Autoresponder Bot in Python

9
158

This is a gem I’ve been waiting to share for a long time. But given it’s a new year, and I’m giving True Miller a good hard shove, its time to release some value.

Warning: the code and concepts covered in this article are for proof of concept only. I am not responsible should any unsavoury outcomes occur.

I’m going to show you guys how to build an automated LocalBitcoins autoresponder. A bot, software, that will automatically respond to your LocalBitcoins trade contacts.

This an incredibly good way to keep your response time as low as possible, and is perfect for those of you that are getting inundated with trades in the current climate.

If you’re not already on LocalBitcoins and/or you’ve got no idea what I’m talking about:

  • Signup to LocalBitcoins. It’s a person-to-person Bitcoin trading marketplace; they all support other coins too, but mainly Bitcoin; you can get great deals.
  • Read my LocalBitcoins-based Bitcoin flipping tutorial. I’ve literally put together a method that you can pick up and run with to make money. This bot article your reading is meant to support this method. Probably wise to start there if you’re lost.

Without further ado, lets get into the magic.

Requirements

Fulfil these requirements in order. And please click my LocalBitcoins link as a thank you. If you haven’t, then signup to something else I’ve linked. Appreciated. Thanks. Anyway:

It’s important that you get a LocalBitcoins account first. Complete verification sooner rather than later if you haven’t already joined. No point building a bot if you don’t have an account yet. Verification does take time, start the ball rolling.

image 11
Verification is simple for Tier 0; input your email, name and country of residence.

Then, install Python, followed by PIP. Python is the programming language the bot is built in. PIP installs packages (pre-written code) that we can link into the Python script. The script I’ve put together uses a few different packages. The packages are simple, and vital.

Clone the LBCAPI repo from github. You might be wincing thinking this is way to complex. You’re wrong. Don’t be a pussy. Watch a YouTube video on how to clone from GitHub. If you know what you’re doing already, congratulations.

Okay:

  • If you’re not a developer, try not to deviate from the guide until you understand what you’re doing. You don’t want to send a bot wild that doesn’t work. Could be disastrous. But no risk no reward. Keep plodding on.

Building a LocalBitcoins Autoresponder

In this section, we’ll actually build the bot. I’m assuming you’ve already got all the relevant requirements. They’re highlighted in bold a few centimetres up the page. I tried to make to obvious, but if you missed it, pay attention.

Connect to LocalBitcoins API with Python

Connection to LocalBitcoins is vital; all other sections will extend this basic connection and can be pasted below the basic connection script.

But first …

1. Generate LocalBitcoins HMAC (API) keys

Provided you’ve signed up, you’ll be able to generate an HMAC key from the Apps Dashboard. This key will allow the bot to communicate with your LocalBitcoins account directly.

Store your HMAC API keys somewhere safe. You don’t want to advertise them on Twitter.

If you want to give your Bitcoin, you can send them directly to this address: bc1qcsgee8eak6kk3snfmlu9afxangjfsmrw23ax2r. For real. I’d appreciate it.

image 12
You’ll need HMAC keys if you want to use this software.

2. Create a new Python script

Create a new folder, drop the LBCAPI library into it. This is the thing you cloned from Github earlier.

Then, create a new Python script in this folder you’ve created. For example, test.py.

image 15
See how the lbcapi folder is in the same folder as the scripts I’ve created, test.py and test2.py.

3. Paste in this python script

Have done my best to make this super simple. Input your LocalBitcoins details in the creds part.

'''
test.py
My LocalBitcoins Bot
'''
# Packages required for the script
import json, time, datetime

# Import LCBAPI; this will give us some useful functionality to connect to the Localbitcoins API
from lbcapi import api

# Store your localbitcoins credentials here; HMAC and username
creds = {
    username: 'truemiller6969',
    hmac_key: 'abcdefg',
    hmac_secret: '123456'
}

# Connection; what we will use to connect to the API
connection = api.hmac(creds['hmac_key'], creds['hmac_secret'])

Building a LocalBitcoins Autoresponder

Please note, this code is only proof of concept and comes with no warranties, liability, nor safety precautions. Only run this if you know what you’re doing!

As I mentioned earlier, the idea behind running an autoresponder is so you keep your response time to a minimum and you don’t miss trades. Flipping Bitcoin on LocalBitcoins can get a bit overwhelming if you’re getting lots of orders.

This software automates the first message sent to customers. You’ll want to:

  • Welcome the customer,
  • send the relevant details,
  • and change the message based on whether you are buy or selling.

Sellers need your account details, buyers need to send their details.

The script

Here is my script template you can tinker with.

'''
bot.py
My LocalBitcoins Bot
'''
import json, time, datetime

# Import LCBAPI; this will give us some useful functionality to connect to the Localbitcoins API
from lbcapi import api

# Store your localbitcoins credentials here; HMAC and username
creds = {
    username: 'truemiller6969',
    hmac_key: 'abcdefg',
    hmac_secret: '123456'
}

# Connection; what we will use to connect to the API
connection = api.hmac(creds['hmac_key'], creds['hmac_secret'])

'''
FUNCTIONS 
'''
def getDashboard(connection = None)
	dashboard = conn.call('GET', '/api/dashboard/').json()['data']
	return dashboard

def getMessages(connection=None, contact_id="123456"):
	messages = connection.call('GET', '/api/contact_messages/%s/'%(contact_id)).json()
	return messages


'''
MAIN FUNCTION
'''
def main():
	while True: # loop forever, or until cancel (Ctrl+C)

		# Reset variables
		localBitcoinsDashboard = localBitcoinsDashboardContacts = []
		trade_type=contact_id=buyer=payment_completed_at=contact_reference=seller=amount=payment_completed_at=messages=None

		# Print the time (for updates)
		print(datetime.datetime.now())

		# Get all the contacts (open trades)
		localBitcoinsDashboardContacts = getDashboard(connection)['contact_list']

		# If there are any contacts
		if len(localBitcoinsDashboardContacts) > 0:
			# Tell user how many trades there are
			print("╿ " + "You have %d open trades." % (len(getDashboard['contact_list']))) 
			# Loop through all the contacts
			for contact in localBitcoinsDashboardContacts:  
				# store the contact data in easily accessed variables  
				trade_type = contact['data']['advertisement']['trade_type']
				contact_id = contact['data']['contact_id']          
				buyer = contact['data']['buyer']
				payment_completed_at = contact['data']['payment_completed_at']
				contact_reference = contact['data']['reference_code']
				seller = contact['data']['seller']
				amount = contact['data']['amount']
				payment_completed_at = contact['data']['payment_completed_at']
				# get messages from the contact
				messages = getMessages(connection, contact_id)['data']
				# print progress dependant on type of trade
				if trade_type == 'ONLINE_BUY':
					print((("[" + str(datetime.datetime.now()) + "]") + ' %d %s %s %s %s') % (contact_id, seller['name'], trade_type, amount, payment_completed_at))
				else:
					print(("[" + str(datetime.datetime.now()) + "]") + ' %d %s %s %s %s' % (contact_id, buyer['name'], trade_type, amount, payment_completed_at))
			
			## AUTO RESPONDER
			# Send first nmessage 
			your_response_count = 0
			for message in messages['message_list']:
				if message['sender']['username'] == creds['username']:
					your_response_count = your_response_count + 1
				else:
					your_response_count = your_response_count   


			if your_response_count <= 0 and trade_type == 'ONLINE_SELL':
				print('┗━ Sending seller message.')
				print(json.dumps(connection.call('post', '/api/contact_message_post/' + str(contact_id) + '/', params={
					'msg': 'Hi, thanks for agreeing to the terms by opening a trade.+\n\n'
					'My Bitcoin is now in Escrow, please make payment ASAP.'
					' If you have no intentions of continuing with the trade, please cancel the trade so my Bitcoin is released back to me and I can continue trading.\n\n'
					'+== REFERENCE MUST BE EXACT (NOTE, THIS UPDATES EVERY TRADE) ==+\n\n\n\n'
					'Details are as follows\n+=====================+\n'
					'Name: [NAME ON ACCOUNT]\n'
					'Sort Code: 123456\n'
					'Account Number: 123456789\n'
					'Reference: ' + str(contact_reference) + ' \n'
					'+=====================+\nPlease, MARK AS PAID once you have paid.'}).json()))
			elif your_response_count <= 0 and trade_type == 'ONLINE_BUY':
				print('┗━ Sending buyer message')
				print(json.dumps(connection.call('post', '/api/contact_message_post/' + str(contact_id) + '/', params={
					'msg': '.\n Hi there, just a moment and your funds will be on their way!\n'}).json()))
			else:
				print('┗━ Sending no message')
		time.sleep(10) # IMPORTANT, DONT SPAM THE API

I’ve done my best to comment each section. But I’d highly advise you to read the script from top to bottom. It’s important that you fully understand it before you let it loose.

Final Thoughts & Future Script Releases

Building a LocalBitcoins autoresponder is fairly simple. Use the code examples above, tinker with it, change it, and thank me for it.

Seriously, comments and feedback or my literal lifeforce. Without your feedback it gets hard to create content, I am human. I know you’re out there, I see the hits and the followers. Speak to me!

Anyway, to reiterate:

  • If you don’t know what this bot can be used for. check out my LocalBitcoins flipping guide.
  • I do have more things I can release too. For example, a LocalBitcoins auto-pricer, that competitively prices your listings against others’. And some past code for bank API automation for checking if payments have been received. If you’d like to get hold of this stuff, drop a comment, subscribe for updates and you’ll be the first to get it.

9 COMMENTS

  1. Hi, great article! About the “LocalBitcoins auto-pricer”:

    1) Would it be able to limit the listing to a minimum % (spread), preventing any losses as a result of the competitor listing his price too low?

    2) Anywhere we can get it somehow?

    Thanks!

  2. Hi there thank you so much for this information please can you drop your discord link as I don’t see it in the website

LEAVE A REPLY

Please enter your comment!
Please enter your name here