Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elizabot #1

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions clever.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
from twython import Twython

import os
import time
import sys
import time
import cleverbottwo
import eliza
import datetime
from random import choice, randint
from creds import *
#import any other natual processing libs


"""Serialize function. Writes the last_reply_id to the file ~/.twitter_last_reply"""
def cleanup(last_id):
try:
filename = os.environ.get("HOME",'')+os.sep+'.twitter_last_reply'
f = file(filename, 'w')
f.write(last_id)
f.close()
except IOError:
print "[!] ERROR could not open", filename


#These are the keys from the twitter tools for python library.
CONSUMER_KEY = 'uS6hO2sV6tDKIOeVjhnFnQ'
CONSUMER_SECRET = 'MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'

# input your bot handle
handle = "@silshack"

clock = datetime.datetime.now()

doctor = eliza.eliza()

doctorisms = [" Mmkay?", " Hmmm?", " :/", " :)", " I mean...."]

statuses = [u' (╯°□°)╯︵ ┻━┻)',
u'I drifted off there for a bit....Ƹ̵̡Ӝ̵̨̄Ʒ',
u'¯\_(ツ)_/¯ wah wahh',
u'Time for a fish: .·´¯`·.´¯`·.¸¸.·´¯`·.¸><(((º>',
u'I wish I owned a little cabin somewhere. __̴ı̴̴̡̡̡ ̡͌l̡̡̡ ̡͌l̡*̡̡ ̴̡ı̴̴̡ ̡̡͡|̲̲̲͡͡͡ ̲▫̲͡ ̲̲̲͡͡π̲̲͡͡ ̲̲͡▫̲̲͡͡ ̲|̡̡̡ ̡ ̴̡ı̴̡̡ ̡͌l̡̡̡̡.___',
u'HANDS OFF MY SERVERS ̿\̵͇̿̿\з=(◕_◕)=ε/̵͇̿̿/',
u'ˁ˚ᴥ˚ˀ That is all.',
u'()==[:::::::::::::>',
u'▇ ▅ █ ▅ ▇ ▂ ▃ ▁ ▁ ▅ ▃ ▅ ▅ ▄ ▅ ▇']


if __name__ == "__main__":

#anyone talking to us?
last_id_replied = ''
speaker_id = ''
message_id = ''

#we serialize into a file in ~/.twitter_last_reply. check if this file is present and read value.
last_file = os.environ.get("HOME",'')+os.sep+'.twitter_last_reply'
if os.path.exists(last_file):
try:
id_file=file(last_file , 'r')
id = id_file.readline()
last_id_replied = id.strip()
print "[+] Read last_reply_id", last_id_replied
except IOError:
print"[!] Could not read ", last_file
else: print"[!] Didn't find ~/.twitter_last_reply file.. starting fresh prince"

#twitter client to post. Posting requires oAuth schutff
twitter = Twython(APP_KEY, APP_SECRET, FINAL_OAUTH_TOKEN, FINAL_OAUTH_TOKEN_SECRET)

#our cleverbot instance
cbot=cleverbottwo.Session()
#main loop. Just keep searching anyone talking to us
while True:
try:
mentions = twitter.search(q=handle, since_id=last_id_replied)['statuses']
if not mentions:
print "No one talking to us now...", time.ctime()
for mention in mentions[:3]:
#cut our handle out
message = mention['text'].replace(handle , '')
message_id = mention['id']
speaker = mention['user']['screen_name']

speaker_id = str(mention['user']['id'])
print "[+] Something named "+speaker+" is saying "+message

# If it's not the bot speaking:
if speaker != handle[1:]:
# follow the user
twitter.create_friendship(screen_name = speaker, follow = "true")
#clever_response = cbot.Ask(message)
clever_response = doctor.respond(message.strip())
reply = '@%s %s' % (speaker, clever_response + choice(doctorisms))
print "[+] Replying " , reply
twitter.update_status(status=reply, in_reply_to_status_id = message_id)
#update last_id_replied
last_id_replied=str(int(message_id) + 1)
cleanup(last_id_replied)

print "Last message_id was ", message_id
print "[Zzz] Slumber...\n"
time.sleep(10)
hour = clock.hour
if randint(1, 10000) < 416:
if hour > 10 and time.hour < 24:
zzz = "z" * randint(1,10) + "." * randint(1,25)
twitter.update_status(status==zzz)
stat = choice(statuses)
print "Soooo bored. Saying something random now:"
print stat
twitter.update_status(status=stat)

except KeyboardInterrupt:
print"[!] Cleaning up. Last speaker_id was ", speaker_id, ". Last message_id was ", message_id
cleanup(last_id_replied)
sys.exit()

167 changes: 167 additions & 0 deletions cleverbot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""
Extracted source from https://pypi.python.org/pypi/cleverbot/0.1.1
"""

from hashlib import md5
import pprint
import urllib, urllib2

class Cleverbot:

HOST = "www.cleverbot.com"
PROTOCOL = "http://"
RESOURCE = "/webservicemin"
API_URL = PROTOCOL + HOST + RESOURCE

DEBUG = False

headers = \
{ 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)'
, 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
, 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
, 'Accept-Language' : 'en-us,en;q=0.8,en-us;q=0.5,en;q=0.3'
, 'Cache-Control' : 'no-cache'
, 'Host' : HOST
, 'Referer' : PROTOCOL + HOST + '/'
, 'Pragma' : 'no-cache'
}

def __init__(self, debug=False):
self.DEBUG = debug
self.__debug("Initializing new session")

""" The data that will get passed to Cleverbot's web API """
self.data = \
{ 'stimulus' : ''
, 'start' : 'y' # Never modified
, 'sessionid' : ''
, 'vText8' : ''
, 'vText7' : ''
, 'vText6' : ''
, 'vText5' : ''
, 'vText4' : ''
, 'vText3' : ''
, 'vText2' : ''
, 'icognoid' : 'wsf' # Never modified
, 'icognocheck' : ''
, 'fno' : 0 # Never modified
, 'prevref' : ''
, 'emotionaloutput' : '' # Never modified
, 'emotionalhistory' : '' # Never modified
, 'asbotname' : '' # Never modified
, 'ttsvoice' : '' # Never modified
, 'typing' : '' # Never modified
, 'lineref' : ''
, 'sub' : 'Say' # Never modified
, 'islearning' : 1 # Never modified
, 'cleanslate' : False # Never modified
}

""" The log of our conversation with Cleverbot """
self.conversation=[]

def ask(self,q):
"""Asks Cleverbot a question.

Maintains message history.

Args:
q (str): The question to ask
Returns:
Cleverbot's answer
"""
self.__debug("Asking a question", q)

# Set the current question
self.data['stimulus'] = q

# Connect to Cleverbot's API and remember the response
resp = self._send()

# TODO ensure Cleverbot received the question properly

# Add the current question to the conversation log
self.conversation.append(q)

#parsed = self._parse(resp)

# Set data as appropriate
#if self.data['sessionid'] != '':
# self.data['sessionid'] = parsed['conversation_id']

# Add Cleverbot's reply to the conversation log
# self.conversation.append(parsed['answer'])

#return parsed['answer']
return resp


def _send(self):
"""POST the user's question and all required information to the
Cleverbot API

Cleverbot tries to prevent unauthorized access to its API by
obfuscating how it generates the 'icognocheck' token, so we have
to URLencode the data twice: once to generate the token, and
twice to add the token to the data we're sending to Cleverbot.
"""
self.__debug("Sending data")

# Set data as appropriate
if self.conversation:
linecount = 1
for line in reversed(self.conversation):
linecount += 1
self.data['vText'+str(linecount)] = line
if linecount == 8:
break

# Generate the token
enc_data = urllib.urlencode(self.data)
digest_txt = enc_data[9:29]
token = md5(digest_txt).hexdigest()
self.data['icognocheck'] = token

# Add the token to the data
enc_data = urllib.urlencode(self.data)
req = urllib2.Request(self.API_URL, enc_data, self.headers)

# POST the data to Cleverbot's API
conn = urllib2.urlopen(req)
resp = conn.read()

# Return Cleverbot's response
return resp

def _parse(self, text):
"""Parses Cleverbot's response"""

self.__debug("Parsing response")

parsed = map(lambda e: e.split('\r'), text.split('\r\r\r\r\r\r')[:-1])

return \
{ 'answer' : parsed[0][0]
, 'conversation_id' : parsed[0][1]
, 'conversation_log_id' : parsed[0][2]
, 'unknown': parsed[1][-1]
}

def __debug(self, *args):
"""Print stuff to stdin if DEBUG is true"""

if self.DEBUG:
print args

if __name__ == "__main__":
cb1 = Cleverbot()
cb2 = Cleverbot()

resp1 = cb1.ask("Hello.")
print "Bob:", "Hello"

while True:
print "Alice:", resp1
resp2 = cb2.ask(resp1)
print "Bob:", resp2
resp1 = cb1.ask(resp2)
Loading