如何用Python编写简单的IRC机器人?
我需要帮助写一个基本的IRC机器人,它只需要连接到一个频道。有没有人能给我解释一下?我已经成功连接到IRC服务器,但我还不能加入频道和登录。目前我写的代码是:
import sockethost = 'irc.freenode.org'
port = 6667
join_sock = socket.socket()
join_sock.connect((host, port))
<code here>
任何帮助都会非常感激。
5 个回答
19
我用这个作为主要的IRC代码:
import socket
import sys
server = "server" #settings
channel = "#channel"
botnick = "botname"
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket
print "connecting to:"+server
irc.connect((server, 6667)) #connects to the server
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!\n") #user authentication
irc.send("NICK "+ botnick +"\n") #sets nick
irc.send("PRIVMSG nickserv :iNOOPE\r\n") #auth
irc.send("JOIN "+ channel +"\n") #join the chan
while 1: #puts it in a loop
text=irc.recv(2040) #receive the text
print text #print text to console
if text.find('PING') != -1: #check if 'PING' is found
irc.send('PONG ' + text.split() [1] + '\r\n') #returnes 'PONG' back to the server (prevents pinging out!)
然后,你可以开始设置命令,比如:!hi <nick>
if text.find(':!hi') !=-1: #you can change !hi to whatever you want
t = text.split(':!hi') #you can change t and to :)
to = t[1].strip() #this code is for getting the first word after !hi
irc.send('PRIVMSG '+channel+' :Hello '+str(to)+'! \r\n')
注意,所有的irc.send
文本必须以PRIVMSG
或NOTICE
+ 频道/用户
开头,并且文本应该以:
开头!
55
要连接到一个IRC频道,你需要先向IRC服务器发送一些特定的命令,这些命令是IRC协议的一部分。
当你连接到服务器后,要等服务器把所有数据(比如欢迎信息等)发送完毕,然后你才能发送PASS命令。
PASS <some_secret_password>
接下来是NICK命令。
NICK <username>
然后你需要发送USER命令。
USER <username> <hostname> <servername> :<realname>
这两个命令都是必须的。
之后,你可能会收到服务器发来的PING消息,每当服务器发PING消息给你时,你都需要用PONG命令回复服务器。服务器在你发送NICK和USER命令之间也可能会要求你发送PONG。
PING :12345678
用PONG命令回复“PING”后面的内容,确保完全一样:
PONG :12345678
我认为PING后面的内容对每个服务器都是独特的,所以一定要用服务器发给你的那个值来回复。
现在你可以用JOIN命令加入一个频道:
JOIN <#channel>
现在你可以用PRIVMSG命令给频道和用户发送消息:
PRIVMSG <#channel>|<nick> :<message>
退出可以用
QUIT :<optional_quit_msg>
可以试试Telnet!从这里开始:
telnet irc.example.com 6667
想了解更多命令和选项,可以查看IRC RFC。
希望这些信息对你有帮助!
13
可能最简单的方法是参考twisted对IRC协议的实现。你可以看看这个链接:http://github.com/brosner/bosnobot,从中获取一些灵感。