def send_message(channel, message, server='irc.mozilla.org', nickname='loads', port=6667): client = irc.client.IRC() c = client.server().connect(server, port, nickname) def on_connect(connection, event): connection.join(channel) main_loop(connection) def on_join(connection, event): main_loop(connection) def main_loop(connection): connection.privmsg(channel, message) connection.quit("Bye !") def on_disconnect(connection, event): raise ExitError() c.add_global_handler("welcome", on_connect) c.add_global_handler("join", on_join) c.add_global_handler("disconnect", on_disconnect) try: client.process_forever() except ExitError: pass
def run(self): while self.processor.shared.paused(): time.sleep(1) self.ircname = self.host + ' ' + self.getname() logger.info("joining IRC") while not self.processor.shared.stopped(): client = irc.client.IRC() try: c = client.server().connect('irc.freenode.net', 6667, self.nick, self.password, ircname=self.ircname) except irc.client.ServerConnectionError: logger.error('irc', exc_info=True) time.sleep(10) continue c.add_global_handler("welcome", self.on_connect) c.add_global_handler("join", self.on_join) c.add_global_handler("quit", self.on_quit) c.add_global_handler("kick", self.on_kick) c.add_global_handler("whoreply", self.on_who) c.add_global_handler("namreply", self.on_name) c.add_global_handler("disconnect", self.on_disconnect) c.set_keepalive(60) self.connection = c try: client.process_forever() except BaseException as e: logger.error('irc', exc_info=True) time.sleep(10) continue logger.info("quitting IRC")
def connect_and_join(client): connection = client.server().connect(CONFIG['irc_server'], CONFIG['irc_port'], CONFIG['irc_nick']) chan = CONFIG['irc_channel'] sleep(10) connection.join(chan) connection.privmsg(chan, 'Hello from Gumboot') return connection
def main(): global config global markov_bot load_config("config.json") #irc.client.ServerConnection.buffer_class = irc.client.LineBuffer client = irc.client.IRC() #client.server().buffer_class = buffer.UTF16LineBuffer markov_bot = markov.markov.MarkovBot(config["lines_file"], config["min_context_depth"], config["max_context_depth"]) try: print "Connecting to {0}:{1} with Nick {2}".format(config["server"], config["port"], config["nick"]) c = client.server().connect(config["server"], config["port"], config["nick"]) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) c.add_global_handler("welcome", on_connect) c.add_global_handler("join", on_join) c.add_global_handler("pubmsg", on_message) c.add_global_handler("privmsg", on_message) command_map["info"] = on_info_cmd; command_map["save"] = on_save_cmd; command_map["getcontexts"] = on_getcontexts_cmd client.process_forever()
def run(self): last_id = 0 while True: try: _, _, addrs = socket.gethostbyname_ex(self.url) for a in addrs: try: print 'Try to connect to %s:%s' % (a, self.port) socket.create_connection((a, self.port), 1) self.addr = a except: pass if not self.addr: raise Exception('All servers do not respond') client = irc.client.IRC() c = client.server().connect(self.addr, self.port, self.settings['login'], password=self.settings['authtoken']) c.add_global_handler('welcome', self.on_connect) c.add_global_handler('pubmsg', self.on_message) client.process_forever() except Exception: print traceback.format_exc() finally: time.sleep(5)
def main(): global target if len(sys.argv) != 4: print "Usage: irccat <server[:port]> <nickname> <target>" print "\ntarget is a nickname or a channel." raise SystemExit(1) cmd, host_port, nickname, target = sys.argv s = host_port.split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print "Error: Erroneous port." raise SystemExit(1) else: port = 6667 client = irc.client.IRC() try: c = client.server().connect(server, port, nickname) except irc.client.ServerConnectionError, x: print x raise SystemExit(1)
def connect(self): """Create a server object, connect and join the channel""" client = irc.client.IRC() try: c = client.server().connect( TwitchParams.server, TwitchParams.port, TWITCH_USER) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) # install handlers # g = lambda x: x**2 c.add_global_handler("welcome", self.on_connect) # send password c.pass_(TWITCH_PASS) # join channel? TODO c.join(TwitchParams.pokemon) print 'about to start forever loop' ''' fall into the forever loop ''' client.process_forever()
def main(): global links if len(sys.argv) != 3: print "Usage: servermap <server[:port]> <nickname>" sys.exit(1) links = [] s = sys.argv[1].split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print "Error: Erroneous port." sys.exit(1) else: port = 6667 nickname = sys.argv[2] client = irc.client.IRC() sys.stdout.write("Connecting to server...") sys.stdout.flush() try: c = client.server().connect(server, port, nickname) except irc.client.ServerConnectionError, x: print x sys.exit(1)
def irctest(): client = irc.client.IRC() server = client.server().connect("127.0.0.1", 6667, "netsink") server.join("#testchan", key="12345") server.privmsg("#testchan", "ready for tasking") # drain response messages for _ in range(6): client.process_once(0.015) server.close()
def test_irc(): server = SocketServer.TCPServer(('', 0), ircserver.IRCHandler) server.cfg = ModuleConfig('irc.conf').cfg thread.start_new_thread(server.serve_forever, ()) client = irc.client.IRC() conn = client.server().connect('127.0.0.1', server.socket.getsockname()[1], 'nickname') conn.join("#testchan", key="12345") conn.privmsg("#testchan", "ready for tasking") # drain response messages for _ in range(6): client.process_once(0.015) conn.close()
def get_conn(self, host, port): if (host, port) in self.irc_servers: return self.irc_servers[(host, port)] client = irc.client.IRC() conn = client.server() conn.connect(host, port, nickname='irker') self.irc_servers[(host, port)] = conn thread = threading.Thread(target=conn.irclibobj.process_forever) client._thread = thread thread.daemon = True thread.start() return conn
def run(self): while self.processor.shared.paused(): time.sleep(1) self.ircname = self.host + ' ' + self.getname() # avoid UnicodeDecodeError using LenientDecodingLineBuffer irc.client.ServerConnection.buffer_class = irc.buffer.LenientDecodingLineBuffer logger.info("joining IRC") t = threading.Thread(target=self.who_thread) t.start() while not self.processor.shared.stopped(): client = irc.client.Reactor() try: bind_address = (self.irc_bind_ip, 0) if self.irc_bind_ip else None ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket, bind_address=bind_address) c = client.server().connect('irc.freenode.net', 6697, self.nick, self.password, ircname=self.ircname, connect_factory=ssl_factory) except irc.client.ServerConnectionError: logger.error('irc', exc_info=True) time.sleep(10) continue c.add_global_handler("welcome", self.on_connect) c.add_global_handler("join", self.on_join) c.add_global_handler("quit", self.on_quit) c.add_global_handler("kick", self.on_kick) c.add_global_handler("whoreply", self.on_who) c.add_global_handler("namreply", self.on_name) c.add_global_handler("disconnect", self.on_disconnect) c.set_keepalive(60) self.connection = c try: client.process_forever() except BaseException as e: logger.error('irc', exc_info=True) time.sleep(10) continue logger.info("quitting IRC")
def send_message(args): client = irc.client.IRC() try: c = client.server().connect(args["server"], args["port"], args["nickname"]) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) return False cc = ConnectionCallbacks(args["target"], args["message"]) c.add_global_handler("welcome", cc.on_connect) c.add_global_handler("disconnect", cc.on_disconnect) while cc.state != "Disconnected": client.process_once(0.2)
def startUp(serverIP, serverPort, channelList): # Create a client client = irc.client.Reactor() bot_name = subprocess.check_output("hostname") bot_name = str(str.rstrip(bot_name.decode("utf-8"))) dprint("botname = " + bot_name) # Create a server connection globals()['server'] = client.server() # Connect to serverIP and serverPort (TODO: Loop through channel list) server.connect(serverIP, serverPort, bot_name) server.join("#club45") server.notice("bruh", "#club45") dprint("Joined server") server.topic("This is test topic", "#club45")
def main(): print "DALE" global target global user_ids, command_queue global file user_ids = loadFactoids() command_queue = {} #if len(sys.argv) != 4: # print ("Usage: irccat <server[:port]> <nickname> <target>") # print ("\ntarget is a nickname or a channel.") # raise SystemExit(1) #cmd, host_port, nickname, target = sys.argv cmd = "chat.us.freenode.net" host_port = "chat.us.freenode.net:6667" nickname = "CoffeeGuy" + str( random.randint(0,1000) ) target = "##roci" s = host_port.split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print "Error: Erroneous port." raise SystemExit(1) else: port = 6667 print "Connecting" client = irc.client.IRC() try: c = client.server().connect(server, port, nickname) except irc.client.ServerConnectionError, x: print x raise SystemExit(1)
def main(): global target args = get_args() target = args.target client = irc.client.IRC() try: c = client.server().connect(args.server, args.port, args.nickname) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) c.add_global_handler("welcome", on_connect) c.add_global_handler("join", on_join) c.add_global_handler("disconnect", on_disconnect) client.process_forever()
def run(self): while self.processor.shared.paused(): time.sleep(1) self.ircname = self.host + ' ' + self.getname() # avoid UnicodeDecodeError using LenientDecodingLineBuffer irc.client.ServerConnection.buffer_class = irc.buffer.LenientDecodingLineBuffer logger.info("joining IRC") t = threading.Thread(target=self.who_thread) t.start() while not self.processor.shared.stopped(): client = irc.client.Reactor() try: #bind_address = (self.irc_bind_ip, 0) if self.irc_bind_ip else None #ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket, bind_address=bind_address) #c = client.server().connect('irc.freenode.net', 6697, self.nick, self.password, ircname=self.ircname, connect_factory=ssl_factory) c = client.server().connect('irc.freenode.net', 6667, self.nick, self.password, ircname=self.ircname) except irc.client.ServerConnectionError: logger.error('irc', exc_info=True) time.sleep(10) continue c.add_global_handler("welcome", self.on_connect) c.add_global_handler("join", self.on_join) c.add_global_handler("quit", self.on_quit) c.add_global_handler("kick", self.on_kick) c.add_global_handler("whoreply", self.on_who) c.add_global_handler("namreply", self.on_name) c.add_global_handler("disconnect", self.on_disconnect) c.set_keepalive(60) self.connection = c try: client.process_forever() except BaseException as e: logger.error('irc', exc_info=True) time.sleep(10) continue logger.info("quitting IRC")
def notify(msg): client = irc.client.Reactor() server = client.server() server.connect("irc.freenode.net", 6667, "hsldzat") def on_connect(connection, event): connection.join("#hakierspejs") def on_join(connection, event): connection.privmsg("#hakierspejs", msg) connection.quit() raise RuntimeError() client.add_global_handler("welcome", on_connect) client.add_global_handler("join", on_join) try: client.process_forever() except RuntimeError: pass
def login(username, passwd, server): servers[server] = {} try: servers[server]["conn"] = client.server().connect(server, 6667, username) except irc.client.ServerConnectionError: pass # TODO: handle error # add generic printing for everything for val in irc.events.numeric.values(): servers[server]["conn"].add_global_handler(val, generic_print) # add some specific behaviours special_handlers = ["welcome", "disconnect", "privmsg", "pubmsg", "join", "part"] for h in special_handlers: servers[server]["conn"].remove_global_handler(h, generic_print) func = globals()["_on_%s" % h] servers[server]["conn"].add_global_handler(h, func)
def save_data(self, token, trigger_id, **data): """ let's publish the data """ if data and data['link'] is not None and len(data['link']) > 0: # get the data of this trigger trigger = Irc.objects.get(trigger_id=trigger_id) # open a connection # TODO : # add a wait before posting ; # join once # left once client = irc.client.IRC() try: c = client.server().connect(trigger.server, trigger.port, trigger.nickname) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1) if trigger.channel_key: c.join(trigger.channel, key=trigger.channel_key) else: c.join(trigger.channel) text = '' text = (data['title'] + ' - ' + data['link'] if 'title' in data else data['link']) c.privmsg(trigger.channel, text) c.quit("Using irc.client.py") sentance = str('irc post {} on server {}/{} done').format( text, trigger.server, trigger.channel) logger.debug(sentance) else: logger.critical("no data provided for trigger ID %s ", trigger_id)
def start(self): """Setup client, connect to server, ... """ # create client client = irc.client.IRC() # log into chat server = client.server().connect(self.config['server'], self.config['port'], self.config['username']) # process chat messages server.add_global_handler('pubmsg', self.parse_input) # log into chat room server.join(self.config['channel']) # start analysis self.analyze_input() # wait client.process_forever()
def __call__(self, test_results): msg = '[loads] Test Over. \x1f' + str(test_results) # creating the IRC client client = irc.client.IRC() if self.ssl: connect_factory = irc.connection.Factory(wrapper=ssl.wrap_socket) else: connect_factory = irc.connection.Factory() c = client.server().connect(self.server, self.port, self.nickname, connect_factory=connect_factory) def on_connect(connection, event): connection.join(self.channel) def on_endofnames(connection, event): main_loop(connection) def main_loop(connection): connection.privmsg(self.channel, msg) connection.quit("Bye !") def on_disconnect(connection, event): raise ExitError() def on_error(connection, event): raise ExitError() c.add_global_handler("welcome", on_connect) c.add_global_handler("endofnames", on_endofnames) c.add_global_handler("disconnect", on_disconnect) c.add_global_handler("error", on_error) try: client.process_forever() except ExitError: pass
def main(): global server global target global port global nickname global message args = get_args() message = args.message client = irc.client.Reactor() try: c = client.server().connect(server, port, nickname) except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(0) c.add_global_handler("welcome", on_connect) c.add_global_handler("join", on_join) c.add_global_handler("disconnect", on_disconnect) client.process_forever()
def main(): global links if len(sys.argv) != 3: print("Usage: servermap <server[:port]> <nickname>") sys.exit(1) links = [] s = sys.argv[1].split(":", 1) server = s[0] if len(s) == 2: try: port = int(s[1]) except ValueError: print("Error: Erroneous port.") sys.exit(1) else: port = 6667 nickname = sys.argv[2] client = irc.client.IRC() sys.stdout.write("Connecting to server...") sys.stdout.flush() try: c = client.server().connect(server, port, nickname) except irc.client.ServerConnectionError as x: print(x) sys.exit(1) c.add_global_handler("welcome", on_connect) c.add_global_handler("passwdmismatch", on_passwdmismatch) c.add_global_handler("links", on_links) c.add_global_handler("endoflinks", on_endoflinks) c.add_global_handler("disconnect", on_disconnect) client.process_forever()
def run(self): while self.processor.shared.paused(): time.sleep(1) self.ircname = self.host + " " + self.getname() # avoid UnicodeDecodeError using LenientDecodingLineBuffer irc.client.ServerConnection.buffer_class = irc.buffer.LenientDecodingLineBuffer logger.info("joining IRC") while not self.processor.shared.stopped(): client = irc.client.Reactor() try: c = client.server().connect("irc.freenode.net", 6667, self.nick, self.password, ircname=self.ircname) except irc.client.ServerConnectionError: logger.error("irc", exc_info=True) time.sleep(10) continue c.add_global_handler("welcome", self.on_connect) c.add_global_handler("join", self.on_join) c.add_global_handler("quit", self.on_quit) c.add_global_handler("kick", self.on_kick) c.add_global_handler("whoreply", self.on_who) c.add_global_handler("namreply", self.on_name) c.add_global_handler("disconnect", self.on_disconnect) c.set_keepalive(60) self.connection = c try: client.process_forever() except BaseException as e: logger.error("irc", exc_info=True) time.sleep(10) continue logger.info("quitting IRC")
action='store_true', help='Print to stdout all events') parser.add_argument('--debug', action='store_true', help='Debug messages') options = parser.parse_args() def debug(*args): "Prints all arguments, if the debug option is enable." if options.debug: print ' '.join(map(str, args)) Random = random.Random() client = irc.client.IRC() server = client.server() channellist = [] hodors = ['Hodor' + x for x in ['.', '...', '?', '!']] # Default event processor def process_event(connection, event): """ Prints the parameters of the supplied event: type, arguments, source, and target. """ print "{0}: {1} ({2}->{3})".format(event.type, event.arguments, event.source, event.target) def pubmsg_handler(connection, event): """
dialogue = '%s: %s' % (t['character'], t['action']['dialogue']) for i in xrange(0, len(dialogue), 400): connection.privmsg('#ghostbusters', dialogue[i:i + 400]) time.sleep(len(dialogue.split()) * 0.5) elif 'action' in t and 'movement' in t['action']: connection.action( '#ghostbusters', '%s: %s' % (t['character'], t['action']['movement'])) time.sleep(5) elif 'topic' in t: connection.topic('#ghostbusters', t['topic']) time.sleep(2) elif 'narration' in t: for i in xrange(0, len(t['narration']), 400): connection.privmsg('#ghostbusters', t['narration'][i:i + 400]) time.sleep(len(t['narration'].split()) * 0.5) if options.ssl: connect_factory = irc.connection.Factory(wrapper=ssl.wrap_socket) else: connect_factory = irc.connection.Factory() client = irc.client.IRC() connection = client.server().connect(host, options.port, 'venkman', password=options.password, connect_factory=connect_factory) connection.add_global_handler('welcome', on_connect) client.process_forever()
Vim�UnDo�E��§�a�u�I$wduk�|x���U�oK��"P client.process_forever()M>>>>S~�l _�����S~n��5�_�"����S~o��H"def on_connect(connection, event):5�_�����S~o��I connection.privmsg()5�_�����S~o��I connection.privmsg('')5�_�$����S~o��I& connection.privmsg('NickServ', '')5�_�@����S~pp�?CI raise SystemExit(1)5�_�B����S~pv�ACK c.add_global_handler()5�_� B����S~pz�ACK c.add_global_handler("")5�_� B����S~p��ACK c.add_global_handler("use.")5�_� B����S~qp�AB, c.add_global_handler("use.", on_connect)5�_� B����S~qq�AB5�_� ����S~q��I5 connection.privmsg('NickServ', 'IDENTIFY loser5')5�_� ����S~q��I5 connection.privmsg('NickServ', 'IDENTIFY loser5')5�_� ����S~q��6 # connection.privmsg('NickServ', 'IDENTIFY loser5')5�_�/����S~q��H/"The nick or channel to which to send messages"5�_�����S~r �Jdef on_notice()5�_�����S~r�K�K5�_�����S~r�5�_�����S~r�K6 # connection.privmsg('NickServ', 'IDENTIFY loser5')5�_�����S~r�K5 connection.privmsg('NickServ', 'IDENTIFY loser5')5�_�C����S~r �BEK5�_�D����S~r(�CEL c.add_global_handler()5�_�D����S~r)�CEL c.add_global_handler("")5�_�D&����S~r4�CEL& c.add_global_handler("privnotice")5�_�����S~rK�Ldef on_notice():5�_�����S~r��L#! /usr/bin/env python### Example program using irc.client.#F# This program is free without restrictions; do anything you like with# it.#!# Joel Rosdahl <*****@*****.**> import sysimport argparseimport itertoolsimport irc.clientimport irc.logging target = None/"The nick or channel to which to send messages"!def on_notice(connection, event):4 connection.privmsg('NickServ', 'IDENTIFY loser5')"def on_connect(connection, event):% if irc.client.is_channel(target): connection.join(target) return main_loop(connection)def on_join(connection, event): main_loop(connection)def get_lines(): while True:* yield sys.stdin.readline().strip()def main_loop(connection):7 for line in itertools.takewhile(bool, get_lines()): print(line)( connection.privmsg(target, line)* connection.quit("Using irc.client.py")%def on_disconnect(connection, event): raise SystemExit()def get_args():& parser = argparse.ArgumentParser()! parser.add_argument('server')# parser.add_argument('nickname')? parser.add_argument('target', help="a nickname or channel")? parser.add_argument('-p', '--port', default=6667, type=int)% irc.logging.add_arguments(parser) return parser.parse_args()def main(): global target args = get_args() irc.logging.setup(args) target = args.target client = irc.client.IRC() try:J c = client.server().connect(args.server, args.port, args.nickname), except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1)1 c.add_global_handler("privnotice", on_notice)/ c.add_global_handler("welcome", on_connect)) c.add_global_handler("join", on_join)5 c.add_global_handler("disconnect", on_disconnect) client.process_forever()if __name__ == '__main__': main()5�_�?����S~s�>@LJ c = client.server().connect(args.server, args.port, args.nickname)5�_�?K����S~s�>ALK #c = client.server().connect(args.server, args.port, args.nickname)5�_�@����S~s �?AM c = client.server()5�_� @$����S~s�?AM% c = client.server().connect()5�_�! @%����S~s�?AM' c = client.server().connect('')5�_� "!@9����S~s�?AM; c = client.server().connect('irc.freenode.net', '')5�_�!#"@A����S~s�?AMC c = client.server().connect('irc.freenode.net', '6667', '')5�_�"$#����S~s)�M target = None5�_�#%$����S~s*�M#target = None5�_�$&% ����S~s.�Ntarget = ""5�_�%'&/����/6vS~st�.0N& parser = argparse.ArgumentParser()5�_�&('0����/6vS~sw�/1N! parser.add_argument('server')5�_�')(1����/6vS~sy�02N# parser.add_argument('nickname')5�_�(*)2����/6vS~s|�13N? parser.add_argument('target', help="a nickname or channel")5�_�)+*3����/6vS~s~�24N? parser.add_argument('-p', '--port', default=6667, type=int)5�_�*,+4����/6vS~s��35N% irc.logging.add_arguments(parser)5�_�+-,5����/6vS~s��46N return parser.parse_args()5�_�,.-5����/6vS~s��47N# return parser.parse_args()5�_�-/.<����/7vS~s��;=O irc.logging.setup(args)5�_�.0/=����/7vS~s��<>O target = args.target5�_�/10=����/7vS~s��<?O #target = args.target5�_�021> ����/7vS~s��=?P target =""5�_�132>����/7vS~s��=?P target = ""5�_�243C8����/7vS~s��BDPK c = client.server().connect('irc.freenode.net', '6667', 'blarnath')5�_�354C<����/7vS~s� �BDPJ c = client.server().connect('irc.freenode.net', 6667', 'blarnath')5�_�4658����/7vS~t�79Pdef main():5�_�576O����/7vS~t �NPPif __name__ == '__main__':5�_�687P����/7vS~t�O main()5�_�7989����9NvS~t �8OP global target args = get_args() #irc.logging.setup(args) #target = args.target target = "#coproc_test" client = irc.client.IRC() try:K #c = client.server().connect(args.server, args.port, args.nickname)I c = client.server().connect('irc.freenode.net', 6667, 'blarnath'), except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1)1 c.add_global_handler("privnotice", on_notice)/ c.add_global_handler("welcome", on_connect)) c.add_global_handler("join", on_join)5 c.add_global_handler("disconnect", on_disconnect) client.process_forever()5�_�8:99����9NvS~t-�8:P global target5�_�9;:L����9NvS~�e�MOQclient.process_forever()�KNP5�_�:<;N ����9OvS~�l�MPQclient.process_forever()5�_�;=<M����9OvS~��LMwhile True:5�_�<>=M����9NvS~���LNP client.process_forever()5�_�=>M����9NvS~�k �LNPclient.process_forever()5�_�����S~q��J!def on_notice(connection, event): �K�KH #! /usr/bin/env python### Example program using irc.client.#F# This program is free without restrictions; do anything you like with# it.#!# Joel Rosdahl <*****@*****.**> import sysimport argparseimport itertoolsimport irc.clientimport irc.logging target = None/"The nick or channel to which to send messages""def on_connect(connection, event):% if irc.client.is_channel(target): connection.join(target) return main_loop(connection)def on_join(connection, event): main_loop(connection)def get_lines(): while True:* yield sys.stdin.readline().strip()def main_loop(connection):7 for line in itertools.takewhile(bool, get_lines()): print(line)( connection.privmsg(target, line)* connection.quit("Using irc.client.py")%def on_disconnect(connection, event): raise SystemExit()def get_args():& parser = argparse.ArgumentParser()! parser.add_argument('server')# parser.add_argument('nickname')? parser.add_argument('target', help="a nickname or channel")? parser.add_argument('-p', '--port', default=6667, type=int)% irc.logging.add_arguments(parser) return parser.parse_args()def main(): global target args = get_args() irc.logging.setup(args) target = args.target client = irc.client.IRC() try:J c = client.server().connect(args.server, args.port, args.nickname), except irc.client.ServerConnectionError: print(sys.exc_info()[1]) raise SystemExit(1)/ c.add_global_handler("welcome", on_connect)) c.add_global_handler("join", on_join)5 c.add_global_handler("disconnect", on_disconnect) client.process_forever()if __name__ == '__main__': main()5��
host, = args def on_connect(connection, event): connection.join('#ghostbusters') # Say things! for t in itertools.cycle(things): if 'action' in t and 'dialogue' in t['action']: dialogue = '%s: %s' % (t['character'], t['action']['dialogue']) for i in xrange(0, len(dialogue), 400): connection.privmsg('#ghostbusters', dialogue[i:i+400]) time.sleep(len(dialogue.split()) * 0.5) elif 'action' in t and 'movement' in t['action']: connection.action('#ghostbusters', '%s: %s' % (t['character'], t['action']['movement'])) time.sleep(5) elif 'topic' in t: connection.topic('#ghostbusters', t['topic']) time.sleep(2) elif 'narration' in t: for i in xrange(0, len(t['narration']), 400): connection.privmsg('#ghostbusters', t['narration'][i:i+400]) time.sleep(len(t['narration'].split()) * 0.5) if options.ssl: connect_factory = irc.connection.Factory(wrapper=ssl.wrap_socket) else: connect_factory = irc.connection.Factory() client = irc.client.IRC() connection = client.server().connect(host, options.port, 'venkman', password=options.password, connect_factory=connect_factory) connection.add_global_handler('welcome', on_connect) client.process_forever()
help='Print to stdout all events') parser.add_argument('--debug', action='store_true', help='Debug messages') options = parser.parse_args() def debug(*args): "Prints all arguments, if the debug option is enable." if options.debug: for x in args: print x, print Random = random.Random() client = irc.client.IRC() server = client.server() channellist = [] hodors = ['Hodor'+x for x in ['.','...','?','!']] # Default event processor def process_event(connection, event): """ Prints the parameters of the supplied event: type, arguments, source, and target. """ print "{0}: {1} ({2}->{3})".format(event.type, event.arguments, event.source, event.target) def pubmsg_handler(connection, event): """ Randomly reply to the pubmsg with "Hodor". """
logger.info(line) connection.privmsg(config['irc']['channel'], line) else: logger.info(f"already seen: {r}") client = irc.client.IRC() try: if config['irc'].getboolean('ssl'): logger.info( f"connecting to {config['irc']['host']}:{config['irc']['port']} with SSL... " ) ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket) bot = client.server().connect(config['irc']['host'], int(config['irc']['port']), config['irc']['nick'], connect_factory=ssl_factory) else: logger.info( f"connecting to {config['irc']['host']}:{config['irc']['port']} without SSL... " ) bot = client.server().connect(config['irc']['host'], int(config['irc']['port']), config['irc']['nick']) except irc.client.ServerConnectionError: logger.error(sys.exc_info()[1]) print(sys.exc_info()[1]) raise SystemExit(1) bot.add_global_handler("welcome", on_connect) bot.add_global_handler("join", on_join)
def main(channel=None, caller=None): """ Main procedure. """ # pylint: disable=R0914,R0912,W0603 # Too many local variables # Too many branches # Using the global statement from x84.bbs import getsession, getterminal, getch, echo, ini import irc.client import irc.logging session, term = getsession(), getterminal() EXIT = False if channel is None: try: channel = ini.CFG.get('irc', 'channel') except: channel = '#1984' nick = session.handle.replace(' ', '_') if nick == 'anonymous': # anonymous is heavily used, make up a new one nick = 'anon{0:03d}'.format(random.randrange(999)) if not channel[0] in '#!': channel = '#' + channel try: host = ini.CFG.get('irc', 'server') except: host = 'irc.efnet.org' try: port = ini.CFG.getint('irc', 'port') except: port = 6667 try: host_ssl = ini.CFG.getboolean('irc', 'ssl') except: host_ssl = False try: swag = ini.CFG.get('irc', 'swag') except: swag = 'x/84 BBS %s' % ini.CFG.get('system', 'bbsname') def refresh(pager, ipb, init=False): """ Returns terminal sequence suitable for refreshing screen. """ session.activity = 'Chatting in %s' % channel pager.move_end() return u''.join(( u''.join((u'\r\n', term.clear_eol, u'\r\n', term.clear_eol, term.bright_blue(u' mULTi USER nOTEPAD!'.center(term.width).rstrip()), term.clear_eol, (u'\r\n' + term.clear_eol) * (pager.height + 2), pager.border())) if init else u'', pager.title(u''.join(( term.reset, term.blue(u'-[ '), term.bold_blue(channel), term.blue(u' ]-'),))), pager.refresh(), ipb.refresh(),)) def format_server(mesg): return u''.join(( term.green('-'), term.bold_green('!'), term.green('- '), term.white(mesg), )) def format_chat(nick, target, mesg): return u''.join(( term.bold_blue('<'), term.bold_white(nick), term.bold_blue('> '), term.white(mesg), )) def format_join(nick, chan): return u''.join(( term.green('>'), term.bold_green('>'), term.green('> '), term.bold_white(nick), term.white(' joined '), term.bold_white(chan), )) def format_me(nick, target, mesg): return u''.join(( term.bold_blue('* '), term.bold_white(nick), ' ', term.white(mesg), )) def format_quit(nick, mesg): return u''.join(( term.green('<'), term.bold_green('<'), term.green('< '), term.bold_white(nick), term.white(' quit '), term.bold_black('['), term.white(mesg or 'bye'), term.bold_black(']'), )) def show_help(): return u'\r\n'.join(( term.bold_yellow('/help ') + term.white('shows this help'), term.bold_yellow('/me ') + term.white('to send an action'), term.bold_yellow('/topic ') + term.white('to see/set the topic'), term.bold_yellow('/quit ') + term.white('to quit the chat'), )) pager = get_pager(None) # output window readline = get_inputbar(pager) # input bar echo(refresh(pager, readline, init=True)) echo(pager.append(format_server(u''.join(( term.white('use '), term.bold_white('/quit'), term.white(' to exit'), ))))) dirty = time.time() def on_ctcp(c, event): if event.arguments[0] == 'ACTION': pager.append(format_me( event.source.nick, event.target, event.arguments[1], )) c.dirty = time.time() def on_connect(sock): pager.append(format_server('connected')) dirty = time.time() def on_currenttopic(c, event): nick = event.source.nick chan, topic = event.arguments pager.append(format_server(u''.join(( term.bold_white(nick), term.white(' set '), term.bold_white(chan), term.white(' topic to: '), term.bold_white(topic), )))) c.dirty = time.time() def on_erroneusnickname(c, event): pager.append(format_server('dude, that nick is not valid')) def on_error(c, event): pager.append(format_server('error: %s' % event.target)) c.dirty = time.time() c.available = False def on_welcome(c, event): pager.append(format_server(u''.join(( term.white('ready, logged in as '), term.bold_yellow(c.get_nickname()), term.white(' (use '), term.bold_white('/nick'), term.white(' to change)'), )))) pager.append(format_server('joining %s' % channel)) c.join(channel) c.dirty = time.time() def on_disconnect(c, event=None): global dirty pager.append(format_server('disconnected')) c.dirty = time.time() c.available = False def on_endofnames(c, event): pager.append(format_server('%s end of names list' % event.arguments[0])) c.dirty = time.time() def on_join(c, event): global dirty chan = event.target nick = event.source.nick pager.append(format_join(nick, chan)) c.dirty = time.time() def on_namreply(c, event): nicks = [] for nick in event.arguments[2].split(): if nick[0] in '@+%!': nicks.append(term.bold_red(nick[0]) + term.bold_white('%-9s' % nick[1:])) else: nicks.append(term.bold_white('%-9s' % nick)) pager.append(format_server('%s %s' % (event.arguments[1], u' '.join(nicks)))) c.dirty = time.time() def on_nick(c, event): pager.append(format_server(u''.join(( term.bold_white(event.source.nick), term.white(' is now known as '), term.bold_white(event.target), )))) c.dirty = time.time() def on_nicknameinuse(c, event): server.nickname += '_' pager.append(format_server(u''.join(( term.white('handle in use, trying '), term.bold_yellow(server.nickname), )))) server.nick(server.nickname) c.dirty = time.time() def on_topic(c, event): nick = event.source.nick chan = event.target topic = event.arguments[0] pager.append(format_server(u''.join(( term.bold_white(nick), term.white(' set '), term.bold_white(chan), term.white(' topic to: '), term.bold_white(topic), )))) c.dirty = time.time() def on_pubmsg(c, event): global dirty pager.append(format_chat( event.source.nick, event.target, ' '.join(event.arguments) )) c.dirty = time.time() def on_part(c, event): pager.append(format_quit(event.source.nick, event.arguments[0])) c.dirty = time.time() def on_quit(c, event): pager.append(format_quit(event.source.nick, event.arguments[0])) c.dirty = time.time() if host_ssl: import ssl factory = irc.connection.Factory(wrapper=ssl.wrap_socket) else: factory = irc.connection.Factory() client = irc.client.IRC( on_connect=on_connect, on_disconnect=on_disconnect, ) server = client.server() server.dirty = None server.available = True server.add_global_handler('ctcp', on_ctcp) server.add_global_handler('currenttopic', on_currenttopic) server.add_global_handler('endofnames', on_endofnames) server.add_global_handler('erroneusnickname', on_erroneusnickname) server.add_global_handler('error', on_error) server.add_global_handler('join', on_join) server.add_global_handler('namreply', on_namreply) server.add_global_handler('nicknameinuse', on_nicknameinuse) server.add_global_handler('nick', on_nick) server.add_global_handler('part', on_part) server.add_global_handler('pubmsg', on_pubmsg) server.add_global_handler('quit', on_quit) server.add_global_handler('topic', on_topic) server.add_global_handler('welcome', on_welcome) echo(pager.append(format_server(u''.join(( term.white('connecting to '), term.bold_white(host), ))))) server.connect( host, port, nick, ircname=swag, connect_factory=factory, ) def process_cmd(pager, msg): """ Process command recieved and display result in chat window. """ cmd, args = msg.split()[0], msg.split()[1:] # pylint: disable=W0603 # Using the global statement global CHANNEL, NICKS, EXIT if cmd.lower() == '/help': pager.append(show_help()) return True elif cmd.lower() in ('/act', '/me',): server.ctcp('action', channel, ' '.join(args)) pager.append(format_me(server.nickname, channel, ' '.join(args))) server.dirty = time.time() elif cmd.lower() in ('/names', '/users', '/who'): server.names(channel) elif cmd.lower() == '/nick': if args: server.nickname = ' '.join(args) server.nick(server.nickname) elif cmd.lower() == '/say': server.privmsg(channel, ' '.join(args)) pager.append(format_chat(server.nickname, channel, ' '.join(args))) server.dirty = time.time() elif cmd.lower() == '/topic': if args: server.topic(channel, ' '.join(args)) else: server.topic(channel) elif cmd.lower() == '/quit': EXIT = True server.quit(' '.join(args)) elif cmd.lower() == '/users': queue.put('NAMES %s' % CHANNEL) return True else: pager.append(format_server(u''.join(( term.bold_red('syntax error '), term.white('do you need /help ?'), )))) return False while not EXIT and server.available: inp = getch(POLL_KEY) # poll for and process screen resize if session.poll_event('refresh') or ( inp in (term.KEY_REFRESH, unichr(12))): pager = get_pager(pager) saved_inp = readline.content readline = get_inputbar(pager) readline.content = saved_inp echo(refresh(pager, readline, init=True)) dirty = None # process keystroke as input, or, failing that, # as a command key to the pager. refresh portions of # input bar or act on carriage return, accordingly. elif inp is not None: otxt = readline.process_keystroke(inp) if readline.carriage_returned: if readline.content.startswith('/'): if process_cmd(pager, readline.content): pager = get_pager(pager) echo(refresh(pager, readline, init=True)) elif (0 != len(readline.content.strip())): line = readline.content.strip() server.privmsg(channel, line) pager.append(format_chat(server.nickname, channel, line)) dirty = time.time() readline = get_inputbar(pager) echo(readline.refresh()) elif 0 == len(otxt): if type(inp) is int: echo(pager.process_keystroke(inp)) else: echo(u''.join(( readline.fixate(-1), readline.colors.get('highlight', u''), otxt, term.normal))) # update pager contents. Its a lot for 9600bps .. if server.dirty is not None: dirty = dirty or server.dirty if dirty is not None and time.time() - dirty > POLL_OUT: echo(refresh(pager, readline)) dirty = None server.dirty = None # poll irc client stuff client.process_once(POLL_IRC) echo(u''.join((term.move(term.height, 0), term.normal))) server.quit() return True