gpt4 book ai didi

python - Python编写的IRC机器人——加入 channel 功能

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:45 24 4
gpt4 key购买 nike

我正在尝试向我的 python IRC 机器人添加一个功能,当我在 IRC 上输入“join #channel-name”时,机器人将加入 channel 。

这是我的代码:

# IRC bot written by syrius
import socket

server = "irc.freenode.net" # IRC server
channel = "#syrius-test" # Channel
botnick = "syrius-bot" # Nickname of the bot
master = "syrius_" # Nickname of the bot's master
exitcode = "bye " + botnick #Text that we will use to make the bot quit

def ircwrite(message):
global ircsock
ircsock.send(str(message).encode('latin-1', 'ignore'))

def ping():
ircwrite("PONG :pingis\n")

def sendmsg(chan , msg):
ircwrite("PRIVMSG "+ chan +" :"+ msg +"\n")

def joinchan(channel):
ircsock.send(bytes("JOIN "+ channel + "\n"))

def join():
ircsock.send(bytes("JOIN %s"))

def hello():
ircwrite("PRIVMSG "+ channel +" :Hello!\n")

def quitting():
ircwrite("PRIVMSG "+ channel +" :Okay boss, leaving now.\n")


ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667))
ircwrite("USER "+ botnick +" "+ botnick +" "+ botnick +" :IRC bot coded by syrius.\n")
ircwrite("NICK "+ botnick +"\n")

joinchan(channel)

while 1:
ircmsg = ircsock.recv(2048).decode() # receive data from the server
ircmsg = ircmsg.strip('\n\r') # removing any unnecessary linebreaks.
print(ircmsg) # Here we print what's coming from the server
name = ircmsg.split('!',1)[0][1:] # We split out the name

if ircmsg.find(":Hello "+ botnick) != -1: # If we can find "Hello Mybot" it will call the function hello()
hello()

if ircmsg.find("PING :") != -1: # if the server pings us then we've got to respond!
ping()

if name.lower() == master.lower() and ircmsg.find(":quit " + botnick) != -1:
quitting()
ircsock.send(bytes("QUIT \n", "UTF-8"))

if name.lower() == master.lower() and ircmsg.find(":join %s") != -1:
join()

main()

当然,下面的代码是不正确的:

第23行:

def join():
ircsock.send(bytes("JOIN %s"))

第 56 行:

if name.lower() == master.lower() and ircmsg.find(":join %s") != -1:
join()

我想知道我应该在那里放什么,以便机器人可以加入 channel 。

任何帮助将不胜感激。

最佳答案

我发现这个解决方案存在一些问题,我的建议是您应该尝试使用 IRC 框架,例如 Pydle 或其他十亿个已经处理协议(protocol)的框架之一。

我看到的第一个问题是使用 latin-1 进行编码,通常您应该使用 utf-8,您也可以使用服务器在 RPL_ISUPPORT 回复的 CHARSET 中通告的任何内容,尽管这不再常见。沿着编码行,您还可以从 utf-8 解码 IRC 行,这样您就可以处理字符串而不是字节,只需在输出处重新编码即可。

下一个 IRC 问题将是您的行结束,IRC 消息应始终以 CR-LS(回车换行)结束,这将是\r\n 字符,而不仅仅是\n。

我想提到的最后一件事是你的字符串格式化,你应该使用 "JOIN {}".format(channel) 这是目前首选的字符串格式化方法,除非你使用 python 3.7 那么你将使用类似的 fstrings。

按照您现在尝试进行格式化的方式,您正在通过连接(例如“USER”+ channel )来完成它,但您也尝试通过%使用旧式字符串格式化s。如果您想使用 %s 格式,正确的方法是 "JOIN %s"% (channel),尽管现在使用 .format 和 fstrings 是首选方法。

关于python - Python编写的IRC机器人——加入 channel 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46184196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com