async def start(self, name_pairs): '''Start IRC connections if enabled in environment.''' import irc.client as irc_client from jaraco.stream import buffer # see https://pypi.python.org/pypi/irc under DecodingInput irc_client.ServerConnection.buffer_class = \ buffer.LenientDecodingLineBuffer # Register handlers for events we're interested in reactor = irc_client.Reactor() for event in 'welcome join whoreply disconnect'.split(): reactor.add_global_handler(event, getattr(self, 'on_' + event)) # Note: Multiple nicks in same channel will trigger duplicate events clients = [ IrcClient(self.coin, real_name, self.nick + suffix, reactor.server()) for (real_name, suffix) in name_pairs ] while True: try: for client in clients: client.connect(self) while True: reactor.process_once() await asyncio.sleep(2) except irc_client.ServerConnectionError as e: self.logger.error('connection error: {}'.format(e)) except self.DisconnectedError: self.logger.error('disconnected') await asyncio.sleep(10)
def main(): # global target global KEY_MAPPINGS_TUPLE global KEY_MAPPINGS KEY_MAPPINGS = {t[0]: t[1] for t in KEY_MAPPINGS_TUPLE} if len(KEY_MAPPINGS_TUPLE) != len(KEY_MAPPINGS.keys()): keys = [tup[0] for tup in KEY_MAPPINGS_TUPLE] dupes = set([x for x in keys if keys.count(x) > 1]) raise ValueError( f'There are duplicate keys in the key mappings tuple. They are: {dupes}' ) reactor = client.Reactor() try: c = reactor.server().connect( 'irc.twitch.tv', 6667, 'trialsparkplays', password='******') except client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) twitch_plays = TwitchPlays(connection=c) setattr(c, '_handle_message', twitch_plays.handle_message) c.join('#trialsparkplays') c.privmsg('#trialsparkplays', 'Connected!') c.process_data() reactor.process_forever()
def post_to_irc(msg, host, port, nick, ident, realname, target): """ Log into an IRC server and send a message to a channel. """ global IRC_CLIENT, IRC_SERVER if IRC_CLIENT is None: IRC_CLIENT = client.Reactor() IRC_SERVER = IRC_CLIENT.server() IRC_SERVER.connect(host, port, nick) if client.is_channel(target): IRC_SERVER.join(target) IRC_SERVER.privmsg(target, msg)
def __init__(self, host: str, port: int, nickname: str, channel: str, password: Optional[str] = None, capabilities: Optional[List[str]] = None) -> None: super().__init__() self.host = host self.port = port self.nickname = nickname self.channel = channel self.password = password self.capabilities = capabilities if capabilities is not None else [] self.shutdown_event = threading.Event() self.expect_disconnection = threading.Event() self.last_ping = datetime.datetime.now() self.on_event: Optional[base.EventCallback] = None self.reactor = client.Reactor() self.reactor.add_global_handler('welcome', self.on_welcome) self.reactor.add_global_handler('pubmsg', self.on_pubmsg) self.reactor.add_global_handler('action', self.on_action) self.reactor.add_global_handler('ping', self.on_ping)
def main(address='irc.rizon.net', port=6667, nick='bwaka'): bot = client.Reactor() bot.add_global_handler("ctcp", on_ctcp) bot.add_global_handler("privmsg", on_priv) bot.add_global_handler("pubmsg", on_pub) bot.add_global_handler("invite", on_invite) bot.add_global_handler("quit", on_quit) server = bot.server() print('connecting...') server.connect(address, port, nick, username='******', ircname='bot') if server.is_connected(): print('connected') sleep(1) for channel in CHANNELS: server.join(channel) try: bot.process_forever() except KeyboardInterrupt: server.disconnect("bai") exit()
def __init__(self, config_file): self._exit_signal = False self._nick_change_counter = 0 self._config_file = config_file self._client = client.Reactor() self._client.add_global_handler("welcome", self._on_connect) self._client.add_global_handler("disconnect", self._on_disconnect) self._client.add_global_handler("nicknameinuse", self._on_nicknameinuse) self._client.add_global_handler("pubmsg", self._on_privmsg) self._client.add_global_handler("privmsg", self._on_privmsg) self._client.add_global_handler("join", self._on_join) self._client.add_global_handler("part", self._on_part) self._client.add_global_handler("quit", self._on_quit) self._client.add_global_handler("nick", self._on_nick) self._client.add_global_handler("namreply", self._on_namreply) self._server_list = dict() # Initialize timer self._timer_lock = threading.Lock() self._timer_queue = list() self._timer = threading.Timer(1, self._timer_process) self._timer.start() # Load config and initialize modules self._load_config() self._module_handler()
def _irc_command_as_streamer(self, commands: Union[str, List[str]], success_msg: str, failure_msgs: Container[str], retry_on_error: bool = True) -> None: if isinstance(commands, str): commands = [commands] channel = '#' + self.oauth.streamer_username.lower() pubnotices: queue.Queue[str] = queue.Queue() welcome = threading.Event() def on_welcome(_c: client.ServerConnection, _e: client.Event) -> None: welcome.set() def on_pubnotice(_: client.ServerConnection, event: client.Event) -> None: msg_ids = [i['value'] for i in event.tags if i['key'] == 'msg-id'] if not msg_ids: return if len(msg_ids) > 1: logger.error('Multiple msg-id tags: %s', event) # ... but continue anyway, and just use the first one. pubnotices.put(msg_ids[0]) self.oauth.refresh() reactor = client.Reactor() connection = reactor.server().connect( 'irc.chat.twitch.tv', 6667, self.oauth.streamer_username.lower(), password=f'oauth:{self.oauth.access_token}') connection.add_global_handler('welcome', on_welcome) connection.add_global_handler('pubnotice', on_pubnotice) reactor.process_once(timeout=5) if not welcome.wait(timeout=5): connection.disconnect() if retry_on_error: self._irc_command_as_streamer(commands, success_msg, failure_msgs, retry_on_error=False) return else: raise base.ServerError('WELCOME not received.') connection.cap('REQ', 'twitch.tv/commands', 'twitch.tv/tags') connection.cap('END') reactor.process_once(timeout=5) for command in commands: connection.privmsg(channel, command) result = '' unknown_msgs = [] deadline = (datetime.datetime.utcnow() + datetime.timedelta(seconds=10)) while result == '' and datetime.datetime.utcnow() < deadline: timeout = deadline - datetime.datetime.utcnow() reactor.process_once(timeout=timeout.total_seconds()) while True: try: msg = pubnotices.get_nowait() except queue.Empty: break if (msg == success_msg or msg in failure_msgs) and result == '': result = msg else: unknown_msgs.append(msg) if result == success_msg: logger.info('%s: success', command) elif result: logger.error('%s: %s', command, result) else: if unknown_msgs: logger.error('%s: No response. Unknown pubnotices: %s', command, unknown_msgs) else: logger.error('%s: No response.') if retry_on_error: connection.disconnect() self._irc_command_as_streamer(commands, success_msg, failure_msgs, retry_on_error=False) return connection.disconnect()