forked from Breakthrough/humanitybot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsprbt.py
executable file
·228 lines (193 loc) · 8.91 KB
/
sprbt.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
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
226
227
228
#!/usr/bin/env python
#
# Humanitybot: A Cards-Against Humanity IRC Bot
# -----------------------------------------------------------
# [ https://github.com/Breakthrough/humanitybot ]
#
# Copyright (C) 2014 Brandon Castellano <www.bcastell.com>
# Copyright (c) 2013-2014, Matthew Ames <www.supermatt.net>
#
# Humanitybot is licensed under the BSD 2-Clause License; see the
# included LICENSE file or visit the following page for details:
# https://github.com/Breakthrough/humanitybot
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
import socket
import ssl
import sys
import re
import threading
import time
from datetime import datetime
from datetime import timedelta
import select
import humanitybot_config
import functions
class IRCConnector(threading.Thread):
def __init__ (self, server):
# TODO: Just replace the below with the server dict() directly.
self.host = server['host']
self.port = server['port']
self.channel = server['channel']
self.use_ssl = server['use_ssl']
self.hb_interval = server['heartbeat_interval']
self.hb_last = time.time()
self.delay_time = 0.1 # Time to wait in seconds between loop iterations if hb_interval > 0
self.admin_list = server['admin_list']
self.botname = server['nickname'] # IRC nickname
self.ns_pass = server['nickserv_password']
self.identity = "superbot"
self.realname = "superbot"
self.hostname = "supermatt.net"
self.allmessages = []
self.lastmessage = datetime.now()
self.pulsetime = 500
threading.Thread.__init__ ( self )
def output(self, message):
print("Server: %s\nMessage:%s\n" %(self.host, message))
def say(self, message):
#print "sending %s" % message
messagetosend = "PRIVMSG %s :%s\n" %(message["channel"], message["message"])
self.s.send(messagetosend)
def run (self):
try:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if self.use_ssl:
self.s = ssl.wrap_socket(self.s)
except:
print 'Failed to create socket'
sys.exit()
#remote_ip = socket.gethostbyname(self.host)
#self.output(remote_ip)
#self.s.connect((remote_ip, self.port))
self.s.connect((self.host, self.port))
# As per issue #3, need to leave socket asynchronous for sending hearbeats.
if not self.hb_interval > 0:
self.s.setblocking(1) # If no heartbeat, set synchronous.
message1 = "NICK %s\r\n" %self.botname
message2 = 'USER %s %s %s :%s\r\n' % (
self.identity, self.hostname, self.host, self.realname )
self.s.send(message1)
self.s.send(message2)
g = functions.Game(self)
while 1:
#
# If we need to send a heartbeat/PING... (see issue #3)
#
if self.hb_interval > 0:
# TODO: Only delay if no data/message recieved, then update HB timer.
time.sleep(self.delay_time)
if (time.time() - self.hb_last) > self.hb_interval:
self.hb_last = time.time()
self.s.send("PING %s\n" % self.host)
line = None
message = None
ready = select.select([self.s], [], [], 0.1)
if ready[0]:
line = self.s.recv(250)
print line
if line:
#self.output(line)
line.strip()
splitline = line.split() #" :")
if "PING" in splitline[0]:
pong = "PONG %s" % splitline[1]
self.output(pong)
self.s.send(pong)
##
## [Issue #4] Auto-send NickServ password when MOTD ends
## https://github.com/Breakthrough/humanitybot/issues/4
##
## Replaced with !ns trigger/command until issue resolved.
##
#if re.search(":End of /MOTD command.", line):
# joinchannel = "JOIN %s\n" %self.channel
# self.output(joinchannel)
# self.s.send("PRIVMSG nickserv :identify hum4n1ty\n")
# self.s.send(joinchannel)
# self.inchannel = True
if re.search("^:.* NICK .*$", line):
nicksplit = line.split()
oldnickstring = nicksplit[0][1:]
oldnicklist = oldnickstring.split("!")
oldnick = oldnicklist[0]
newnick = nicksplit[2][1:]
for player in g.players:
if player.username == oldnick:
player.username = newnick
if re.search("^:.* QUIT .*$", line) or re.search("^:.* PART .*$", line):
split1 = line.split()
split2 = split1[0].split("!")
username = split2[0][1:]
print username
message = g.part(username)
if message:
self.allmessages.append({"message": message, "channel": self.channel})
if re.search("PRIVMSG", line):
details = line.split()
user = details[0].split("!")
username = user[0][1:]
channel = details[2]
messagelist = details[3:]
message = " ".join(messagelist)[1:]
lower = message.lower()
if channel == self.botname:
channel = username
if username in self.admin_list:
if lower == "!kill":
print 'QUIT: %s' % username
self.s.send("QUIT :Bot quit\n")
elif lower == '!ns':
self.s.send("PRIVMSG nickserv :identify %s\n" % self.ns_pass)
elif lower == '!join':
joinchannel = "JOIN %s\n" % self.channel
self.output(joinchannel)
#self.s.send("PRIVMSG nickserv :identify hum4n1ty\n")
self.s.send(joinchannel)
self.inchannel = True
# elif lower == '$whois':
# joinchannel = "WHOIS supermatt\n"
# self.output(joinchannel)
# #self.s.send("PRIVMSG nickserv :identify hum4n1ty\n")
# self.s.send(joinchannel)
# self.inchannel = True
elif lower == "!test":
self.allmessages.append({"message": "test message", "channel": channel})
elif lower == "!reload":
try:
reload(functions)
self.allmessages.append({"message": "Reloaded functions", "channel": channel})
except:
self.allmessages.append({"message": "Unable to reload due to errors", "channel": channel})
else:
self.allmessages += functions.actioner(g, message, username, channel, self.channel)
if re.search(":Closing Link:", line):
sys.exit()
if g.inprogress or g.starttime:
self.allmessages += functions.gameLogic(g, message, username, channel, self.channel)
line = None
message = None
timestamp = datetime.now()
if len(self.allmessages) > 0:
newtime = self.lastmessage + timedelta(milliseconds = self.pulsetime)
if timestamp > newtime:
#print self.allmessages
currmess = self.allmessages.pop(0)
self.say(currmess)
self.lastmessage = timestamp
#print self.allmessages
for server in humanitybot_config.irc_connections:
IRCThread = IRCConnector(server)
IRCThread.start()
# Currently does not quit gracefully (issue #5), need to track thread status and !kill messages.
# TODO: Monitor threads (keep a list of refs/connections), restart if required
# (e.g. thread closes without seeing !kill).
# TODO: Watch for !kill command from any thread - need a message queue
# (e.g. graceful exit).