More robust implementation.

This commit is contained in:
AZ Huang 2013-12-11 23:55:40 +08:00
parent b231bfa22b
commit dc2ecc946e

View File

@ -40,34 +40,41 @@ class SyncBot(Tox):
def connect(self): def connect(self):
print('connecting...') print('connecting...')
self.bootstrap_from_address(SERVER[0], 0, SERVER[1], SERVER[2]) self.bootstrap_from_address(SERVER[0], 1, SERVER[1], SERVER[2])
def ensure_exe(self, func, args):
count = 0
THRESHOLD = 10
while True:
try:
return func(*args)
except:
print func, count
assert count < THRESHOLD
count += 1
for i in range(10):
self.do()
sleep(0.02)
def loop(self): def loop(self):
checked = False checked = False
self.joined = False self.joined = False
try:
self.add_friend(GROUP_BOT, "")
except: pass
try: try:
while True: while True:
status = self.isconnected() status = self.isconnected()
if not checked and status: if not checked and status:
print('Connected to DHT.') print('Connected to DHT.')
checked = True checked = True
self.ensure_exe(self.add_friend, (GROUP_BOT, ""))
self.bid = self.get_friend_id(GROUP_BOT)
if checked and not status: if checked and not status:
print('Disconnected from DHT.') print('Disconnected from DHT.')
self.connect() self.connect()
checked = False checked = False
if not self.joined:
try:
tid = self.get_friend_id(GROUP_BOT)
self.send_message(tid, 'invite')
except: pass
readable, _, _ = select.select([self.irc], [], [], 0.01) readable, _, _ = select.select([self.irc], [], [], 0.01)
if readable: if readable:
@ -85,8 +92,9 @@ class SyncBot(Tox):
if rx.group(2) == '^syncbot': if rx.group(2) == '^syncbot':
self.irc.send('PRIVMSG %s :%s\r\n' % self.irc.send('PRIVMSG %s :%s\r\n' %
(CHANNEL, self.get_address())) (CHANNEL, self.get_address()))
else: elif self.tox_group_id != None:
self.send_group_msg(msg) self.ensure_exe(self.group_message_send,
(self.tox_group_id, msg))
l = line.rstrip().split() l = line.rstrip().split()
if l[0] == "PING": if l[0] == "PING":
@ -96,17 +104,10 @@ class SyncBot(Tox):
except KeyboardInterrupt: except KeyboardInterrupt:
self.save_to_file('data') self.save_to_file('data')
def send_group_msg(self, msg): def on_connection_status(self, friendId, status):
self.sent = msg if not self.joined and friendId == self.bid and status:
if self.tox_group_id != None: print('Groupbot online, trying to join group chat.')
sent = False self.ensure_exe(self.send_message, (tid, 'invite'))
while not sent:
try:
self.group_message_send(self.tox_group_id, msg)
sent = True
except:
self.do()
sleep(0.02)
def on_group_invite(self, friendid, pk): def on_group_invite(self, friendid, pk):
if not self.joined: if not self.joined: