summaryrefslogtreecommitdiff
path: root/megahal_bot.py
blob: f1f3864d5163129cf61eb5d0b274c64506819026 (plain)
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import logging
from threading import Event
import random

import mh_python
import time
import pyPgSQL.PgSQL
from omegle import OmegleChat



class MegahalBot(OmegleChat):
	def __init__(self,disconnect_event,name,host="omegle.com",color=0):
		self.disconnect_event = disconnect_event
		self.name=name
		self.color = color
		OmegleChat.__init__(self,name=" Megahal",host=host)
		self.idlecount = 0
		

	def c(self,str,bold=False,color=0):
		if color == 0:
			color = self.color
		if bold:
			return "\033[1m\033[%sm%s\033[0m\033[0m" %(color, str)
		else:
			return "\033[%sm%s\033[0m" %(self.color, str)


	def respond(self,message,prepend=""):
		r=mh_python.doreply(message.encode("utf-8"))
		print self.c("%s%s [MSG] %s: %s" %(prepend,time.strftime("%H:%M:%S"), self.name, r),bold=True)
		try:
			self.send(r) #.decode("utf-8"))
		except Exception,e:
			print e
			self.disconnect_event.set()

	def on_idle(self):
		self.idlecount += 1
		if self.idlecount > 8:
			self.logger.info("Idle > 8. disconnect()")
			self.disconnect()
			self.disconnect_event.set()
		else:
			self.logger.info("Idle count %s/8" % self.idlecount)
			self.respond("hey?") #restart the conv.

	def on_message(self,message):
		print self.c("%s%s [MSG] %s: %s" %(
				"\033[1A\033[2K\033[30D",
				time.strftime("%H:%M:%S"), "Stranger", message),bold=True,color=32)
		self.idlecount = 0
		time.sleep(0.05)
		typestr = "%s [EVT] %s: typing" %(time.strftime("%H:%M:%S"),self.name)
		print self.c(typestr,bold=True,color=32)
		try:
			self.typing()
		except Exception,e:
			try:
				self.disconnect()
			except:
				self.disconnect_event.set()
			return
		time.sleep(random.randint(2,5))
		self.respond(message,prepend="\033[1A\033[2K\033[%sD"%(len(typestr))) #move up 1; delete line; move left %s

	def on_connect(self):
		print self.c("%s [EVT] %s Connection confirmed" % (time.strftime("%H:%M:%S"), self.name))


	def on_disconnect(self):
		print self.c("%s [EVT] %s disconnect" % (time.strftime("%H:%M:%S"), self.name))
		self.disconnect_event.set()



if __name__ == "__main__":
	import getopt
	import sys

	def usage():
		print """%s - megahal ding
Argumente:
  -h, --help		Diese Hilfe
  --host=HOST		(Standard: HOST=omegle.com)
  -d DBNAME       or
  --dbname=DBNAME	Database (Standard: DBNAME=omegle)
  -l              or
  --local               Do local testing
  -p NAME         or
  --profile=NAME	Database select profile (Standard: NAME=standard)
			see sourcecode""" % (sys.argv[0])

	#parse args
	try:
		opts, args = getopt.getopt(sys.argv[1:], "hp:d:l", ["help", "host=", "profile=","dbname=","local"])
	except getopt.GetoptError,err:
		print str(err)
		usage()
		sys.exit(2)
	
	#defaults
	local = False
	host = "omegle.com"
	sql = {"standard":
                   """SELECT message FROM omegle_messages 
                       WHERE LENGTH(message) < 35
                         AND NOT ( message ILIKE '%www.%'
                             OR message ILIKE '%http%'
                             OR message ILIKE '%@%.%')
                     ;""",
	       "offensive":
                   """SELECT message FROM omegle_messages 
                       WHERE ( message ILIKE '%sex%' 
                            OR message ILIKE '%boob%' 
                            OR message ILIKE '%horny %'
                            OR message ILIKE '%pussy %'
                            OR message ILIKE '%ass %'
                            OR message ILIKE '%naked%'
                            OR message ILIKE '%fuck%'
                            OR message ILIKE '%pants %'
                            OR message ILIKE '%penis%'
                            OR LENGTH(message) < 7 AND CAST(RANDOM()*10 as integer)=1)
                        AND LENGTH(message) < 35
                        AND NOT ( message ILIKE '%www.%'
                            OR message ILIKE '%http%'
                            OR message ILIKE '%@%.%');""",
	       "offensive-large":
                   """SELECT message FROM omegle_messages WHERE from_ident in (
              SELECT from_ident FROM omegle_messages 
                       WHERE ( message ILIKE '%sex%' 
                            OR message ILIKE '%boob%' 
                            OR message ILIKE '%horny %'
                            OR message ILIKE '%pussy %'
                            OR message ILIKE '%ass %'
                            OR message ILIKE '%naked%'
                            OR message ILIKE '%fuck%'
                            OR message ILIKE '%pants %'
                            OR message ILIKE '%penis%'
                            OR LENGTH(message) < 7 AND CAST(RANDOM()*10 as integer)=1)
                        AND LENGTH(message) < 35
                        AND NOT ( message ILIKE '%www.%'
                            OR message ILIKE '%http%'
                            OR message ILIKE '%@%.%')    );""",
		"serious":
                    """SELECT message
                         FROM omegle_messages om1
                        WHERE (  SELECT COUNT(*) 
                                   FROM omegle_messages om2 
                                  WHERE ( om1.from_ident = om2.from_ident 
                                       OR om1.to_ident = om2.from_ident) 
                                    AND (om1.send_time - om2.send_time > interval '-2 hours' 
                                     AND om1.send_time - om2.send_time < interval '2 hours')) > 25
                          AND LENGTH(message) < 30
                          AND NOT ( message ILIKE '%www.%'
                            OR message ILIKE '%http%'
                            OR message ILIKE '%@%.%');""",
	       }
	sqlKey = "standard"
	dbname = "omegle"

	for o, a in opts:
		if o in ('-h', '--help'):
			usage()
			sys.exit(0)
		elif o in ('-d', '--dbname'):
			dbname = a
		elif o in ('-l', '--local'):
			local = True
		elif o == "--host":
			host = a
		elif o in ("-p", "--profile"):
			if sql.has_key(a):
				sqlKey = a
				print sql[a]
			else:
				print "Profile %s does not exist, create it!" % a
				sys.exit(0)

	mh_python.initbrain()

	conn = pyPgSQL.PgSQL.connect(database=dbname)
	cur = conn.cursor()

	cur.execute(sql[sqlKey])
	messages = cur.fetchall()
	c=0
	for message in messages:
		c+=1
		if c%20==0:
			print "%s%s/%s" % ("\033[2K\033[E",c,len(messages)),
		#XXX pass massage[0] to mh and end with a fucked up python
		mh_python.learn("%s " % (message[0]))
		mh_python.learn("%s " % (message[0]))

	print "%s%s/%s" % ("\033[2K\033[E",len(messages),len(messages))
	cur.close()
	conn.close()
	del messages

	logging.basicConfig(level=logging.DEBUG)
	if local:
		print "CTRL-C\n>>> ",
		while True:
			x=sys.stdin.readline().strip()
			print "<<< %s\n>>> " % mh_python.doreply(x),
	else:
		print "press ctrl-c to abort"
		event = Event()
		bot=MegahalBot(event,"A",host=host,color=31)

		bot.start()

		try:
		       while True:
			       event.wait(0.5)
			       if event.isSet():
				       print "disconnect_event set"
				       break
		except KeyboardInterrupt:
			print "CTRL-C pressed, exiting"

		if bot.is_connected: bot.disconnect()