change socket reading method

main
nebula 2024-12-15 15:32:00 -06:00
parent 20f97a4e8a
commit 98efc6a871
1 changed files with 40 additions and 36 deletions

76
main.py
View File

@ -286,41 +286,45 @@ class IRCBot():
def ping_pong(self): def ping_pong(self):
while True: while True:
sleep(2) char = self.s.recv(1).decode("UTF-8")
response = self.s.recv(8192).decode("UTF-8") if not char:
if not response:
exit(f"{self.nick}: no response from IRC server") exit(f"{self.nick}: no response from IRC server")
split = response.split("\r\n") line = ""
for line in split: while char:
line = line.strip() if char == "\n":
if line.startswith("PING"): break
pong = "PONG " + line[5:] elif char != "\r":
self.sendline(pong) line += char
continue char = self.s.recv(1).decode("UTF-8")
channel_search = channel_re.search(line) line = line.strip()
if not channel_search: if line.startswith("PING"):
continue pong = "PONG " + line[5:]
name_search = name_re.search(line) self.sendline(pong)
channel = channel_search.group(1) continue
if name_search: channel_search = channel_re.search(line)
name = name_search.group(1) if not channel_search:
else: continue
name = None channel = channel_search.group(1)
if name and not channel.startswith("#"): name_search = name_re.search(line)
channel = name if name_search:
try: name = name_search.group(1)
message_body = line[line.index(" :") + 2:] else:
except Exception as e: name = None
print(e) if name and not channel.startswith("#"):
message_body = "" channel = name
for command, callback in self.commands: try:
if line.lower().endswith(command): message_body = line[line.index(" :") + 2:]
result = callback(channel, name) except Exception as e:
if result: print(e)
self.send(channel, result) message_body = ""
if message_body: for command, callback in self.commands:
for callback in self.searchers: if line.lower().endswith(command):
callback(message_body) result = callback(channel, name)
if result:
self.send(channel, result)
if message_body:
for callback in self.searchers:
callback(message_body)
def run(): def run():
bot = IRCBot( bot = IRCBot(
@ -329,7 +333,7 @@ def run():
helptext, helptext,
[ # endswith commands [ # endswith commands
("!help", post_help), ("!help", post_help),
("!rollcall", post_help) ("!rollcall", post_help),
("!trivia", post_question), ("!trivia", post_question),
("!aitrivia", post_ai_question), ("!aitrivia", post_ai_question),
("!trscores", post_top_scores), ("!trscores", post_top_scores),
@ -346,7 +350,7 @@ def run():
) )
while True: while True:
sleep(2) sleep(0.5)
bot.ping_pong() bot.ping_pong()
if __name__ == "__main__": if __name__ == "__main__":