一部のサーバーでは、実際に何かを行う前に、PONG で PING に応答する必要があります。
ircSend('NICK ' + nick + '\r\n')
ircSend('USER john_bot john_bot bla :john_bot\r\n')
data = ircRecv() # explained later
if data.find('PING') != -1:
ircSend('PONG ' + data.split()[1] + '\r\n')
ircSend('JOIN :' + chan + '\r\n')
ircSend('PRIVMSG ' + chan + ' :Hello.\r\n')
あなたは本当にこれを必要としません
a=irc.recv (4096)
print a
IRC サーバーが一度に複数の行を送信することがあります (MOTD や NAMES など)。合計バイト数が 4096 を超えない限り、これで適切に処理されます (一部の行は 2 行に分割されます)。
data = irc.recv(4096)
for line in data.split('\r\n'):
# process the line
行が半分になることが問題である場合 (PING が発生した場合のように、まれに発生する可能性があります)、一度に 1 行を受信し、残りの文字をソケットのバッファーに残すことができます。ただし、これは少し効率が悪いかもしれません (私はテストしていないので、まったく問題にならないかもしれません)。
def ircRecv():
line = ''
while 1: # same as while True:
character = irc.recv(1)
if character == '\n':
break # exit the loop
elif character != '\r':
line += character
print line
return line
IRC RFC の 8 ページから:
<message> ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
<prefix> ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
<command> ::= <letter> { <letter> } | <number> <number> <number>
<SPACE> ::= ' ' { ' ' }
<params> ::= <SPACE> [ ':' <trailing> | <middle> <params> ]
<middle> ::= <Any *non-empty* sequence of octets not including SPACE
or NUL or CR or LF, the first of which may not be ':'>
<trailing> ::= <Any, possibly *empty*, sequence of octets not including
NUL or CR or LF>
<crlf> ::= CR LF
これは、次のようにいつでもメッセージの送信者を簡単かつ確実に取得できることを意味します。
# put this inside the main loop
# this will throw an IndexError when the connection is closed,
# an empty line does not contain any spaces
line = ircRecv()
if line.split()[0].find('!') != -1:
# the first character must be a colon because <command> can't include
# an exclamation mark
someOneElsesNick = line[1:line.find('!')]
command = line.split()[1]
誰かが挨拶したら答える!
if command == 'PRIVMSG':
destination = line.split()[2] # channel or bot's nick
# <trailing>, in this case, the message
message = line[line[1:].find(':')+2 : ] # everything after the 2nd colon
# we add one since we don't want include the <trailing> colon in
# the message and an other one because line[1:].find() is one smaller
# number than line.find() would be
# if we receive a private message, we have to respond to the sender,
# not to ourself
if destination == nick:
destination = someOneElsesNick
if message.startswith('hi!'):
ircSend('PRIVMSG ' + destination + ' :Hi, '
+ someOneElsesNick + '!\r\n')
詳細については、IRC RFC を確認してください: http://www.ietf.org/rfc/rfc1459.txt (特にセクション 2.3.1 と 4)。IRC プロトコルを扱いたくない場合は、Twisted を使用してください:) http://twistedmatrix.com/trac/