0

The script below will display metar information when users type !metar (airport code). However, I'm having two issues:

1) How to handle when the user types !metar without the code. I'd like to display: "Example: !metar ksfo". The if statement below doesn't do this.

2) How to handle when the user types an incorrect code. urllib will open the .txt file but it displays an error from the html link. I tried a similar if statement but that doesn't work either.

    import socket
from urllib import urlopen

def metar(airport):
    airport = airport.upper()
    for metar in urlopen('http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT' %airport):
        metar = metar.decode("utf-8")
        if "%s" %airport in metar:
            irc.send('PRIVMSG '+ channel +' :%s' %metar)
        #else: 
        #   irc.send('PRIVMSG '+ channel +' :Incorrect airport code.')

network = 'irc.freenode.net'
port = 6667
nick = 'savvis_bot'
channel = '#savvis_bot'

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Connecting to server...", network
irc.connect((network, port))
print irc.recv(4096)
irc.send("USER "+ nick +" "+ nick +" "+ nick +" :Savvis\n")
irc.send("NICK " + nick + "\n")
irc.send("JOIN " + channel + "\n")

while True:
    data = irc.recv(4096)
    print data
    if data.find('PING') != -1:
        irc.send('PING ' + data.split() [1] + '\r\n')
    if data.find(':!metar') != -1:
        airport_command = data.split(':!metar')
        airport = airport_command[1].strip()
        if airport == '':
            irc.send('PRIVMSG '+ channel +' :Example: !metar KSFO')
        else:
            metar(airport)
Savvis
  • 53
  • 1
  • 3
  • 7
  • [ircbot example with comments](http://www.habnabit.org/twistedex.html) from [How do i program a simple IRC bot in python?](http://stackoverflow.com/questions/2968408/how-do-i-program-a-simple-irc-bot-in-python) – jfs Oct 25 '12 at 11:44

1 Answers1

1

1) Try changing the if/else condition from:

if "%s" %airport in metar:

to

if airport in metar:

2) Wrap urlopen into try/except clause and send an error on exceptions, possibly distinguishing between connection timeouts and stuff like that vs incorrect airport code.

Then, I'm not sure whether you were asking questions about this bot before, but I think I saw a similar question tonight.

IRC is a line-based protocol. Doing irc.recv(4096) is not guaranteed to fetch what you want. It can be a middle of line, can be end of line, can be end of one line and beginning of another, etc. You need to use readline()-based approach, rather than byte-buffer.

favoretti
  • 29,299
  • 4
  • 48
  • 61