Twisted Connection Bot 参考函数 Class

Reference function of Twisted Connection Bot Class

我目前正在开发 Twitch.tv 聊天和审核机器人(完整代码可以在 github 此处找到:https://github.com/DarkElement75/tecsbot; might not be fully updated to match the problem I describe), and in doing this I need to have many different Twisted TCP connections to various channels. I have (because of the way Twitch's Whisper system 有效)一个用于发送/接收私语的连接,并且需要任何连接到任何通道的能力可以通过 TwitchWhisperBot 的 write() 函数引用此耳语连接并在此连接上发送数据。但是,我还没有找到一种方法允许我当前的全局函数引用这个 write() 函数。这是我现在拥有的:

#global functions
def send_whisper(self, user, msg):
    whisper_str = "/w %s %s" % (user, msg)
    print dir(whisper_bot)
    print dir(whisper_bot.transport)
    whisper_bot.write("asdf")

def whisper(self, user, msg):
    '''global whisper_user, whisper_msg
    if "/mods" in msg:
        thread.start_new_thread(get_whisper_mods_msg, (self, user, msg))
    else:
        whisper_user = user
        whisper_msg = msg'''
    if "/mods" in msg:
        thread.start_new_thread(get_whisper_mods_msg, (self, user, msg))
    else:
        send_whisper(self, user, msg)
#Example usage of these (inside a channel connection):
send_str = "Usage: !permit add <user> message/time/<time> <message count/time duration/time unit>/permanent" 
whisper(self, user, send_str)

#Whisper classes
class TwitchWhisperBot(irc.IRCClient, object):
    def write(self, msg):
        self.msg(self.channel, msg.encode("utf-8"))
        logging.info("{}: {}".format(self.nickname, msg))

class WhisperBotFactory(protocol.ClientFactory, object):
    wait_time = 1

    def __init__(self, channel):
        global whisper_bot

        self.channel = channel
        whisper_bot = TwitchWhisperBot(self.channel)

    def buildProtocol(self, addr):
        return TwitchWhisperBot(self.channel)

    def clientConnectionLost(self, connector, reason):
        # Reconnect when disconnected
        logging.error("Lost connection, reconnecting")
        self.protocol = TwitchWhisperBot
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        # Keep retrying when connection fails
        msg = "Could not connect, retrying in {}s"
        logging.warning(msg.format(self.wait_time))
        time.sleep(self.wait_time)
        self.wait_time = min(512, self.wait_time * 2)
        connector.connect()
#Execution begins here:
#main whisper bot where other threads with processes will be started
#sets variables for connection to twitch chat

whisper_channel = '#_tecsbot_1444071429976'
whisper_channel_parsed = whisper_channel.replace("#", "")

server_json = get_json_servers()
server_arr = (server_json["servers"][0]).split(":")
server = server_arr[0]
port = int(server_arr[1])

#try:
# we are using this to make more connections, better than threading
# Make logging format prettier
logging.basicConfig(format="[%(asctime)s] %(message)s",
                    datefmt="%H:%M:%S",
                    level=logging.INFO)

# Connect to Twitch IRC server, make more instances for more connections
#Whisper connection
whisper_bot = ''
reactor.connectTCP(server, port, WhisperBotFactory(whisper_channel))

#Channel connections
reactor.connectTCP('irc.twitch.tv', 6667, BotFactory("#darkelement75"))

此处最简单的解决方案是使用单例模式,因为可以保证在任何给定时间每种类型只有一个连接。就个人而言,对于 Twisted,我认为最简单的解决方案是使用 reactor 来存储您的实例(因为 reactor 本身是一个单例)。

那么您要做的是,在 TwitchWhisperBot 内,登录时:

def signedOn(self):
    reactor.whisper_instance = self

然后,您可以在代码的其他任何地方访问该实例:

reactor.whisper_instance = self

为了理智起见,您还应该检查它是否已设置:

if getattr(reactor, 'whisper_instance'):
    reactor.whisper_instance.write("test_user", "message")
else:
    logging.warning("whisper instance not set")