我正在尝试使用twisted.words.protocols.irc模块创建一个IRC机器人。
僵尸程序将解析来自通道的消息并解析它们以获取命令字符串。
除非我需要机器人通过发送whois命令来识别缺口,否则一切正常。在privmsg方法(我正在进行解析的方法)返回之前,不会处理whois回复。
例如:
from twisted.words.protocols import irc
class MyBot(irc.IRClient):
..........
def privmsg(self, user, channel, msg):
"""This method is called when the client recieves a message"""
if msg.startswith(':whois '):
nick = msg.split()[1]
self.whois(nick)
print(self.whoislist)
def irc_RPL_WHOISCHANNELS(self, prefix, params):
"""This method is called when the client recieves a reply for whois"""
self.whoislist[prefix] = params
有没有办法以某种方式让机器人在self.whois(缺口)之后等待回复?
也许使用线程(我没有任何经验)。
答案 0 :(得分:2)
Deferred
是Twisted中的核心概念,必须熟悉它才能使用Twisted。
基本上,你的whois检查功能应该返回Deferred
,当你收到whois-reply时会被触发。
答案 1 :(得分:-2)
我设法通过将所有处理程序方法作为线程运行,然后设置一个字段来解决这个问题 kirelagin的建议,在运行whois查询之前,并修改接收数据的方法 在收到回复时更改字段。它不是最优雅的解决方案,但它有效。
修改后的代码:
class MyBot(irc.IRClient):
..........
def privmsg(self, user, channel, msg):
"""This method is called when the client recieves a message"""
if msg.startswith(':whois '):
nick = msg.split()[1]
self.whois_status = 'REQUEST'
self.whois(nick)
while not self.whois_status == 'ACK':
sleep(1)
print(self.whoislist)
def irc_RPL_WHOISCHANNELS(self, prefix, params):
"""This method is called when the client recieves a reply for whois"""
self.whoislist[prefix] = params
def handleCommand(self, command, prefix, params):
"""Determine the function to call for the given command and call
it with the given arguments.
"""
method = getattr(self, "irc_%s" % command, None)
try:
# all handler methods are now threaded.
if method is not None:
thread.start_new_thread(method, (prefix, params))
else:
thread.start_new_thread(self.irc_unknown, (prefix, command, params))
except:
irc.log.deferr()
def irc_RPL_WHOISCHANNELS(self, prefix, params):
"""docstring for irc_RPL_WHOISCHANNELS"""
self.whoislist[prefix] = params
def irc_RPL_ENDOFWHOIS(self, prefix, params):
self.whois_status = 'ACK'