2013-06-24 39 views
0

我正在做一个bot来将IRC和DC(直接连接)连接在一起。我一直在使用C++中的一个现有实现,但它没有包含我们之后的所有功能。python中的回调函数和事件

我正在使用一个IRC库python这是真正好编码。我可以为各种IRC事件(特别是接收公共消息)注册一些回调处理程序。这个回调函数能够从IRC库中的线程引用在主python执行中创建的对象。

这里是我的回调:

def on_connect(connection, event): 
    connection.join(ircSettings['channel']) 

def on_disconnect(connection, event): 
    sys.exit() 

def on_pubmsg(connection, event): 
    hubClient.sendMessage(event.source.split('!')[0] + ': ' + event.arguments[0]) 

这里就是我如何设置它们:

# Create the IRC client 
ircClient = irc.client.IRC() 
try: 
    ircConnection = ircClient.server().connect(ircSettings['server'], ircSettin$ 
except irc.client.ServerConnectionError, x: 
    print x 
    sys.exit() 

# Set the IRC event handlers 
ircConnection.add_global_handler("welcome", on_connect) 
ircConnection.add_global_handler("pubmsg", on_pubmsg) 
ircConnection.add_global_handler("disconnect", on_disconnect) 

我真的很喜欢这个解决方案,因为它使一个非常整洁的代码(尤其是在这个例子中) 。但是,我不知道如何修改我的DC库来生成这些事件。

感兴趣的主要点是回调的引用hubClient,这是在主要的Python程序创建的,像这样的能力:

# Create the DC client 
hubClient = DC.DirectConnect(dcSettings) 
hubClient.connect(dcSettings['hub']) 

最初,我通过一个函数指针,以我的DC库运行时收到一条消息:

def messageHandler(nick, msg): 
    if nick is not ircSettings['nick']: 
     ircConnection.privmsg(ircSettings['channel'], nick + ': ' + msg) 

dcSettings = { 
    'nick': 'dans_bot', 
    'sharesize': 10*1024**3, # 10GB 
    'ip': '0.0.0.0', # XXX: This might not matter, but needed for library 
    'hub': ('192.168.1.129', 411), 
    'handler': messageHandler 
} 

但我得到的错误:

NameError: global name 'ircConnection' is not defined 

如何设置我的DC客户端以我仍然可以引用这些本地(到主执行)对象的方式创建回调?

编辑:我添加了'ircConnection'声明。

回答

1

我想ircConnection是第三方模块。并且该模块的简单导入可以解决此错误:global name ircConnection is not defined。在你的主模块中试试import ircConnection

+0

我编辑了我的帖子以显示如何声明ircConnection。 – dantheman

0

你的代码中唯一的问题是ircConnection的引用是第一次出现在try-except块内,如果失败,那么这个var将是None。在尝试之前只写ircConnection = None

# Create the IRC client 
ircClient = irc.client.IRC() 
ircConnection = None 
try: 
    ircConnection = ircClient.server().connect(ircSettings['server'], ircSettin$ 
except irc.client.ServerConnectionError, x: 
    print x 
    sys.exit() 

# Set the IRC event handlers 
ircConnection.add_global_handler("welcome", on_connect) 
ircConnection.add_global_handler("pubmsg", on_pubmsg) 
ircConnection.add_global_handler("disconnect", on_disconnect)