0 Google+ 0 Reddit 355 StumbleUpon 0 Pinterest 0

I have recently been working on a new project that required scraping data from other websites and have been slowly learning python. I usually work with PHP but I knew python will work faster and better. I also have always wanted to create a simple chatbot that I can input text into and it would reply with something meaningful. Creating a chatbot with a huge database of words and actually understanding what is being said is not an easy task and is something that is way over my head. I was browsing Reddit and found out that you can get results in JSON format is you append ‘.json‘ to the end of the URL. This got me thinking, what if I search Reddit with a question or comment and pick a random search result and reply with one of the top comments. This would fill my urge in creating a chatbot and it would also be a good starting point if I ever wanted to go deeper into creating a database and store answers for the chatbot to get a personality of its own.

I figured the Raspberry Pi would be an easy starting point since I have a bunch of them laying around and it is already setup with a Python environment. You can easily replicate this in any Python environment but I tested out my chatbot on the Raspberry Pi.

Objective

To create a chatbot in Python on the Raspberry Pi that searches Reddit and replies using a Reddit comment

Material

You will need the following:

Instructions

Create a new file on the Raspberry Pi and call it main.py

Copy the code into main.py and save the file. To run the file open a terminal window on the Raspberry Pi and navigate to the folder the file is located in. Run the following command:

python main.py 1 python main . py

You should get a prompt asking you to “Ask me anything: “. Ask the chatbot anything and see what reply you get.

Python Source Code

import requests import json import random #The main function that will grab a reply def grab_reply(question): #Navigate to the Search Reddit Url r = requests.get('https://www.reddit.com/r/AskReddit/search.json?q=' + question + '&sort=relevance&t=all', headers = {'User-agent': 'Chrome'}) answers = json.loads(r.text) #Load the JSON file Children = answers["data"]["children"] ans_list= [] for post in Children: if post["data"]["num_comments"] >= 5: #Greater then 5 or equal comments ans_list.append (post["data"]["url"]) #If no results are found return "I have no idea" if len(ans_list) == 0: return "I have no idea" #Pick A Random Post comment_url=ans_list[random.randint(0,len(ans_list)-1)] + '.json?sort=top' #Grab Random Comment Url and Append .json to end #Navigate to the Comments r = requests.get(comment_url, headers = {'User-agent': 'Chrome'}) reply= json.loads(r.text) Children = reply[1]['data']['children'] reply_list= [] for post in Children: reply_list.append(post["data"]["body"]) #Add Comments to the List if len(reply_list) == 0: return "I have no clue" #Return a Random Comment return reply_list[random.randint(0,len(reply_list)-1)] #Main Loop, Always ask for a question while 1: q=raw_input("Ask me anything: ") q=q.replace(" ", "+") #Replace Spaces with + for URL encoding print(grab_reply(q)) #Grab and Print the Reply 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import requests import json import random #The main function that will grab a reply def grab_reply ( question ) : #Navigate to the Search Reddit Url r = requests . get ( 'https://www.reddit.com/r/AskReddit/search.json?q=' + question + '&sort=relevance&t=all' , headers = { 'User-agent' : 'Chrome' } ) answers = json . loads ( r . text ) #Load the JSON file Children = answers [ "data" ] [ "children" ] ans_list = [ ] for post in Children : if post [ "data" ] [ "num_comments" ] >= 5 : #Greater then 5 or equal comments ans_list . append ( post [ "data" ] [ "url" ] ) #If no results are found return "I have no idea" if len ( ans_list ) == 0 : return "I have no idea" #Pick A Random Post comment_url = ans_list [ random . randint ( 0 , len ( ans_list ) - 1 ) ] + '.json?sort=top' #Grab Random Comment Url and Append .json to end #Navigate to the Comments r = requests . get ( comment_url , headers = { 'User-agent' : 'Chrome' } ) reply = json . loads ( r . text ) Children = reply [ 1 ] [ 'data' ] [ 'children' ] reply_list = [ ] for post in Children : reply_list . append ( post [ "data" ] [ "body" ] ) #Add Comments to the List if len ( reply_list ) == 0 : return "I have no clue" #Return a Random Comment return reply_list [ random . randint ( 0 , len ( reply_list ) - 1 ) ] #Main Loop, Always ask for a question while 1 : q = raw_input ( "Ask me anything: " ) q = q . replace ( " " , "+" ) #Replace Spaces with + for URL encoding print ( grab_reply ( q ) ) #Grab and Print the Reply

Input / Outputs

Below are some sample Input / Outputs that I got from my chatbot.

Input: Whats your name? Output: My name is Lara and I never really thought it fits me, especially during my teens I always wanted a longer, more sophisticated name with a cute nickname. I have never had a short nickname, as kids the others called me Lara Croft sometimes. In addition, substitute teachers kept calling me Laura, Sarah etc. (Im German they sound kinda similar) 1 2 Input : Whats your name ? Output : My name is Lara and I never really thought it fits me , especially during my teens I always wanted a longer , more sophisticated name with a cute nickname . I have never had a short nickname , as kids the others called me Lara Croft sometimes . In addition , substitute teachers kept calling me Laura , Sarah etc . ( Im German they sound kinda similar )

Input: ​Whats your favorite cheese? Output: Brie on a warm baguette. I'm salivating just thinking of it. 1 2 Input : ​ Whats your favorite cheese ? Output : Brie on a warm baguette . I ' m salivating just thinking of it .

Input: Do you know you are a robot? Output: Everyone on Reddit is a bot except you. 1 2 Input : Do you know you are a robot ? Output : Everyone on Reddit is a bot except you .

Input: How smart are you? Output: Smart enough to know the world is full of people who know way more about every topic I know a lot about. 1 2 Input : How smart are you ? Output : Smart enough to know the world is full of people who know way more about every topic I know a lot about .

Input: Whats the meaning of life? Output: How the fuck would I know? I'm 5 1 2 Input : Whats the meaning of life ? Output : How the fuck would I know ? I ' m 5

Hopefully this Reddit Chatbot inspires you to work on something and even expand on it. You can store answers in a database for future use or you can analyze them and train the chatbot. If you use my code for anything please let me know, I would love to hear on how you expanded it.