-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_talk.py
149 lines (131 loc) · 4.7 KB
/
random_talk.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import string
import re
import random
import pickle
import json
import urllib2
import urllib
pairs = ()
chat_files = open('Random_chat.pkl', 'rb')
pairs=pickle.load(chat_files)
offensive=['boobs','fuck','suck','dick','bitch','ass','tits','pussy','cock','milf']
reflections = {
"am" : "are",
"was" : "were",
"i" : "you",
"i'd" : "you would",
"i've" : "you have",
"i'll" : "you will",
"my" : "your",
"are" : "am",
"you've" : "I have",
"you'll" : "I will",
"your" : "my",
"yours" : "mine",
"you" : "me",
"me" : "you"
}
class Chat(object):
def __init__(self, pairs,reflections={}):
"""
Initialize the chatbot. Pairs is a list of patterns and responses. Each
pattern is a regular expression matching the user's statement or question,
e.g. r'I like (.*)'. For each such pattern a list of possible responses
is given, e.g. ['Why do you like %1', 'Did you ever dislike %1']. Material
which is matched by parenthesized sections of the patterns (e.g. .*) is mapped to
the numbered positions in the responses, e.g. %1.
:type pairs: list of tuple
:param pairs: The patterns and responses
:type reflections: dict
:param reflections: A mapping between first and second person expressions
:rtype: None
"""
self._pairs = [(re.compile(x, re.IGNORECASE),y) for (x,y) in pairs]
self._reflections = reflections
# bug: only permits single word expressions to be mapped
def _substitute(self, str):
"""
Substitute words in the string, according to the specified reflections,
e.g. "I'm" -> "you are"
:type str: str
:param str: The string to be mapped
:rtype: str
"""
words = ""
for word in string.split(string.lower(str)):
if word in self._reflections:
word = self._reflections[word]
words += ' ' + word
return words
def _wildcards(self, response, match):
pos = string.find(response,'%')
while pos >= 0:
num = string.atoi(response[pos+1:pos+2])
response = response[:pos] + \
self._substitute(match.group(num)) + \
response[pos+2:]
pos = string.find(response,'%')
return response
def respond(self, str):
"""
Generate a response to the user input.
:type str: str
:param str: The string to be mapped
:rtype: str
"""
# check each pattern
for (pattern, response) in self._pairs:
match = pattern.match(str)
# did the pattern match?
if match:
resp = random.choice(response) # pick a random response
resp = self._wildcards(resp, match) # process wildcards
# fix munged punctuation at the end
if resp[-2:] == '?.': resp = resp[:-2] + '.'
if resp[-2:] == '??': resp = resp[:-2] + '?'
return resp
# Hold a conversation with a chatbot
def converse(self, inp):
self.inp=inp
if self.inp:
response= self.respond(self.inp)
if (('encyclopedia' in response) and (random.randint(1,2) % 2 == 0)):
search=inp.split()
search='+'.join(search)
search='http://lmgtfy.com/?q='+search
return search
else:
return response
rude_chatbot = Chat(pairs, reflections)
def rude_chat(input_line):
if input_line[-1] == '!':
input_line=input_line[:-1]
url='http://api.duckduckgo.com/?' + urllib.urlencode({"q":str(input_line)}) +'&format=json&kp=-1&pretty=1'
try:
proxy = urllib2.ProxyHandler({'http': 'proxy.iiit.ac.in:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
data=urllib2.urlopen(url).read()
except:
return rude_chatbot.converse(input_line)
if random.randint(1,10) > 5:
if '<TITLE>ERROR: The requested URL could not be retrieved</TITLE>' not in data:
text=json.loads(data)
if text:
text2=(text['Abstract']).encode('utf-8')
text3=str(text['AbstractURL']).encode('utf-8')
text=text2+'<br/>'+text3
if text2:
return text2
else:
text=rude_chatbot.converse(input_line)
if text3:
return str(text)+'<br/>'+" Wiki Uncle says this might help you: <a href='"+str(text3)+"'>Wikipage</a>"
else:
return rude_chatbot.converse(input_line)
else:
return rude_chatbot.converse(input_line)
else:
return rude_chatbot.converse(input_line)
else:
return rude_chatbot.converse(input_line)