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
|
import time
import threading
import irctk
import random
class Bot(threading.Thread):
host = 'tolkien.freenode.net'
port = 6697
ssl = True
password = None
def __init__(self, channel, threads, queue, name, rate, per):
threading.Thread.__init__(self)
self.threads = threads
self.queue = queue
self.name = name
self.channel = channel
# following for rate limiting:
self.rate = rate
self.per = per
self.last_check = time.time()
self.allowance = rate
self.log('starting up')
self.ready = False
self.client = irctk.Client(nickname=name, ident=name, realname=name, password=Bot.password)
self.client.delegate = self
self.client.connect(Bot.host, Bot.port, use_tls=Bot.ssl)
def irc_raw(self, client, line):
try:
self.log('IRC: ' + line)
except:
self.log('failed to log')
#pass
def log(self, line):
print "{} [{}] {}".format(time.strftime('%H:%M'), self.name, line)
def irc_registered(self, client):
self.log('joining ' + self.channel)
channel = client.add_channel(self.channel)
channel.join()
def irc_channel_join(self, client, nick, channel):
if str(nick) == str(client.get_nickname()):
self.log('im ready :)')
self.ready = True
def can_send(self):
current = time.time()
time_passed = current - self.last_check;
self.last_check = current
self.allowance += time_passed * (self.rate / self.per)
if self.allowance > self.rate:
self.allowance = self.rate
if self.allowance > 1.0:
self.allowance -= 1.0
return True
return False
def run(self):
self.log('run() called')
while True:
waiting = True
while waiting:
for thread in self.threads:
if not thread.ready:
waiting = True
break
else:
waiting = False
time.sleep(random.random())
# start flushing the queue
while self.can_send():
try:
line = self.queue.popleft()
self.client.send_line(
'PRIVMSG ' + self.channel + ' :' + line
)
time.sleep(0.25)
except IndexError:
# end of queue
self.log('done working')
self.client.quit('bye bye')
return
time.sleep(0.1)
|