首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >扭曲连接Bot类的参考函数

扭曲连接Bot类的参考函数
EN

Stack Overflow用户
提问于 2015-12-18 05:53:02
回答 1查看 99关注 0票数 0

我目前正在开发一个Twitch.tv聊天和慢速机器人(在github上可以找到完整的代码:https://github.com/DarkElement75/tecsbot;可能无法完全更新以匹配我描述的问题),在这样做时,我需要有许多不同的Twisted TCP连接到不同的通道。我(因为抽搐语系统的工作方式)有一个用来发送/接收耳语的连接,并且需要任何连接到任何通道的能力,可以通过TwitchWhisperBot的write()函数引用这个低语连接并在这个连接上发送数据。但是,我还没有找到允许当前全局函数引用这个write()函数的方法。我现在要说的是:

代码语言:javascript
复制
#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"))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-21 05:25:12

这里最简单的解决方案是使用Singleton模式,因为您保证在任何给定的时间都只能拥有每种类型的单个连接。就个人而言,使用Twisted,我认为最简单的解决方案是使用反应堆来存储您的实例(因为反应堆本身是一个单例)。

因此,您想要做的是,在TwitchWhisperBot内部,在登录时:

代码语言:javascript
复制
def signedOn(self):
    reactor.whisper_instance = self

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

代码语言:javascript
复制
reactor.whisper_instance = self

看在理智的份上,你还应该检查它是否设置好了:

代码语言:javascript
复制
if getattr(reactor, 'whisper_instance'):
    reactor.whisper_instance.write("test_user", "message")
else:
    logging.warning("whisper instance not set")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34349280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档