def bot_run(): channel = get_channel() server = get_server() nickname = "spider_bot" irc = IRC() irc.connect(server, channel, nickname) # Infinite loop until disconnected while True: text = filter_input(irc.get_text()) print text if check_msg(text, channel) and "*snap*" in text.lower(): irc.send(channel, "Alexis...I don't feel so good...") irc.quit("disintegrated") if nickname == "spider_bot": nickname = "CAPTAIN_MARVEL" elif nickname == "CAPTAIN_MARVEL": nickname = "spider_bot" sleep(5) # Because quitting closes the connection with the server irc = IRC() irc.connect(server, channel, nickname) if check_msg(text, channel) and "goat" in text.lower(): with open("./static/battle_goat.txt", "r") as goat: lines = goat.readlines() for line in lines: irc.send(channel, line.strip("""\n""")) if check_msg(text, channel) and "pineapple" in text.lower(): with open("./static/pineapple.txt", "r") as pineapple: lines = pineapple.readlines() for line in lines: irc.send(channel, line.strip("""\n""")) if check_msg(text, channel)\ and ("tom brady" in text.lower() or "tb12" in text.lower() or "touchdown tommy" in text.lower()): irc.send(channel, "the GOAT") if check_msg(text, channel) and "spider_bot" in text.lower(): irc.send(channel, ":D") if check_msg(text, channel) and "the herd" in text.lower(): irc.send(channel, "ALL THE GOATS") if check_msg(text, channel) and "idea" in text.lower(): irc.send(channel, "it's gonna be YUUUGGEEE") if "QUIT" in text: irc.send(channel, "*mic drop*")
def bot_run(): channel = get_channel() server = get_server() nickname = "THANOS" irc = IRC() irc.connect(server, channel, nickname) # Infinite loop until disconnected while True: text = filter_input(irc.get_text(), nums=True) print text if check_msg(text, channel) and "imperfectly balanced" in text.lower(): irc.send(channel, "Let's fix that shall we... *snap*") elif check_msg(text, channel) and "perfectly balanced" in text.lower(): irc.send(channel, "As all things should be") if check_msg(text, channel) and "imperfectly balanced"[::-1]\ in text.lower(): irc.send(channel, "Let's fix that shall we... *snap*") elif check_msg(text, channel) and "perfectly balanced"[::-1]\ in text.lower(): irc.send(channel, "As all things should be"[::-1]) if check_msg(text, channel) and "fun" in text.lower(): irc.send( channel, "Fun isn't something one considers when balancing the universe" ) if check_msg(text, channel) and "you should have gone for the head"\ in text.lower(): irc.send(channel, "*snap*")
def main() -> None: """Main entrypoint of the ping example.""" # Parse the arguments and execute the chosen command options = parser.parse_args() # Create an IRC instance irc = IRC(options.server, options.port, options.user, options.nick, timeout=options.timeout, use_tls=options.use_tls) # Connect to the server irc.connect() # Join a channel irc.join("#bot-test") # Loop through all messages - current and future for message in irc.messages: # If someone's sent a message "ping" if isinstance(message, IRCMessage) and message.message == "ping": # Get the target of the message. If the target is the bot directly, # send the message to the author - else send it to the channel the message # was directed to target = message.author if message.target == "test" else message.target # Send "pong" irc.send_message(target, "pong")
def load_settings(self): file = open("settings", "rb") saved_data = load(file) file.close() for data in saved_data: server, channel, botnick = data[0], data[1], data[2] new_irc = IRC(server, channel, botnick) self.new_channel(new_irc)
def handler( *args, **kwargs): #Handle the client connection, do whatever you want here ID = args[0] client = args[1] IRC(client, ID) del webSocket.clients[ID] webSocket.log("INFO", "Connection with %s ended" % ID)
def __init__(self, info_filename): try: info = json.load(open(info_filename, "r")) self.share = Share(info) self.irc = IRC(self.share.HOST, self.share.PORT) except: print("\"info\" file not found or syntax error") traceback.print_exc() sys.exit(1)
def __init__(self): self.IRC = IRC() cmd.loadCusCommands() _thread.start_new_thread(twitch.threadFillOpList, ()) smugs.initSmugs() _thread.start_new_thread(twitch.threadOfflineMSG, (self.IRC, )) _thread.start_new_thread(twitch.threadGlobalMSG, (self.IRC, )) _thread.start_new_thread(smugs.threadCalcPoints, ()) print(config.userList) self.run()
def add_new_channel(self): new_channel_dialog = IRCDialog() if new_channel_dialog.exec_(): server = new_channel_dialog.server.text() channel = new_channel_dialog.channel.text() nickname = new_channel_dialog.nickname.text() if not server or not channel or not nickname: return new_irc = IRC(server, channel, nickname) self.irc_widget.new_channel(new_irc) self.update_actions()
def bot_run(): channel = get_channel() server = get_server() nickname = "test_bot" irc = IRC() irc.connect(server, channel, nickname) while True: text = filter_input(irc.get_text()) print text if check_msg(text, channel) and "test" in text.lower(): irc.send(channel, "Test successful!")
def main(): coordinator = Coordinator() coordinator.run_flag = True irc = IRC() bot = Bot(bot_account['usernm'], bot_account['pwd'], bot_account['channels'], bot_account['main_channel'] ) loop = asyncio.get_event_loop() loop.create_task(irc_bot_init_jobs(irc, bot, loop, coordinator)) loop.create_task(run_irc_bot(irc, bot, loop, coordinator)) loop.run_forever()
def init(): bot = IRC() bot.connect(config.hostname, config.port, config.nickname, config.username, config.realname, config.channel, use_ssl=config.ssl, use_proxy=config.proxy, proxy_host=config.proxy_host, proxy_port=config.proxy_port) driver = pluginDriver() driver.load_plugins("plugins") return bot, driver
def start_bot(self, ip, port, oauth, username, channel): irc = IRC() Admin.bot = TwitchBot((ip, port), oauth, username, channel) test_cmd = TestCmd() Admin.bot.set_commands([test_cmd]) Admin.bot.events.disconnected = self.bot_disconnected Admin.bot.events.connected = self.bot_connected Admin.bot.events.joined = lambda x: self.bot_user_joined(x) Admin.bot.events.parted = lambda x: self.bot_user_parted(x) Admin.bot.events.message_received = lambda x: self.bot_message_received( x.message, x.username) Admin.bot.events.socket_error = lambda exc, is_connected: self.bot_socket_error( exc, is_connected) Admin.bot.start()
def main(channelName, serverName): channel = channelName if channelName.startswith('#') else '#' + channelName server = serverName nickname = "guru_bot" irc = IRC() irc.connect(server, channel, nickname) while 1: messageObj = irc.get_text() print(messageObj.all) if messageObj.type == MessageTypes.MESSAGE and messageObj.message.startswith( nickname): message = messageObj.message answer = AskGuru(message[message.find(nickname) + len(nickname):]) for line in answer.split('\n'): irc.send(channel, line)
def main() -> None: """Main entrypoint of the minimal example.""" # Parse the arguments and execute the chosen command options = parser.parse_args() # Create an IRC instance irc = IRC(options.server, options.port, options.user, options.nick, timeout=options.timeout, use_tls=options.use_tls) # Connect to the server irc.connect() # Read the first message print(next(irc.messages))
def connect(self): conn = sqlite3.connect(self.config['db']) cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS channels (username text)') cursor.execute('SELECT username FROM channels') rows = cursor.fetchall() cursor.close() conn.close() channels = [row[0] for row in rows] channels = set(channels) channels.add('isabellesays') irc = IRC() irc.connect(self.config['server'], self.config['port'], channels, self.config['nick'], self.config['oauth']) self.irc = irc
def main(): # Setup logging logging.basicConfig(level=logging.INFO) # Initialize the config. Config.Init() # Initialize agent agent = Agent() # Initialize IRC irc = IRC(nickname=Config.conf()['botNickName']) irc.SetChannel(Config.conf()['channel']) irc.ResetGame() irc.SetAgent(agent) irc.run(hostname=Config.conf()['ircServer'], port=Config.conf()['ircSSLPort'], tls=True, tls_verify=True)
def __init__(self, address, oauth, username, channel): self.irc=IRC() self.oauth = oauth self.username = username self.channel = channel self.address = address self.events=Events() self.users = [] self.commands=[] self.messages = [] self.l = Lock() self.is_connected = False self.messages_sent = 0 self.last_sent = datetime.datetime.now() self.protocol = Protocol(self.irc, self) self.client = TwitchIRCClient(self.protocol, self.address, self.on_socket_error) self.transport=None
def edit_current_channel(self): current_connection = self.irc_widget.current_connection() edit_channel_dialog = IRCDialog("Edit channel", current_connection.server, current_connection.channel, current_connection.botnick) if edit_channel_dialog.exec_(): server = edit_channel_dialog.server.text() channel = edit_channel_dialog.channel.text() botnick = edit_channel_dialog.nickname.text() if not server or not channel or not botnick\ or server == current_connection.server\ and channel == current_connection.channel\ and botnick == current_connection.botnick: return self.irc_widget.remove_channel() edited_irc = IRC(server, channel, botnick) self.irc_widget.new_channel(edited_irc)
def __init__(self, config): self.config = config irc = IRC() irc.connect(config['server'], config['port'], [config['channel']], config['nick'], config['oauth']) self.irc = irc conn = sqlite3.connect('subs.db') cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS subs (username text, count integer)') cursor.execute('CREATE TABLE IF NOT EXISTS points (username text, count integer)') cursor.execute('CREATE TABLE IF NOT EXISTS votes (username text, option text, points integer)') cursor.close() conn.close() for option in config['options']: filename = 'counters/' + option.lower() + '.txt' try: f = open(filename, 'r') except: f = open(filename, 'w') f.write('0')
def emoji_bot(): channel = get_channel() server = get_server() nickname = "emoji_bot" irc = IRC() irc.connect(server, channel, nickname) # Implicitly render Emojibot help on every successful connection attempt emoji_bot_help(irc, channel) # Infinite loop until disconnected while True: text = filter_input(irc.get_text()) print text # Retrieve Emojibot help whenever "emoji_bot --help" is called if check_msg(text, channel) and "emoji_bot --help" in text.lower(): emoji_bot_help(irc, channel) # -------------------- Various emojis implemented --------------------- if check_msg(text, channel) and "*smiles*" in text.lower(): irc.send( channel, emoji.emojize(':smiley:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*winks*" in text.lower(): irc.send( channel, emoji.emojize(':wink:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*laughs*" in text.lower(): irc.send( channel, emoji.emojize(':joy:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*fistbombs*" in text.lower(): irc.send( channel, emoji.emojize(':punch:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*heart*" in text.lower(): irc.send( channel, emoji.emojize(':hearts:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*smirks*" in text.lower(): irc.send( channel, emoji.emojize(':smirk:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*sleeps*" in text.lower(): irc.send( channel, emoji.emojize(':zzz:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*cool*" in text.lower(): irc.send( channel, emoji.emojize(':sunglasses:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*cries*" in text.lower(): irc.send( channel, emoji.emojize(':cry:', use_aliases=True).encode("utf-8", "replace")) if check_msg(text, channel) and "*tongue*" in text.lower(): irc.send( channel, emoji.emojize(':stuck_out_tongue:', use_aliases=True).encode("utf-8", "replace")) # Secret mic_drop emoji not included in the emoji_bot_help if check_msg(text, channel) and "*mic drop*" in text.lower(): irc.send( channel, emoji.emojize(':microphone:', use_aliases=True).encode("utf-8", "replace"))
from ruamel.yaml import YAML from irc import IRC, User with open('config.yml', 'r') as fp: config = YAML().load(fp) logging.basicConfig(level=logging.DEBUG) logging.getLogger('lomond').setLevel(logging.WARNING) logging.getLogger('curious').setLevel(logging.WARNING) multio.init('trio') bot = Client(config['discord']['token']) bot.irc = IRC(config['irc']['host'], config['irc']['port'], autojoin=config['irc']['autojoin'], nick=config['irc'].get('nick'), bot=bot, config=config) @bot.irc.on('privmsg') async def privmsg_handler(channel: str, author: User, message: str): dest = bot.find_channel(config['discord']['broadcast_channel']) clean_message = message.replace('@', '@\u200b').replace( '`', '\N{MODIFIER LETTER GRAVE ACCENT}')[:1500] timestamp = datetime.datetime.utcnow().strftime('%H:%M:%S') forward = f'`[{timestamp}]` `[{channel}]` {author.nick} » {clean_message}' await dest.messages.send(forward) async def run():
def main(): irc = IRC() irc.connect(config.HOST, config.PORT, config.CHANNEL, config.NICK) skyline = Skyline(config.BRIDGE_IP) skyline.start() stream_room = Group('Stream Room', lights=[ 'Roo side table', 'Lunar side table', 'Desk Portrait Left', 'Desk Portrait Right' ]) _thread.start_new_thread(irc.fill_user_list, ()) while True: response = irc.receive() # If Twitch pings the bot, respond. irc.respond_to_ping(response) username, message = irc.parse_message(response) # Custom commands insta_com = Command('insta', response='Follow r00 on Instagram at www.instagram.com/user_r00') twitter_com = Command('twitter', response='Follow r00 on Twitter at www.twitter.com/user_r00') ping_com = Command('ping', response='Pong') lights_com = Command('lights', response='Control r00\'s lighting with !lights and a color. For example, "!lights purple" will set the room lights to purple! For a full list of colors use !lightcolors.') # irc.process_command(response) if message.strip() == '!ping': irc.chat(ping_com.response) # Socials if message.strip() == "!insta": irc.chat(insta_com.response) elif message.strip() == '!twitter': irc.chat(twitter_com.response) # Shoutouts elif message.strip().split(' ')[0] == "!so": streamer_long = message.strip().split(' ')[1] streamer_short = streamer_long.replace('@', '') irc.chat(f'If you\'re looking for more interesting content, ' f'go check out {streamer_long} at ' f'https://twitch.tv/{streamer_short} ! Drop them a ' f'follow to be notified when they go live.') elif message.strip() == '!crash': # Get a light and collect its current colors for later. light = skyline.lights['Roo side table'] hue, sat, bri = light.hue, light.saturation, light.brightness # Create temporary light to hold current settings. temp_color = Color('temp', hue=hue, sat=sat, bri=bri) skyline.set_color(stream_room.lights, 'red') sleep(3) skyline.set_color(stream_room.lights, temp_color) # Skyline elif message.strip() == '!lights': irc.chat(lights_com.response) elif message.strip() == '!lightcolors': message = 'Lights can be set to ' counter = 0 for color in skyline.colors: if counter < len(skyline.colors.keys()) - 1: message = f'{message}{skyline.colors[color].name}, ' counter += 1 else: message = f'{message} or {skyline.colors[color].name}.' irc.chat(message) elif message.strip().split(' ')[0] == "!lights": color = message.strip().split(' ')[1] if color in skyline.colors: skyline.set_color(stream_room.lights, color) else: irc.chat('Honestly, I have no idea what you want.') elif message.strip() == '!rainbow': skyline.rainbow(stream_room.lights) sleep(1)
#!/usr/bin/python # coding: utf-8 import os import sys import traceback sys.path += ("irc", ) from pluginDriver import pluginDriver from irc import IRC from auth import auth bot = IRC("irc.freenode.net", 6697, "phukbot", "phukj00", "phuk3r", use_ssl=1) bot.raw("MODE phukbot +B") bot.join("#nopezor") driver = pluginDriver() driver.load_plugins("plugins", bot) authentication = auth(bot) authentication.auth_levels['phukd'] = 10 while bot.connected == 1: buffer = bot.receive() if not buffer: continue for buf in buffer: if not buf: continue (tmp, auth_level) = authentication.check(bot, buf)
volunteering_regexes = [ r'^(I think )?(that )?We should (.*)$', r'^Why don\'t we (.*)$', r'^Tardis should (.*)$', r'^Someone (should|needs to) (.*)$', r'^(Please )?(Can|Could) someone (.*)$', r'^It would be good if (.*)$' ] listing_regexes = [ r'^ *what have i (volunteered for|agreed to|let myself in for)', r'^ *omgwtflol' ] irc = IRC( host=config['IRC']['host'], port=config['IRC']['port'], nick=config['IRC']['nick'], channel=config['IRC']['channel']) def main(): irc.channel_message_received_callback = channel_message irc.start_connection() def channel_message(sender, channel, message): if config['System']['debug']: logger.debug("[{0}] {1}: {2}".format(channel, sender, message)) for regex in volunteering_regexes: if re.match(regex, message, re.IGNORECASE): db.insert_message(nick=sender, message=message, channel=channel) num_recorded_messages = db.count_user_messages(nick=sender, channel=channel) pluralstring = 's'
def generate(self): """ Creates the input for each reaction, runs them, and tests for success. If successful, it creates the barrier and product objects. It also then does the conformational search, and finally, the hindered rotor scans. To make the code the most efficient, all of these happen in parallel, in a sense that the jobs are not waiting for each other. E.g., one reaction can still be in the stage of TS search, while the other can be already at the hindered rotor scan. This way, all cores are occupied efficiently. The switching between the various stages are done via the reac_ts_done variable. 0: initiates the TS search 1: checks barrier height and errors in TS, and initiates normal mode displacement test, start the irc calculations 2: submits product optimization 3: submit the frequency calculation 4: do the optimization of the ts and the products 5: follow up on the optimizations 6: finalize calculations, check for wrong number of negative frequencies """ if len(self.species.reac_inst) > 0: alldone = 1 else: alldone = 0 while alldone: for index, instance in enumerate(self.species.reac_inst): obj = self.species.reac_obj[index] instance_name = obj.instance_name # START REATION SEARCH if self.species.reac_ts_done[ index] == 0 and self.species.reac_step[index] == 0: #verify after restart if search has failed in previous kinbot run status = self.qc.check_qc(instance_name) if status == 'error' or status == 'killed': logging.info( '\tRxn search failed (error or killed) for {}'. format(instance_name)) self.species.reac_ts_done[index] = -999 if self.species.reac_ts_done[ index] == 0: # ts search is ongoing if obj.scan == 0: #don't do a scan of a bond if self.species.reac_step[index] == obj.max_step + 1: status = self.qc.get_qc_freq( instance_name, self.species.natom)[0] if status == 0: self.species.reac_ts_done[index] = 1 elif status == -1: logging.info( '\tRxn search failed for {}'.format( instance_name)) self.species.reac_ts_done[index] = -999 else: self.species.reac_step[ index] = reac_family.carry_out_reaction( obj, self.species.reac_step[index]) else: # do a bond scan if self.species.reac_step[ index] == self.par.par['scan_step'] + 1: status = self.qc.get_qc_freq( instance_name, self.species.natom)[0] if status == 0: self.species.reac_ts_done[index] = 1 elif status == -1: logging.info( '\tRxn search failed for {}'.format( instance_name)) self.species.reac_ts_done[index] = -999 else: if self.species.reac_step[index] == 0: self.species.reac_step[ index] = reac_family.carry_out_reaction( obj, self.species.reac_step[index]) elif self.species.reac_step[index] > 0: status = self.qc.check_qc(instance_name) if status == 'error' or status == 'killed': logging.info( '\tRxn search failed for {}'.format( instance_name)) self.species.reac_ts_done[index] = -999 else: err, energy = self.qc.get_qc_energy( instance_name) if err == 0: self.species.reac_scan_energy[ index].append(energy) if len(self.species. reac_scan_energy[index]) > 1: if self.species.reac_scan_energy[ index][ -1] < self.species.reac_scan_energy[ index][-2]: self.species.reac_step[ index] = self.par.par[ 'scan_step'] self.species.reac_step[ index] = reac_family.carry_out_reaction( obj, self.species.reac_step[index]) elif self.species.reac_ts_done[index] == 1: status = self.qc.check_qc(instance_name) if status == 'running': continue elif status == 'error': logging.info( '\tRxn search failed (gaussian error) for {}'. format(instance_name)) self.species.reac_ts_done[index] = -999 else: #check the barrier height: if self.species.reac_type[ index] == 'R_Addition_MultipleBond': sp_energy = self.qc.get_qc_energy( str(self.species.chemid) + '_well_mp2')[1] barrier = (self.qc.get_qc_energy(instance_name)[1] - sp_energy) * constants.AUtoKCAL else: sp_energy = self.qc.get_qc_energy( str(self.species.chemid) + '_well')[1] barrier = (self.qc.get_qc_energy(instance_name)[1] - sp_energy) * constants.AUtoKCAL if barrier > self.par.par['barrier_threshold']: logging.info( '\tRxn barrier too high ({val}) for {name}'. format(val=barrier, name=instance_name)) self.species.reac_ts_done[index] = -999 else: obj.irc = IRC( obj ) #TODO: this doesn't seem like a good design irc_status = obj.irc.check_irc() if 0 in irc_status: # No IRC started yet, start the IRC now logging.info( '\tStarting IRC calculations for {}'. format(instance_name)) obj.irc.do_irc_calculations() elif irc_status[0] == 'running' or irc_status[ 1] == 'running': continue else: #IRC's have succesfully finished, have an error or were killed, in any case #read the geometries and try to make products out of them #verify which of the ircs leads back to the reactant, if any prod = obj.irc.irc2stationary_pt() if prod == 0: logging.info( '\t\tNo product found for {}'.format( instance_name)) self.species.reac_ts_done[index] = -999 else: #IRC's are done obj.products = prod obj.product_bonds = prod.bond self.species.reac_ts_done[index] = 2 elif self.species.reac_ts_done[index] == 2: #identify bimolecular products and wells fragments = obj.products.start_multi_molecular() obj.products = [] for i, frag in enumerate(fragments): obj.products.append(frag) self.qc.qc_opt(frag, frag.geom) self.species.reac_ts_done[index] = 3 elif self.species.reac_ts_done[index] == 3: #wait for the optimization to finish err = 0 for st_pt in obj.products: chemid = st_pt.chemid orig_geom = copy.deepcopy(st_pt.geom) e, st_pt.geom = self.qc.get_qc_geom( str(st_pt.chemid) + '_well', st_pt.natom) if e < 0: logging.info( '\tProduct optimization failed for {}, product {}' .format(instance_name, st_pt.chemid)) self.species.reac_ts_done[index] = -999 err = -1 elif e != 0: err = -1 else: e2, st_pt.energy = self.qc.get_qc_energy( str(st_pt.chemid) + '_well') e2, st_pt.zpe = self.qc.get_qc_zpe( str(st_pt.chemid) + '_well') st_pt.bond_mx() st_pt.characterize() st_pt.calc_chemid() if chemid != st_pt.chemid: #product was optimized to another structure, give warning and remove this reaction logging.info( '\tProduct optimizatied to other structure for {}, product {} to {}' .format(instance_name, chemid, st_pt.chemid)) self.species.reac_ts_done[index] = -999 err = -1 if err == 0: self.species.reac_ts_done[index] = 4 elif self.species.reac_ts_done[index] == 4: # Do the TS and product optimization #make a stationary point object of the ts bond_mx = np.zeros( (self.species.natom, self.species.natom), dtype=int) for i in range(self.species.natom): for j in range(self.species.natom): bond_mx[i][j] = max(self.species.bond[i][j], obj.product_bonds[i][j]) err, geom = self.qc.get_qc_geom(instance_name, self.species.natom) ts = StationaryPoint(instance_name, self.species.charge, self.species.mult, atom=self.species.atom, geom=geom, wellorts=1) err, ts.energy = self.qc.get_qc_energy(instance_name) err, ts.zpe = self.qc.get_qc_zpe(instance_name) ts.bond = bond_mx ts.find_cycle() ts.find_conf_dihedral() obj.ts = ts #do the ts optimization obj.ts_opt = Optimize(obj.ts, self.par, self.qc) obj.ts_opt.do_optimization() #do the products optimizations for st_pt in obj.products: #check for products of other reactions that are the same as this product #in the case such products are found, use the same Optimize object for both new = 1 for i, inst_i in enumerate(self.species.reac_inst): if not i == index: obj_i = self.species.reac_obj[i] if self.species.reac_ts_done[i] > 3: for j, st_pt_i in enumerate( obj_i.products): if st_pt_i.chemid == st_pt.chemid: if len(obj_i.prod_opt) > j: prod_opt = obj_i.prod_opt[j] new = 0 break if new: prod_opt = Optimize(st_pt, self.par, self.qc) prod_opt.do_optimization() obj.prod_opt.append(prod_opt) self.species.reac_ts_done[index] = 5 elif self.species.reac_ts_done[index] == 5: #check up on the TS and product optimizations opts_done = 1 fails = 0 #check if ts is done if not obj.ts_opt.shir == 1: opts_done = 0 obj.ts_opt.do_optimization() if obj.ts_opt.shigh == -999: fails = 1 for pr_opt in obj.prod_opt: if not pr_opt.shir == 1: opts_done = 0 pr_opt.do_optimization() if pr_opt.shigh == -999: fails = 1 if fails: self.species.reac_ts_done[index] = -999 elif opts_done: self.species.reac_ts_done[index] = 6 elif self.species.reac_ts_done[index] == 6: #Finilize the calculations #continue to PES search in case a new well was found if self.par.par['pes']: #verify if product is monomolecular, and if it is new if len(obj.products) == 1: st_pt = obj.prod_opt[0].species chemid = st_pt.chemid energy = st_pt.energy well_energy = self.species.energy new_barrier_threshold = self.par.par[ 'barrier_threshold'] - ( energy - well_energy) * constants.AUtoKCAL dir = os.path.dirname(os.getcwd()) jobs = open(dir + '/chemids', 'r').read().split('\n') jobs = [ji for ji in jobs] if not str(chemid) in jobs: #this well is new, add it to the jobs while 1: try: #try to open the file and write to it pes.write_input( self.par, obj.products[0], new_barrier_threshold, dir) f = open(dir + '/chemids', 'a') f.write('{}\n'.format(chemid)) f.close() break except IOError: #wait a second and try again time.sleep(1) pass #check for wrong number of negative frequencies neg_freq = 0 for st_pt in obj.products: if any([fi < 0. for fi in st_pt.reduced_freqs]): neg_freq = 1 if any([fi < 0. for fi in obj.ts.reduced_freqs[1:]]): neg_freq = 1 if neg_freq: logging.info('\tFound negative frequency for ' + instance_name) self.species.reac_ts_done[index] = -999 else: #the reaction search is finished self.species.reac_ts_done[ index] = -1 # this is the success code # write a temporary pes input file # remove old xval and im_extent files if os.path.exists('{}_xval.txt'.format( self.species.chemid)): os.remove('{}_xval.txt'.format( self.species.chemid)) if os.path.exists('{}_im_extent.txt'.format( self.species.chemid)): os.remove('{}_im_extent.txt'.format( self.species.chemid)) postprocess.createPESViewerInput( self.species, self.qc, self.par) alldone = 1 for index, instance in enumerate(self.species.reac_inst): if any(self.species.reac_ts_done[i] >= 0 for i in range(len(self.species.reac_inst))): alldone = 1 break else: alldone = 0 # write a small summary while running wr = 1 if wr: f_out = open('kinbot_monitor.out', 'w') for index, instance in enumerate(self.species.reac_inst): f_out.write('{}\t{}\t{}\n'.format( self.species.reac_ts_done[index], self.species.reac_step[index], self.species.reac_obj[index].instance_name)) f_out.close() time.sleep(1) s = [] for index, instance in enumerate(self.species.reac_inst): obj = self.species.reac_obj[index] instance_name = obj.instance_name # Write a summary on the combinatorial exploration if 'combinatorial' in instance_name: s.append('NAME\t' + instance_name) # Write the bonds that were broken and formed s.append('BROKEN_BONDS\t' + '\t'.join('[{}, {}]'.format(re[0], re[1]) for re in obj.reac)) s.append('FORMED_BONDS\t' + '\t'.join('[{}, {}]'.format(pr[0], pr[1]) for pr in obj.prod)) # Populate the ts_bond_lengths dict with the values # of this reaction if self.species.reac_ts_done[index] == -1: for i in range(self.species.natom - 1): for j in range(i + 1, self.species.natom): if self.species.bond[i][j] != obj.product_bonds[i][ j]: if (self.species.bond[i][j] == 0 or obj.product_bonds[i][j] == 0): syms = [] syms.append(self.species.atom[i]) syms.append(self.species.atom[j]) syms = ''.join(sorted(syms)) dist = np.linalg.norm(obj.ts.geom[i] - obj.ts.geom[j]) s.append('TS_BOND_LENGTHS\t{}\t{}'.format( syms, dist)) # write the expected inchis s.append('EXPECTED_INCHIS\t' + '\t'.join(inchi for inchi in obj.prod_inchi)) # get the inchis the reaction found if self.species.reac_ts_done[index] == -1: inchis = obj.get_final_inchis() s.append('FOUND_INCHIS\t' + '\t'.join(inchis)) s.append('\n') with open('combinatorial.txt', 'w') as f: f.write('\n'.join(s) + '\n') logging.info("Reaction generation done!")
#!/usr/bin/env python from irc import IRC import os import re import socket import sys irc = IRC() chat = irc.getConnection() def send(command): chat.send(irc.make_command(command)) def join(room): send('JOIN #%s' % room) send('PRIVMSG #%s :Kappa /' % room) def watch(): buffer = '' while True: buffer = buffer + chat.recv(1024).decode('UTF-8') temp = str.split(buffer, '\n') buffer = temp.pop() for line in temp: line = str.rstrip(line) line = str.split(line)
def main() -> None: """Main entrypoint of the bot example.""" # Parse the arguments and execute the chosen command options = parser.parse_args() logger = logging.getLogger(__name__) # Create an IRC instance irc = IRC( options.server, options.port, options.user, options.nick, logger=logger, timeout=options.timeout, use_tls=options.use_tls ) # Connect to the server irc.connect() # Join a channel irc.join("#bot-test") # Loop through all messages - current and future for message in irc.messages: # If someone's sent a message if isinstance(message, IRCMessage): # Get the target of the message. If the target is the bot directly, # send the message to the author - else send it to the channel the message # was directed to target = message.author if message.target == "test" else message.target # Match commands targeted to our bot match = re.match("bot: ([^ ]+)( (.*))?", message.message) if not match: continue # Extract command and optional parameters from the message command, _, parameter = match.groups() if command == "about": # Send about message irc.send_message(target, "I'm a simple example bot using irc-python version {}.".format(irc.version)) irc.send_message(target, "Read more about me on https://github.com/AlexGustafsson/irc-python.") elif command == "help": # Send help message irc.send_message(target, "You invoke me by sending 'bot: <command> <parameters>'") elif command == "torvalds": quotes = [ "Talk is cheap. Show me the code.", "Intelligence is the ability to avoid doing work, yet getting the work done.", "Given enough eyeballs, all bugs are shallow." ] # Send a random Linus Torvalds quote irc.send_message(target, random.choice(quotes)) # nosec elif command == "time": # Send the local time irc.send_message(target, datetime.now().strftime("%H:%M:%S")) elif command == "sum": # Calculate the sum of the parameters try: result = sum([int(number) for number in parameter.split(" ")]) irc.send_message(target, str(result)) except ValueError: logger.error("Got bad parameters for sum: %s", parameter) irc.send_message(target, "Unable to sum the parameters") else: # Handle unknown commands irc.send_message(target, "Sorry, I'm not sure what you want me to do")
#!/usr/bin/env python from irc import IRC from xmlrpc.server import AsyncXMLRPCServer if __name__ == '__main__': server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True, logRequests=False) server.add_handler(IRC()) print 'Running on %s:%s' % tuple(map(str, server.server_address)) try: server.serve_forever() except KeyboardInterrupt: print 'Exiting'
def main() -> None: """Main entrypoint of the bot.""" # Configure the default logging format logging.basicConfig(format="[%(asctime)s] [%(levelname)-5s] %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S") # Create an argument parser for parsing CLI arguments parser = ArgumentParser( description= "An IRC bot providing sentiment analysis and reactions using ASCII emojis" ) # Add parameters for the server connection parser.add_argument("-s", "--server", required=True, type=str, help="The server to connect to") # Add optional parameters for the server connection parser.add_argument("-p", "--port", default=6697, type=int, help="The port to connect to") parser.add_argument("--use-tls", default=True, type=bool, help="Whether or not to use TLS") parser.add_argument("-t", "--timeout", default=300, type=float, help="Connection timeout in seconds") # Add optional parameters for authentication etc. parser.add_argument( "-u", "--user", default="sentiment-bot", help="Username to use when connecting to the IRC server") parser.add_argument("-n", "--nick", default="sentiment-bot", help="Nick to use when connecting to the IRC server") parser.add_argument( "-g", "--gecos", default= "Sentiment Bot v1.0.2 (github.com/AlexGustafsson/irc-sentiment-bot)") parser.add_argument("-c", "--channel", required=True, action='append', help="Channel to join. May be used more than once") # Parse the arguments options = parser.parse_args() # Create an IRC connection irc = IRC(options.server, options.port, options.user, options.nick, timeout=options.timeout, use_tls=options.use_tls) irc.connect() # Connect to specified channels for channel in options.channel: irc.join(channel) # The last analyzed result lastMessageValence = None # Handle all messages for message in irc.messages: if not isinstance(message, IRCMessage): continue target = message.author if message.target == options.nick else message.target if message.message == "{}: help".format(options.nick): irc.send_message( target, "I perform a simple sentiment analysis on your messages and respond with emojis" ) irc.send_message( target, "You can debug the sentiment analysis of the last message like so:" ) irc.send_message(target, "{}: debug".format(options.nick)) elif message.message == "{}: debug".format(options.nick): if lastMessageValence is not None: compound = "compound: {}".format( lastMessageValence["compound"]) debug = ", ".join([ "'{}': {}".format(text, valence) for text, valence in lastMessageValence["debug"] ]) irc.send_message(target, "{}. {}".format(compound, debug)) else: analyzer = SentimentIntensityAnalyzer() scores = analyzer.polarity_scores(message.message) if scores["compound"] >= 0.6: irc.send_message(target, random.choice(positives)) lastMessageValence = scores elif scores["compound"] <= -0.6: irc.send_message(target, random.choice(negatives)) lastMessageValence = scores
from irc import IRC from PyQt5.QtCore import * from PyQt5.QtWidgets import * from requests import Session from threading import Thread from time import sleep from irc import IRC import datetime import random import hashlib username = "******" oauth = "oauth:efhn2jfl093dyrdv94rd91vad3zdoy" channel = "thiseguy" chat1 = IRC(channel, username, oauth) chat1.connect() userlist = [] colorid = [] app = QApplication([]) text_area = QPlainTextEdit() text_area.setFocusPolicy(Qt.NoFocus) message = QLineEdit() layout = QVBoxLayout() layout.addWidget(text_area) layout.addWidget(message) window = QWidget() window.setLayout(layout) window.show() new_messages = []