原文: https://pythonspot.com/building-an-irc-bot/

IRC(互联网中继聊天)的大量(ro)机器人。 那么,如何仅仅为了好玩而开始在 Python 中构建和构建一个?

您将需要一个与 IRC 服务器连接并像传统 IRC 客户端一样运行的程序。IRC 服务器从不要求进行任何复杂的人工验证,例如解决验证码,这就是为什么我们可以简单地使用脚本进行连接的原因。该脚本本身将使用网络套接字,一个库,该库通常用于以多种编程语言(包括 Python 和 C / C++)提供网络交互。

IRC 和 Python

要与 IRC 服务器通信,您需要使用 IRC 协议。 IRC 协议具有不同的消息,例如 PRIVMSG,USER,NICK 和 JOIN。 如果您好奇,可以阅读整个协议。 但是遵循本教程可能会更简单;仅需执行几个步骤即可完成身份验证:

IRC 协议是 IP 协议之上的一层。 要创建套接字,请使用以下命令:

  1. irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

socket.AF_INET通知库使用网络协议 IPv4。第二个参数告诉库使用流套接字,该套接字通常在 TCP 协议上实现。(IRC 通过 TCP/IP 进行工作)。 然后,我们必须使用以下命令对服务器进行身份验证:

  1. USER botname botname botname: phrase
  2. NICK botname
  3. JOIN #channel

有时IDENT命令也是必要的。 总结一下,我们得到了这个类(另存为irc.py):

  1. import socket
  2. import sys
  3. class IRC:
  4. irc = socket.socket()
  5. def __init__(self):
  6. self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  7. def send(self, chan, msg):
  8. self.irc.send("PRIVMSG " + chan + " " + msg + "n")
  9. def connect(self, server, channel, botnick):
  10. #defines the socket
  11. print "connecting to:"+server
  12. self.irc.connect((server, 6667)) #connects to the server
  13. self.irc.send("USER " + botnick + " " + botnick +" " + botnick + " :This is a fun bot!n") #user authentication
  14. self.irc.send("NICK " + botnick + "n")
  15. self.irc.send("JOIN " + channel + "n") #join the chan
  16. def get_text(self):
  17. text=self.irc.recv(2040) #receive the text
  18. if text.find('PING') != -1:
  19. self.irc.send('PONG ' + text.split() [1] + 'rn')
  20. return text

现在我们有了网络连接类,我们可以将其用作实例。 为了说明的目的,我们将使我们的(机器人)机器人保持简单。 如果漫游器在其驻留的通道中收到消息"hello",则它将回复"Hello!"

  1. from irc import *
  2. import os
  3. import random
  4. channel = "#testit"
  5. server = "irc.freenode.net"
  6. nickname = "reddity"
  7. irc = IRC()
  8. irc.connect(server, channel, nickname)
  9. while 1:
  10. text = irc.get_text()
  11. print text
  12. if "PRIVMSG" in text and channel in text and "hello" in text:
  13. irc.send(channel, "Hello!")

将其另存为bot.py并使用python bot.py运行。使用传统的 irc 客户端(mirc,hexchat,irsii)连接到该频道,并观察实验是否成功! 现在,您可以使用可以想象的任何出色功能对其进行扩展。