def handle_topic_changed(message): channel, topic = message.params get_channel(message, channel).topic = topic signal("topic-changed").send(message, user=get_user(message), channel=channel, topic=topic)
def process(f): """ Register an event with Blinker. Convenience function. """ print("Registering function for event {}".format(event)) signal(event).connect(f) return f
def _login(self): """ Send Login message to SpringLobby Server. """ self.writeln("LOGIN {} {} 3200 * TurBoMatrix 0.1".format( self.username, self.password)) signal("login-complete").send(self)
def disconnected(client_wrapper): """ Either reconnect the LobbyProtocol object, or exit, depending on configuration. Called by LobbyProtocol when we lose the connection. """ client_wrapper.protocol.work = False print("Disconnected from {}. Attempting to reconnect...".format( client_wrapper.netid)) signal("disconnected").send(client_wrapper.protocol) if not client_wrapper.protocol.autoreconnect: sys.exit(2) connector = loop.create_connection(LobbyProtocol, **client_wrapper.server_info) def reconnected(f): """ Callback function for a successful reconnection. """ print("Reconnected! {}".format(client_wrapper.netid)) transport, protocol = f.result() protocol.login(client_wrapper.username, client_wrapper.password) protocol.channels_to_join = client_wrapper.channels_to_join protocol.server_info = client_wrapper.server_info protocol.netid = client_wrapper.netid protocol.wrapper = client_wrapper signal("netid-available").send(protocol) client_wrapper.protocol = protocol asyncio. async (connector).add_done_callback(reconnected)
def _parse_mode(message): # :ChanServ!ChanServ@services. MODE ##fwilson +o fwilson if "CHANMODES" in message.client.server_supports: argument_modes = "".join( message.client.server_supports["CHANMODES"].split(",")[:-1]) argument_modes += message.client.server_supports["PREFIX"].split( ")")[0][1:] else: argument_modes = "beIqaohvlk" print("argument_modes are", argument_modes) user = get_user(message.source) channel = message.params[0] modes = message.params[1] args = message.params[2:] flag = "+" for mode in modes: if mode in "+-": flag = mode continue if mode in argument_modes: arg = args.pop(0) else: arg = None signal("{}mode".format(flag)).send(message, mode=mode, arg=arg, user=user, channel=channel) signal("mode {}{}".format(flag, mode)).send(message, arg=arg, user=user, channel=channel)
def connection_made(self, transport): print("Connection MADE") self.work = True self.transport = transport self.wrapper = None self.logger = logging.getLogger("asyncspring.LobbyProtocol") self.last_ping = float('inf') self.last_pong = 0 self.lag = 0 self.buf = "" self.old_nickname = None self.nickname = "" self.server_supports = collections.defaultdict(lambda *_: None) self.queue = [] self.queue_timer = 1.5 self.caps = set() self.registration_complete = False self.channels_to_join = [] self.autoreconnect = True signal("connected").send(self) print("Connection success.") self.process_queue()
def handle_900(message): """ Handle numeric 900 ("SASL authentication successful"). """ print("SASL authentication complete.") signal("sasl-auth-complete").send(message) signal("auth-complete").send(message) asyncspring.plugins.cap.cap_done(message.client, "sasl")
def _redispatch_kick(message): kicker = get_user(message.source) channel, kickee, reason = message.params[0], get_user( message.params[1]), message.params[2] signal("kick").send(message, kicker=kicker, kickee=kickee, channel=channel, reason=reason)
def _writeln(self, line): """ Send a raw message to SpringRTS Lobby immediately. """ if not isinstance(line, bytes): line = line.encode("utf-8") # print("SENT:\t\t{}".format(line)) self.transport.write(line + b"\r\n") signal("lobby-send").send(line.decode())
def _connection_registered(message): log.debug("Connection registered!") signal("accepted").send(message) message.client.registration_complete = True _queue_ping(message.client) for channel in message.client.channels_to_join: # log.debug(channel) message.client.join(channel)
def process(f): """ Register an event with Blinker. Convenience function. """ self.logger.info("Registering function {} for event {}".format(f.__name__, event)) signal(event).connect(f, sender=ANY, weak=False) return f
def data_received(self, data): if not self.work: return data = data.decode() self.buf += data while "\n" in self.buf: index = self.buf.index("\n") line_received = self.buf[:index].strip() self.buf = self.buf[index + 1:] # print(line_received) signal("raw").send(self, text=line_received)
def __init__(self, config): self.bot = discord.Client() self.token = config['discordToken'] self.channels = config['mappingChannels'] self.command_chars = config.get('commandChars', []) # signals self.discord_signal = signal(SIGNALNAMES.DISCORD_MSG) self.irc_signal = signal(SIGNALNAMES.IRC_MSG) self.irc_signal.connect(self.on_irc_message) self.bot.event(self.on_message)
def _register(self): """ Send registration messages to SpringLobby Server. """ if self.email: self.writeln("REGISTER {} {} {}".format(self.username, self.password, self.email)) else: self.writeln("REGISTER {} {}".format(self.username, self.password)) print("Sent registration information") signal("registration-complete").send(self) self.nickname = self.username
def handle_public_messages(message, user, target, text): prefix = message.client.nickname triggers = [ i.format(prefix) for i in ["{}: ", "{}, ", "{} "] + command_character_registry ] for trigger in triggers: if text.startswith(trigger): text = text[len(trigger):] signal("addressed").send(message, user=user, target=target, text=text) return
def reconnected(f): """ Callback function for a successful reconnection. """ print("Reconnected! {}".format(client_wrapper.netid)) transport, protocol = f.result() protocol.login(client_wrapper.username, client_wrapper.password) protocol.channels_to_join = client_wrapper.channels_to_join protocol.server_info = client_wrapper.server_info protocol.netid = client_wrapper.netid protocol.wrapper = client_wrapper signal("netid-available").send(protocol) client_wrapper.protocol = protocol
def handle_irc_cap(message): if message.params[1] == "LS": if message.client.netid not in capabilities_available: capabilities_available[message.client.netid] = set() capabilities_available[message.client.netid].update(set(message.params[2].split())) print("Capabilities provided by server are {}".format(capabilities_available[message.client.netid])) if message.client.netid not in registration_state: registration_state[message.client.netid] = set() registration_state[message.client.netid].add("caps-known") request_capabilities(message.client, capabilities_available[message.client.netid] & capabilities_requested[ message.client.netid]) if message.params[1] == "ACK": print("ACK received from server, ending capability negotiation. {}".format(message.client.caps)) signal("caps-acknowledged").send(message.client) check_all_caps_done(message.client)
async def reconnect(client_wrapper): protocol = None server_info = client_wrapper.server_info log.info("reconnecting") while protocol is None: await asyncio.sleep(10) try: transport, protocol = await loop.create_connection(LobbyProtocol, **server_info) client_wrapper.protocol = protocol signal("netid-available").send(protocol) signal("reconnected").send() except ConnectionRefusedError as conn_error: pass log.info("HOST DOWN! retry in 10 secs {}".format(conn_error))
async def connect(server, port=8200, use_ssl=False): """ Connect to an SpringRTS Lobby server. Returns a proxy to an LobbyProtocol object. """ transport, protocol = await loop.create_connection(LobbyProtocol, host=server, port=port, ssl=use_ssl) protocol.wrapper = LobbyProtocolWrapper(protocol) protocol.server_info = {"host": server, "port": port, "ssl": use_ssl} protocol.netid = "{}:{}:{}{}".format(id(protocol), server, port, "+" if use_ssl else "-") signal("netid-available").send(protocol) connections[protocol.netid] = protocol.wrapper return protocol.wrapper
def __init__(self, config): super(IRCBot, self).__init__(host=config['ircServer'], port=config.get('ircPort', 6667), ssl=config.get('ircSsl', False)) self.nick = config.get('ircNick', 'discirc') self.channels = config['mappingChannels'] self.password = config.get('ircPass') self.channelPass = config.get('channelPass', {}) self.on('CLIENT_CONNECT', self.on_connect) self.on('PING', self.on_ping) self.on('PRIVMSG', self.on_irc_message) self.on('RPL_ENDOFMOTD', self.on_motddone) self.on('ERR_NOMOTD', self.on_motddone) self.users = dict() # signals self.discord_signal = signal(SIGNALNAMES.DISCORD_MSG) self.discord_signal.connect(self.on_discord_message) self.irc_signal = signal(SIGNALNAMES.IRC_MSG)
def connection_made(self, transport): self.loop = asyncio.get_event_loop() self.work = True self.transport = transport self.wrapper = None self.last_ping = float('inf') self.last_pong = 0 self.lag = 0 self.buf = "" self.old_nickname = None self.server_supports = collections.defaultdict(lambda *_: None) self.queue = [] self.queue_timer = 1.0 # seconds self.caps = set() self.registration_complete = False self.signals = dict() self.signals["connected"] = signal("connected") self.signals["raw"] = signal("raw") self.signals["connection-lost"] = signal("connection-lost") self.signals["lobby-send"] = signal("lobby-send") self.signals["registration-complete"] = signal("registration-complete") self.signals["login-complete"] = signal("login-complete") self.signals["connected"].send(self) self.logger.debug("Connection success.") self.process_queue()
async def connect(server, port=8200, use_ssl=False): """ Connect to an SpringRTS Lobby server. Returns a proxy to an LobbyProtocol object. """ protocol = None while protocol is None: try: transport, protocol = await loop.create_connection(LobbyProtocol, host=server, port=port, ssl=use_ssl) except ConnectionRefusedError as conn_error: log.info("HOST DOWN! retry in 10 secs {}".format(conn_error)) await asyncio.sleep(10) except Exception as e: log.debug(e) # self.logger.info("connected") protocol.wrapper = LobbyProtocolWrapper(protocol) protocol.server_info = {"host": server, "port": port, "ssl": use_ssl} protocol.netid = "{}:{}:{}{}".format(id(protocol), server, port, "+" if use_ssl else "-") signal("netid-available").send(protocol) connections[protocol.netid] = protocol.wrapper return protocol.wrapper
from hashlib import md5 from base64 import b64encode from asyncblink import signal, ANY connections = {} plugins = [] def plugin_registered_handler(plugin_name): plugins.append(plugin_name) signal("plugin-registered").connect(plugin_registered_handler) def load_plugins(*plugins): for plugin in plugins: if plugin not in plugins: importlib.import_module(plugin) def encode_password(password): return b64encode(md5(password.encode('utf-8')).digest()).decode() class LobbyProtocolWrapper: """ Wraps an LobbyProtocol object to allow for automatic reconnection. Only used
def _redispatch_joined(message): user = get_user(message.params[1]) channel = message.params[0] signal("joined").send(message, user=user, channel=channel)
def _redispatch_left(message): user = get_user(message.params[1]) channel = message.params[0] signal("left").send(message, user=user, channel=channel)
def _redispatch_quit(message): signal("quit").send(message, user=get_user(message.source), reason=message.params[0])
def _redispatch_nick(message): old_user = get_user(message.source) new_nick = message.params[0] if old_user.nick == message.client.nickname: message.client.nickname = new_nick signal("nick").send(message, user=old_user, new_nick=new_nick)
def connection_lost(self, exc): if not self.work: return self.logger.critical("Connection lost.") signal("connection-lost").send(self.wrapper)
import ssl from asyncblink import signal loop = asyncio.get_event_loop() connections = {} plugins = [] def plugin_registered_handler(plugin_name): plugins.append(plugin_name) signal("plugin-registered").connect(plugin_registered_handler) def load_plugins(*plugins): for plugin in plugins: if plugin not in plugins: importlib.import_module(plugin) class User: """ Represents a user on SpringRTS Lobby, with their nickname, username, and hostname. """ def __init__(self, username, password, email): self.username = username self.password = password
def setUp(self): super(AsyncBlinkTest, self).setUp() self.signal = signal('test-signal')