尝试用 python (3.9.2) 制作一个基本的 irc 机器人,它可以在调用时响应特定的命令。例如,当响应包含空格或空格时,机器人仅显示第一个单词;
me > @hello
bot > hi
me > @how is the weather?
bot > the
本来应该说,the weather seems nice today
这是代码
import sys
import time
import socket
import string
server_address="irc.libera.chat"
server_port = 6667
botnick="lamebot"
channel_name="##megadouched"
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((server_address,server_port))
irc.setblocking(False)
time.sleep(1)
irc.send(bytes("USER "+botnick+" "+botnick+" "+botnick+" bot has joined the chat\r\n", "UTF-8"))
time.sleep(1)
irc.send(bytes("NICK "+botnick+"\n", "UTF-8"))
time.sleep(1)
irc.send(bytes("JOIN "+channel_name+"\n", "UTF-8"))
irc_privmsg = 'b"PRIVMSG "+channel_name+" Hello\r\n"'
while True:
try:
text = irc.recv(4096)
except Exception:
pass
if text.find(bytes(":@hi", "UTF-8"))!=-1:
irc.sendall(bytes("PRIVMSG "+channel_name+" Hello\r\n", "UTF-8"))
text=b""
elif text.find(bytes(":@how is the weather?", "UTF-8"))!=-1:
irc.sendall(bytes("PRIVMSG "+channel_name+" the weather today seems nice\r\n", "UTF-8"))
text=b""
input()
答案1
IRC 协议将消息分成一个命令和多个参数,并用空格分隔。为了允许尾部参数本身包含空格,协议允许在其前面加上冒号作为前缀。就像这个例子中的RFC 2812:
PRIVMSG Angel :yes I'm receiving it !
; Command to send a message to Angel.
现在我发现,RFC 中实际上并没有详细说明这一点,而是隐藏在 2.3.1 消息的 BNF 语法中:
params = *14( 中间空格 ) [ 空格 ":" 尾随 ] =/ 14( 空格 中间 ) [ 空格 [ ":" ] 尾随 ] 中间 = nospcrlfcl *( ":" / nospcrlfcl ) 尾随 = *( ":" / " " / nospcrlfcl )
语法元素可以出现在冒号之后trailing
的末尾,并且与 不同的是,它也允许空格。params
middle
(是的,这意味着像这样的消息PRIVMSG someone the weather today seems nice
具有的参数多于PRIVMSG
命令所采用的参数,但无论出于何种原因,这都不会被视为错误。可能只是简单的实现,或者是波斯特尔定律导致的愚蠢。)