<commit_before>import plugins
import packetFactory
import data.clients
import data.players

from config import YAMLConfig
import config
from commands import Command

ircSettings = YAMLConfig("cfg/gchat-irc.config.yml",
                         {'enabled': False, 'nick': "PSO2IRCBot", 'server': '', 'port': 6667, 'channel': "", 'autoexec': []}, True)

ircMode = ircSettings.get_key('enabled')
ircNick = ircSettings.get_key('nick')
ircServer = (ircSettings.get_key('server'), ircSettings.get_key('port'))
ircChannel = ircSettings.get_key('channel')

chatPreferences = YAMLConfig("cfg/gchat.prefs.json")

if ircMode:
    from twisted.words.protocols import irc
    from twisted.internet import reactor, protocol

    ircBot = None

    # noinspection PyUnresolvedReferences
    class GChatIRC(irc.IRCClient):
        currentPid = 0
        userIds = {}

        def __init__(self):
            global ircNick
            self.nickname = ircNick

        def get_user_id(self, user):
            if user not in self.userIds:
                self.userIds[user] = self.currentPid
                self.currentPid += 1
            return self.userIds[user]

        def connectionMade(self):
            irc.IRCClient.connectionMade(self)
            print("[GlobalChat] IRC Connected!")

        def connectionLost(self, reason):
            irc.IRCClient.connectionLost(self, reason)
            print("[GlobalChat] IRC Connection lost!")

        def signedOn(self):
            global ircBot
            for command in ircSettings.get_key('autoexec'):
                self.sendLine(command)
                print("[IRC-AUTO] >>> %s" % command)
            self.join(self.factory.channel)
            print("[GlobalChat] Joined %s" % self.factory.channel)
            ircBot = self

        def privmsg(self, user, channel, msg):
            if channel == self.factory.channel:
                print("[GlobalChat] [IRC] <%s> %s" % (user.split("!")[0], msg))
                for client in data.clients.connectedClients.values():
                    if client.get_preferences()['globalChat'] and client.get_handle() is not None:
                        client.get_handle().send_crypto_packet(
                            packetFactory.TeamChatPacket(self.get_user_id(user.split("!")[0]),
                                                         "[GIRC] %s" % user.split("!")[0], msg.decode('utf-8')).build())
            else:
                print("[IRC] <%s> %s" % (user, msg))

        def noticed(self, user, channel, message):
            print("[IRC] [NOTICE] %s %s" % (user, message))

        def action(self, user, channel, msg):
            if channel == self.factory.channel:
                print("[GlobalChat] [IRC] * %s %s" % (user, msg))
                for client in data.clients.connectedClients.values():
                    if client.get_preferences()['globalChat'] and client.get_handle() is not None:
                        client.get_handle().send_crypto_packet(
                            packetFactory.TeamChatPacket(self.get_user_id(user.split("!")[0]),
                                                         "[GIRC] %s" % user.split("!")[0],
                                                         "* %s" % msg.decode('utf-8')).build())

        def send_global_message(self, ship, user, message):
            self.msg(self.factory.channel, "[G-%02i] <%s> %s" % (ship, user, message))

        def send_connected(self, ship, user):
            self.msg(self.factory.channel, "* %s connected to Ship %i" % (user, ship))

        def send_left(self, ship, user):
            self.msg(self.factory.channel, "* %s left Ship %i" % (user, ship))

    class GIRCFactory(protocol.ClientFactory):
        """docstring for ClassName"""

        def __init__(self, channel):
            self.channel = channel

        def buildProtocol(self, addr):
            p = GChatIRC()
            p.factory = self
            return p

        def clientConnectionLost(self, connector, reason):
            connector.connect()


@plugins.on_start_hook
def create_preferences():
    global chatPreferences
    global ircMode
    if ircMode:
        global ircChannel
        global ircServer
        bot = GIRCFactory(ircChannel)
        reactor.connectTCP(ircServer[0], ircServer[1], bot)


# noinspection PyUnresolvedReferences
@plugins.on_connection_hook
def check_config(user):
    global chatPreferences
    global ircMode
    if user.playerId in data.clients.connectedClients:
        client_preferences = data.clients.connectedClients[user.playerId].get_preferences()
        if 'globalChat' not in client_preferences:
            if chatPreferences.key_exists(user.playerId):
                client_preferences['globalChat'] = chatPreferences.get_key(user.playerId)['toggle']
            else:
                client_preferences['globalChat'] = True
                chatPreferences.set_key(user.playerId, {'toggle': True})
            if client_preferences['globalChat']:
                user.send_crypto_packet(packetFactory.SystemMessagePacket(
                    "[Proxy] {red}Global chat is enabled, use %sg <Message> to chat and %sgoff to disable it." % (config.globalConfig.get_key('commandPrefix'), config.globalConfig.get_key('commandPrefix')),
                    0x3).build())
                if ircMode:
                    global ircBot
                    ircBot.send_connected(data.players.playerList[user.playerId][0], data.clients.connectedClients[user.playerId].ship)
            else:
                user.send_crypto_packet(packetFactory.SystemMessagePacket(
                    "[Proxy] {red}Global chat is disabled, use %sgon to enable it and use %sg <Message> to chat." % (config.globalConfig.get_key('commandPrefix'), config.globalConfig.get_key('commandPrefix')),
                    0x3).build())
        data.clients.connectedClients[user.playerId].set_preferences(client_preferences)

@plugins.on_client_remove_hook
def notify_loss(user):
    global ircMode
    if ircMode and user.playerId in data.clients.connectedClients:
        global ircBot
        client_preferences = data.clients.connectedClients[user.playerId].get_preferences()
        if 'globalChat' not in client_preferences and client_preferences['globalChat']:
            ircBot.send_left(data.players.playerList[user.playerId][0], data.clients.connectedClients[user.playerId].ship)



@plugins.CommandHook("irc")
class IRCCommand(Command):
    def call_from_console(self):
        global ircMode
        global ircBot
        if ircMode and ircBot is not None:
            ircBot.sendLine(self.args.split(" ", 1)[1])
            return "[IRC] >>> %s" % self.args.split(" ", 1)[1]


@plugins.CommandHook("gon", "Enable global chat.")
class EnableGChat(Command):
    def call_from_client(self, client):
        global chatPreferences
        preferences = data.clients.connectedClients[client.playerId].get_preferences()
        preferences['globalChat'] = True
        client.send_crypto_packet(
            packetFactory.SystemMessagePacket("[GlobalChat] Global chat enabled for you.", 0x3).build())
        data.clients.connectedClients[client.playerId].set_preferences(preferences)
        new_preferences = chatPreferences.get_key(client.playerId)
        new_preferences['toggle'] = True
        chatPreferences.set_key(client.playerId, new_preferences)


@plugins.CommandHook("goff", "Disable global chat.")
class DisableGChat(Command):
    def call_from_client(self, client):<commit_msg>Whoops<commit_after>import plugins
import packetFactory
import data.clients
import data.players

from config import YAMLConfig
import config
from commands import Command

ircSettings = YAMLConfig("cfg/gchat-irc.config.yml",
                         {'enabled': False, 'nick': "PSO2IRCBot", 'server': '', 'port': 6667, 'channel': "", 'autoexec': []}, True)

ircMode = ircSettings.get_key('enabled')
ircNick = ircSettings.get_key('nick')
ircServer = (ircSettings.get_key('server'), ircSettings.get_key('port'))
ircChannel = ircSettings.get_key('channel')

chatPreferences = YAMLConfig("cfg/gchat.prefs.json")

if ircMode:
    from twisted.words.protocols import irc
    from twisted.internet import reactor, protocol

    ircBot = None

    # noinspection PyUnresolvedReferences
    class GChatIRC(irc.IRCClient):
        currentPid = 0
        userIds = {}

        def __init__(self):
            global ircNick
            self.nickname = ircNick

        def get_user_id(self, user):
            if user not in self.userIds:
                self.userIds[user] = self.currentPid
                self.currentPid += 1
            return self.userIds[user]

        def connectionMade(self):
            irc.IRCClient.connectionMade(self)
            print("[GlobalChat] IRC Connected!")

        def connectionLost(self, reason):
            irc.IRCClient.connectionLost(self, reason)
            print("[GlobalChat] IRC Connection lost!")

        def signedOn(self):
            global ircBot
            for command in ircSettings.get_key('autoexec'):
                self.sendLine(command)
                print("[IRC-AUTO] >>> %s" % command)
            self.join(self.factory.channel)
            print("[GlobalChat] Joined %s" % self.factory.channel)
            ircBot = self

        def privmsg(self, user, channel, msg):
            if channel == self.factory.channel:
                print("[GlobalChat] [IRC] <%s> %s" % (user.split("!")[0], msg))
                for client in data.clients.connectedClients.values():
                    if client.get_preferences()['globalChat'] and client.get_handle() is not None:
                        client.get_handle().send_crypto_packet(
                            packetFactory.TeamChatPacket(self.get_user_id(user.split("!")[0]),
                                                         "[GIRC] %s" % user.split("!")[0], msg.decode('utf-8')).build())
            else:
                print("[IRC] <%s> %s" % (user, msg))

        def noticed(self, user, channel, message):
            print("[IRC] [NOTICE] %s %s" % (user, message))

        def action(self, user, channel, msg):
            if channel == self.factory.channel:
                print("[GlobalChat] [IRC] * %s %s" % (user, msg))
                for client in data.clients.connectedClients.values():
                    if client.get_preferences()['globalChat'] and client.get_handle() is not None:
                        client.get_handle().send_crypto_packet(
                            packetFactory.TeamChatPacket(self.get_user_id(user.split("!")[0]),
                                                         "[GIRC] %s" % user.split("!")[0],
                                                         "* %s" % msg.decode('utf-8')).build())

        def send_global_message(self, ship, user, message):
            self.msg(self.factory.channel, "[G-%02i] <%s> %s" % (ship, user, message))

        def send_connected(self, ship, user):
            self.msg(self.factory.channel, "* %s connected to Ship %i" % (user, ship))

        def send_left(self, ship, user):
            self.msg(self.factory.channel, "* %s left Ship %i" % (user, ship))

    class GIRCFactory(protocol.ClientFactory):
        """docstring for ClassName"""

        def __init__(self, channel):
            self.channel = channel

        def buildProtocol(self, addr):
            p = GChatIRC()
            p.factory = self
            return p

        def clientConnectionLost(self, connector, reason):
            connector.connect()


@plugins.on_start_hook
def create_preferences():
    global chatPreferences
    global ircMode
    if ircMode:
        global ircChannel
        global ircServer
        bot = GIRCFactory(ircChannel)
        reactor.connectTCP(ircServer[0], ircServer[1], bot)


# noinspection PyUnresolvedReferences
@plugins.on_connection_hook
def check_config(user):
    global chatPreferences
    global ircMode
    if user.playerId in data.clients.connectedClients:
        client_preferences = data.clients.connectedClients[user.playerId].get_preferences()
        if 'globalChat' not in client_preferences:
            if chatPreferences.key_exists(user.playerId):
                client_preferences['globalChat'] = chatPreferences.get_key(user.playerId)['toggle']
            else:
                client_preferences['globalChat'] = True
                chatPreferences.set_key(user.playerId, {'toggle': True})
            if client_preferences['globalChat']:
                user.send_crypto_packet(packetFactory.SystemMessagePacket(
                    "[Proxy] {red}Global chat is enabled, use %sg <Message> to chat and %sgoff to disable it." % (config.globalConfig.get_key('commandPrefix'), config.globalConfig.get_key('commandPrefix')),
                    0x3).build())
                if ircMode:
                    global ircBot
                    ircBot.send_connected(data.players.playerList[user.playerId][0], data.clients.connectedClients[user.playerId].ship)
            else:
                user.send_crypto_packet(packetFactory.SystemMessagePacket(
                    "[Proxy] {red}Global chat is disabled, use %sgon to enable it and use %sg <Message> to chat." % (config.globalConfig.get_key('commandPrefix'), config.globalConfig.get_key('commandPrefix')),
                    0x3).build())
        data.clients.connectedClients[user.playerId].set_preferences(client_preferences)

@plugins.on_client_remove_hook
def notify_loss(user):
    global ircMode
    if ircMode and user.playerId in data.clients.connectedClients:
        global ircBot
        client_preferences = data.clients.connectedClients[user.playerId].get_preferences()
        if 'globalChat' in client_preferences and client_preferences['globalChat']:
            ircBot.send_left(data.players.playerList[user.playerId][0], data.clients.connectedClients[user.playerId].ship)



@plugins.CommandHook("irc")
class IRCCommand(Command):
    def call_from_console(self):
        global ircMode
        global ircBot
        if ircMode and ircBot is not None:
            ircBot.sendLine(self.args.split(" ", 1)[1])
            return "[IRC] >>> %s" % self.args.split(" ", 1)[1]


@plugins.CommandHook("gon", "Enable global chat.")
class EnableGChat(Command):
    def call_from_client(self, client):
        global chatPreferences
        preferences = data.clients.connectedClients[client.playerId].get_preferences()
        preferences['globalChat'] = True
        client.send_crypto_packet(
            packetFactory.SystemMessagePacket("[GlobalChat] Global chat enabled for you.", 0x3).build())
        data.clients.connectedClients[client.playerId].set_preferences(preferences)
        new_preferences = chatPreferences.get_key(client.playerId)
        new_preferences['toggle'] = True
        chatPreferences.set_key(client.playerId, new_preferences)


@plugins.CommandHook("goff", "Disable global chat.")
class DisableGChat(Command):
    def call_from_client(self, client):
{'fraction_non_alphanumeric': 0.11658774094577469, 'fraction_numerical': 0.004001867538184486, 'mean_word_length': 2.466019417475728, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '895926', 'n_tokens_mistral': 4349, 'n_tokens_neox': 4174, 'n_words': 872}