Python:无法连接到服务器

时间:2011-01-24 19:56:48

标签: python networking irc

我无法连接到将要打印的服务器

“连接到端口......”然后它会说“套接字超时。”

我的节目明天到期,让这个真的有用真好。

已编辑的代码:现在它只会使用连接端口.... 没有其他印刷品。

import socket, string, time, random, re, urllib2, cookielib, smtplib, os

class Pibot: #main class
        def __init__(self):  #basic information to allow for the rest of the program to work.
            self.server= 'irc.evilzone.org'
            self.port = 6667
            self.botname= 'pibot'
            self.chan= 'test'
            self.owner = 'Josh.H'
            self.nick = "bawt"
            self.irc = None
            self.data = ''

    def iConnect(self): #trys to connect to the server and allows the user to see if it failed to connect.
            print ("Connecting to ports...")
            print self.data
            time.sleep(3)
            try:
                    self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    self.irc.connect((self.server, self.port))

            except (socket.error, socket.herror, socket.gaierror):
                    print "Failed to connect to Ports"



    def iStart(self):
            #Not guaranteed to send all your data, iisn't checking the return values
            #however this function iStart is used to send the NICK of the bot and the USER to the server through particle data
            #it then auto joins the channel
            #in future development I'd like to get accuainted with Twisted or IRCutils as they allow it to be quiet powerful and less buggy

            self.irc.send('NICK %s\r\n' % self.nick)
            self.irc.send("USER %s %s bla :%s\r\n" % ("Ohlook", 'itsnotmy', 'Realname'))
            time.sleep(4)
            self.irc.send("JOIN #%s\r\n" % self.chan)
            self.data = self.irc.recv( 4096 ) 

    def MainLoop(self,iParse = 0): #MainLoop is used to make the commands executable ie !google !say etc;
            try:
                while True:
                    # This method sends a ping to the server and if it pings it will send a pong back
                    #in other clients they keep receiving till they have a complete line however mine does not as of right now
                    #The PING command is used to test the presence of an active client or
                    #server at the other end of the connection.  Servers send a PING
                    #message at regular intervals if no other activity detected coming
                    #from a connection.  If a connection fails to respond to a PING
                    #message within a set amount of time, that connection is closed. A
                    #PING message MAY be sent even if the connection is active.
                    #PONG message is a reply to PING message.  If parameter <server2> is
                    #given, this message will be forwarded to given target.  The <server>
                    #parameter is the name of the entity who has responded to PING message
                    #and generated this message.

                    self.data = self.irc.recv( 4096 )
                    if self.data.find ( 'PING' ) != -1:
                        self.irc.send(( "PONG %s \r\n" ) % (self.recv.split() [ 1 ])) #Possible overflow problem

                    if self.data.find( "!google" ) != -1:
                        #googles the search term and displays the first 5 results
                        #format = !google: <Search Term>
                        #One thing that I noticed is that it will print on a seperate line without the header
                        #In the next Update I would have fixed this.
                        fin = data.split(':')
                        if not fin:
                                irc.send("PRIVMSG #%s :syntax'^google :search term\r\n'" % chan)

                        else:
                            #In the next version to avoid overflow I will create another if statement and edit the search code
                            #However I am using what xgoogle has reccomended.
                                fin = fin[3].strip() 
                                gs = GoogleSearch(fin)
                                gs.results_per_page = 5
                                results = gs.get_results()
                                for result in results:
                                    irc.send("PRIVMSG #%s :%s\r\n" % (chan, result.url.encode("utf8")))

                    ###############################################################################################################################
                    #   No excpetion checking here, these functions can and will fail in time and in later versions will need to be edited.          
                    #   If hellboundhackers changes this code may break
                    #   This function takes a quote from the header of hellboundhackers
                    #   it first looks at the header of the USer agent then the header of the website (HBH) and reads it then prints
                    #   the quote when QUOTEM is recognized in the irc closes the connection to the wbesite and deletes the cookie
                    ###############################################################################################################################

                    if "QUOTEM" in self.data:
                        #Pulls a quote from HBH
                        cj = cookielib.CookieJar()
                        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
                        opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
                        opener.addheaders.append( ('Referer', 'http://www.hellboundhackers.org/index.php') )
                        resp = opener.open('http://www.hellboundhackers.org/index.php')
                        r = resp.read()
                        resp.close()
                        del cj, opener
                        da = re.findall("Enter; width:70%;'>(.*)",r)
                        self.irc.send("PRIVMSG #%s :%s\r\n" % (chan, da[0])) # Note Possible overflow

                    if "!whoareyou" in self.data:
                        #bot info allows users on IRC to see which commands are currently working
                        self.irc.send("PRIVMSG #%s :I am %s, I was created By:%s \r\n" % (self.chan, self.nick,self.owner))
                        self.irc.send("PRIVMSG #%s :I was written in Python 27, and edited with IDLE\r\n" % self.chan)
                        self.irc.send("PRIVMSG #%s :The Classes used are socket, string, time, re, urllib2, cookielib\r\n" % self.chan)
                        self.irc.send("PRIVMSG #%s :As well as some functions from various other sources(supybot,twisted,xgoogle)\r\n" % self.chan)
                        self.irc.send("PRIVMSG #%s :type ^commands for a list of things I can do\r\n" % self.chan)
            except (socket.error, socket.timeout):
                    print "Sockets timed out."

bot = Pibot()
bot.iConnect()
bot.MainLoop()

旁注:没有错误。 非常感激。我也是在学习,所以不要点燃我。 :(

EDIT2:我已解决了大部分问题,现在出现错误:

Traceback (most recent call last):
  File "L:\txtbot.py", line 119, in <module>
    bot.MainLoop()
  File "L:\txtbot.py", line 64, in MainLoop
    self.irc.send(( "PONG %s \r\n" ) % (self.recv.split() [ 1 ])) #Possible overflow problem
AttributeError: Pibot instance has no attribute 'recv'

3 个答案:

答案 0 :(得分:1)

您似乎永远不会将连接信息传递给套接字:

                self.irc = socket.socket()

我认为它应该是这样的:

                self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.irc.connect((self.server, self.port))

答案 1 :(得分:0)

iConnect中,您只是创建一个套接字,而不是将其连接到服务器。您需要使用socket.create_connection。 另外,将socket.error和socket.timeout混为一谈并不是一个好主意,因为它在调试时可能会产生误导。此外,您应该打印错误,而不仅仅是一般消息。它可以帮助你找出问题所在。

答案 2 :(得分:0)

您不能在任何地方致电iStart。如果我正确地记住了我的IRC,您需要先发送您的昵称信息,然后才会向您发送任何数据。