当用户输入!metar(机场代码)时,下面的脚本将显示metar信息。但是,我有两个问题:
1) 用户输入 !metar 时没有代码如何处理。我想显示:“示例:!metar ksfo”。下面的 if 语句不这样做。
2)当用户输入错误代码时如何处理。urllib 将打开 .txt 文件,但会显示来自 html 链接的错误。我尝试了类似的 if 语句,但这也不起作用。
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)