Python: IRC bot made with socket library returning error “Bad file descriptor”

I’ve been trying to write an IRC bot but when I try to send a command to it I have been receiving the error “Bad File Descriptor”, this is hard to troubleshoot and I cannot figure out why it’s happening, my code looks fine to me; does anyone know what might be wrong with it?

Below is the section of code that is causing me issues.

import socket, random

server = "irc.example.com"

def main(nummessages, channel, message)   
ircsock.connect((server, 6697))
            for i in range (nummessages):
                with open('cookies.txt', 'r') as info:
                        channel = f'#{channel}'
                        info = info.read().splitlines()
                        info = random.choice(info)
                        info = info.split(':')
                        token = info[1]
                        username = info[0]
                        nick = username
                        ircsock.send(bytes('NICK' + ' ' + username + 'n', 'UTF-8'))
                        ircsock.send(bytes('PASS' + ' oauth:' + token + 'n', 'UTF-8'))
                        ircsock.send(bytes('JOIN' + ' ' + channel + 'n', 'UTF-8'))
                        ircsock.send(bytes('PRIVMSG ' + channel + ' :' + message + 'rn', 'UTF-8'))
                        ircsock.send(bytes('PART' + ' ' + channel + 'n', 'UTF-8'))
                        ircsock.send(bytes('QUIT' + ':Bye' + 'n', 'UTF-8'))
                        ircsock.shutdown(socket.SHUT_RDWR)
                        ircsock.close()
test1 = 1
test2 = "test"
test3 = "test"

def main(test1, test2, test3)

Answer

“Bad file descriptor” can occur when you try to use a file/socket/etc that you already closed.

Your code doesn’t work at all, but I assume you broke it when you edited it down for the question. It is clear that you create a socket outside the loop, connect it outside the loop, then you repeat several times that you send some messages and close it.

So your program opens the socket, connects the socket, sends messages, closes the socket, sends more messages, closes the socket, sends more messages, closes the socket, … I hope it is obvious why you might be trying to use a closed socket.

If you want a new socket connection then you have to connect every time you want a new connection, and you also need a new socket. Each socket can only be used once – you can’t close it and then connect it again – you have to close it and make a new one.