summary refs log tree commit diff
path: root/IRC.py
blob: 430bbf03a70663ee4037706d11cbff3083c07ee8 (plain)
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

import socket
import sys
import time
class IRCBadMessage(Exception):
    pass

def parsemsg(s):
    """Breaks a message from an IRC server into its prefix, command, and arguments.
    """
    prefix = ''
    trailing = []
    if not s:
       raise IRCBadMessage("Empty line.")
    if s[0] == ':':
        prefix, s = s[1:].split(' ', 1)
    if s.find(' :') != -1:
        s, trailing = s.split(' :', 1)
        args = s.split()
        args.append(trailing)
    else:
        args = s.split()
    command = args.pop(0)
    return prefix, command, args

LINEEND = '\r\n'

class IRCBot:

    irc = None

    def __init__(self, sock):
        # Define the socket
        self.irc = sock

    def send_privmsg(self, channel, msg):
        # Transfer data
        self.irc.send(bytes("PRIVMSG " + channel + " :"  + msg + LINEEND, "UTF-8"))
    
    def send_quit(self, quitmsg):
        msg = f'QUIT :{quitmsg}' + LINEEND
        print(msg)
        self.irc.send(msg.encode('utf-8'))

    def send_action(self, action_msg):
        pass

    def connect(self, server, port, channel, botnick, botpass, botnickpass):
        # Connect to the server
        print("Connecting to: " + server)
        self.irc.connect((server, port))

        # Perform user authentication
        self.irc.send(bytes("USER " + botnick + " " + botnick +
                      " " + botnick + " :python" + LINEEND, "UTF-8"))
        self.irc.send(bytes("NICK " + botnick + LINEEND, "UTF-8"))
        self.irc.send(bytes("NICKSERV IDENTIFY " +
                      botnickpass + " " +  LINEEND, "UTF-8"))
        time.sleep(5)

        # join the channel
        self.irc.send(bytes("JOIN " + channel + LINEEND, "UTF-8"))

    def get_response(self):
        time.sleep(1)
        # Get the response
        resp = self.irc.recv(4096).decode("UTF-8")
        msg = parsemsg(resp)

        if msg[1] == 'PING':
            print('Sending pong')
            self.irc.send(
                bytes('PONG ' + LINEEND, "UTF-8"))

        return msg