/ bin / darkirc / script / bots / irc.py
irc.py
 1  import socket
 2  
 3  class IRC:
 4      irc = socket.socket()
 5    
 6      def __init__(self):
 7          # Define the socket
 8          self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 9   
10      def send(self, channel, msg):
11          # Transfer data
12          self.irc.send(bytes("PRIVMSG " + channel + " :" + msg + "\n", "UTF-8"))
13   
14      def connect(self, server, port, channels, botnick):
15          # Connect to the server
16          print("Connecting to: " + server)
17          self.irc.connect((server, port))
18  
19          # Perform user authentication
20          self.irc.send(bytes("CAP LS 302\n", "UTF-8"))
21          self.irc.send(bytes("CAP REQ :no-history\n", "UTF-8"))
22          self.irc.send(bytes("NICK " + botnick + "\n", "UTF-8"))
23          self.irc.send(bytes("USER " + botnick + " 0 * :" + botnick + "\n", "UTF-8"))
24          self.irc.send(bytes("CAP END\n", "UTF-8"))
25  
26          # join the channel
27          for chan in channels:
28              self.irc.send(bytes("JOIN " + chan + "\n", "UTF-8"))
29  
30      def disconnect(self, server, port):
31          # Disonnect from the server and gracefully shutdown and close socket
32          print("Disonnecting from: " + server + ":" + str(port))
33          # Send QUIT command to IRC server
34          self.irc.send(bytes("QUIT\n", "UTF-8"))
35          self.irc.shutdown(socket.SHUT_RDWR)
36          self.irc.close()
37          
38   
39      def get_response(self):
40          # Get the response
41          resp = self.irc.recv(2040).decode("UTF-8")
42          msg = resp.split(':')[-1]
43   
44          if resp.find('PING') != -1:                      
45              self.irc.send(bytes('PONG ' + msg + '\r\n', "UTF-8"))
46              return
47   
48          return resp.strip()