def run(self, init_irc, send_select=False): # print self.irc_client # print self.irc_client.command_handler.session_view if send_select: if self.irc_client and self.irc_client.command_handler.session_view: if not self.session_view: self.session_view = self.irc_client.command_handler.session_view print 'session view' print self.session_view # print 'active view' # print self.window.active_view() if self.session_view: for region in self.session_view.sel(): print '%d - %d' % (region.begin(), region.end()) if self.irc_client.command_handler.tgt_nick: print "got to here" helpers.msg(self.irc_client, self.irc_client.command_handler.tgt_nick, 'SELECTION[%d,%d]' % (region.begin(), region.end())) # else: # print 'not in active view!' else: if init_irc: self.init() else: # if not self.irc_client and not self.irc_thread: # print 'oh nos! initing irc session' # self.init() self.window.show_quick_panel(['Share active view (default)', 'Share other view...'], self.view_to_share)
def updateMood(self): me = self.mainwindow.profile() try: helpers.msg(self.cli, "#pesterchum", "MOOD >%d" % (me.mood.value())) except socket.error: self.setConnectionBroken()
def updateColor(self): me = self.mainwindow.profile() for h in self.mainwindow.convos.keys(): try: helpers.msg(self.cli, h, "COLOR >%s" % (self.mainwindow.profile().colorcmd())) except socket.error: self.setConnectionBroken()
def welcome(self, server, nick, msg): self.parent.setConnected() mychumhandle = self.mainwindow.profile().handle mymood = self.mainwindow.profile().mood.value() if not self.mainwindow.config.lowBandwidth(): helpers.join(self.client, "#pesterchum") helpers.msg(self.client, "#pesterchum", "MOOD >%d" % (mymood))
def reply_to(self, replytext): if self.is_private_message: target = self.sender else: target = self.source msgtosend = (self.sender + ": " if not self.is_private_message else "") + replytext helpers.msg(self.client, target, msgtosend)
def privmsg(self, nick, chan, msg): msg = msg.decode() match = re.match('\!say (.*)', msg) if match: to_say = match.group(1).strip() print('Saying, "%s"' % to_say) helpers.msg(self.client, chan, to_say)
def privmsg(self, nick, chan, msg): actual_nick = nick.split("!")[0] contact_channel = self.channel_cache.get(chan, None) if not contact_channel or not msg.startswith("PanoptaOutage"): return try: msg = msg.split(" ", 1)[1] except: return contact = contact_channel.contact customer = contact.customer outages = list(customer.active_outages) self.log.info("received message from contact:customer %d:%d" % (contact.id, customer.id)) # reset the timeout so they stay connected 60 seconds longer self.client.started = time.time() msg = msg.encode("utf-8") action, responses, extra = CS.outage_respond(chan, msg, outages=outages) if action == "outage_log": self.log.info("writing to outage log") log_msg, outages = extra log_msg = "%s from irc %s: \"%s\"" % (actual_nick, self.server, log_msg) for outage in outages: outage.log(log_msg) for response in responses: helpers.msg(self.client, chan, response) time.sleep(1)
def tryBotCommand(self, prefix, dest, msg): """ tests a command to see if its a command for the bot, returns True and calls self.processBotCommand(cmd, sender) if its is. """ logging.debug("tryBotCommand('%s' '%s' '%s')" % (prefix, dest, msg)) if dest == self.client.nick: dest = parse_nick(prefix)[0] elif msg.startswith(self.client.nick): msg = msg[len(self.client.nick)+1:] else: return False msg = msg.strip() parts = msg.split(' ', 1) command = parts[0] arg = parts[1:] try: self.command_handler.run(command, prefix, dest, *arg) except CommandError as e: helpers.msg(self.client, dest, str(e)) return True
def fetch_note(self, chan, key): db = anydbm.open(config.get('yamms', 'notes_db'), 'r') key = ''.join(ch for ch in key if ch not in set(string.punctuation)).lower() if key in db: note = db[key] helpers.msg(self.client, chan, "%s: %s" % (key, note)) db.close()
def _parse_cmd_pb_add(self, hostmask, chan, cmd): logging.info('s! %s %s %s' % (hostmask, chan, cmd)) m = re.match('^\s*(\S+)\s+(\S+)\s*$', cmd, re.UNICODE) if not m: helpers.msg(self.cli, chan, 'Usage: !a(dd) contact <number|email>') return nickname = m.group(1) email = None number = None if '@' in m.group(2): email = m.group(2) else: number = m.group(2) self.sms900.queue_event( 'ADD_PB_ENTRY', { 'hostmask': hostmask, 'nickname': nickname, 'email': email, 'number': number })
def main(): logging.basicConfig(level=logging.DEBUG) cli = IRCClient(MyHandler, host=HOST, port=PORT, nick=NICK)#,connect_cb=connect_cb) conn = cli.connect() i = 0 while True: if i < 1000000: i+=1 if i == 1000: print 'joining' helpers.join(cli, CHANNEL) if i == 1000000: print 'joining' helpers.join(cli, CHANNEL) helpers.msg(cli, CHANNEL, 'connected') i+=1 try: item = status_queue.get(False) print str(item.author.screen_name) if str(item.author.screen_name) != NICK: helpers.msg(cli, CHANNEL, str(item.author.screen_name)+' -- '+str(item.text)) api.update_status(str(item.author.screen_name)+' -- '+str(item.text)) except: pass conn.next() ## python 2
def privmsg(self, nick, chan, msg): """ handle msgs """ nick = nick[:nick.index("!")] modmsg = self.gen_modmsg(nick, msg) if modmsg is not None: helpers.msg(self.client, chan, modmsg)
def tryBotCommand(self, prefix, dest, msg): """ tests a command to see if its a command for the bot, returns True and calls self.processBotCommand(cmd, sender) if its is. """ logging.debug("tryBotCommand('%s' '%s' '%s')" % (prefix, dest, msg)) if dest == self.client.nick: dest = parse_nick(prefix)[0] elif msg.startswith(self.client.nick): msg = msg[len(self.client.nick) + 1:] else: return False msg = msg.strip() parts = msg.split(' ', 1) command = parts[0] arg = parts[1:] try: self.command_handler.run(command, prefix, dest, *arg) except CommandError as e: helpers.msg(self.client, dest, str(e)) return True
def privmsg(self, nick, chan, msg): msg_parts = msg.split(":") if (chan == BOT_CHANNEL and len(msg_parts) > 0 and msg_parts[0] == BOT_NICK): command = msg_parts[1].strip() # Show the available categories. if command == 'categories': for key in sorted(self.crowdmap.categories): helpers.msg(self.client, chan, "%s. %s" % (key, self.crowdmap.categories[key])) # Add a pin to the map. else: commands = command.split(' ') tags = [] tweet_id = commands[0] commands = commands[1:] command_index = 0 in_tags = True while in_tags and command_index < len(commands): command = commands[command_index] if command[0] == '#': tags.append(command[1:]) else: in_tags = False command_index += 1 self.crowdmap.add_tweet(Twitter.get_tweet(tweet_id), tags, ' '.join(commands[(command_index-1):]))
def privmsg(self, nick, chan, msg): try: msg = msg.decode('utf-8') except UnicodeDecodeError: msg = msg.decode('iso-8859-1', 'ignore') # display msg, do other stuff if len(msg) == 0: return # silently ignore CTCP if msg[0] == '\x01': handle = nick[0:nick.find("!")] logging.warning("---> recv \"CTCP %s :%s\"" % (handle, msg[1:-1])) if msg[1:-1] == "VERSION": helpers.ctcp_reply(self.parent.cli, handle, "VERSION", "Pesterchum %s" % (_pcVersion)) elif msg[1:-1].startswith("NOQUIRKS") and chan[0] == "#": op = nick[0:nick.find("!")] self.parent.quirkDisable.emit(chan, msg[10:-1], op) return handle = nick[0:nick.find("!")] if chan != "#pesterchum": # We don't need anywhere near that much spam. logging.info("---> recv \"PRIVMSG %s :%s\"" % (handle, msg)) if chan == "#pesterchum": # follow instructions if msg[0:6] == "MOOD >": try: mood = Mood(int(msg[6:])) except ValueError: mood = Mood(0) self.parent.moodUpdated.emit(handle, mood) elif msg[0:7] == "GETMOOD": mychumhandle = self.mainwindow.profile().handle mymood = self.mainwindow.profile().mood.value() if msg.find(mychumhandle, 8) != -1: helpers.msg(self.client, "#pesterchum", "MOOD >%d" % (mymood)) elif chan[0] == '#': if msg[0:16] == "PESTERCHUM:TIME>": self.parent.timeCommand.emit(chan, handle, msg[16:]) else: self.parent.memoReceived.emit(chan, handle, msg) else: # private message # silently ignore messages to yourself. if handle == self.mainwindow.profile().handle: return if msg[0:7] == "COLOR >": colors = msg[7:].split(",") try: colors = [int(d) for d in colors] except ValueError: colors = [0, 0, 0] color = QtGui.QColor(*colors) self.parent.colorUpdated.emit(handle, color) else: self.parent.messageReceived.emit(handle, msg)
def get_karma(self, chan, data): m = re.match(r'^(\w+)$', data.strip()) if m: db = anydbm.open(config.get('yamms', 'karma_db'), 'c') key = ''.join(ch for ch in m.group(1) if ch not in set(string.punctuation)).lower() if key in db: helpers.msg(self.client, chan, "%s has %s karmas." % (key, db[key]))
def announce(self,nick,chan,msg): if authed(self,nick,chan): if msg not in TOPIC_CHANS: TOPIC_CHANS.append(msg) config.set('IRC','announce',','.join(TOPIC_CHANS)) helpers.msg(self.client,chan,'%s: OK, I will announce status changes in %s'%(nick,msg)) else: helpers.msg(self.client,chan,'%s: Um...I am *already* announcing status changes in %s...'%(nick,msg))
def startConvo(self, handle, initiated): h = str(handle) try: helpers.msg(self.cli, h, "COLOR >%s" % (self.mainwindow.profile().colorcmd())) if initiated: helpers.msg(self.cli, h, "PESTERCHUM:BEGIN") except socket.error: self.setConnectionBroken()
def updateColor(self): #logging.debug("irc updateColor (outgoing)") me = self.mainwindow.profile() for h in list(self.mainwindow.convos.keys()): try: helpers.msg(self.cli, h, "COLOR >%s" % (self.mainwindow.profile().colorcmd())) except socket.error: self.setConnectionBroken()
def handle(self, message): params = message.params.split(" ", 1) if len(params) != 2: self.replytoinvalidparams(message) else: target = params[0] msg = params[1] helpers.msg(message.client, target, msg)
def del_op(self,nick,chan,msg): if authed(self,nick,chan): if msg in AUTHD: AUTHD.remove(msg) config.set('IRC','authed_users',','.join(AUTHD)) helpers.msg(self.client,chan,'%s: OK, I removed %s as a bot operator'%(nick,msg)) else: helpers.msg(self.client,chan,'%s: Um...%s is not a bot operator...'%(nick,msg))
def startConvo(self, handle, initiated): h = unicode(handle) try: if initiated: helpers.msg(self.cli, h, "PESTERCHUM:BEGIN") helpers.msg(self.cli, h, "COLOR >%s" % (self.mainwindow.profile().colorcmd())) except socket.error: self.setConnectionBroken()
def deannounce(self,nick,chan,msg): if authed(self,nick,chan): if msg in TOPIC_CHANS: TOPIC_CHANS.remove(msg) config.set('IRC','announce',','.join(TOPIC_CHANS)) helpers.msg(self.client,chan,'%s: OK, I will stop announcing status changes in %s'%(nick,msg)) else: helpers.msg(self.client,chan,'%s: Um...I am not announcing status changes in %s...'%(nick,msg))
def privmsg(self, nick, chan, msg): msg = msg.decode() match = re.match("\!say (.*)", msg) if match: to_say = match.group(1).strip() # print('Saying, "%s"' % to_say) # helpers.msg(self.client, chan, to_say) print("self " + " nick " + nick + " chan " + chan + " msg " + msg) helpers.msg(self.client, chan, "self " + " nick " + nick + " chan " + chan + " msg " + msg)
def welcome(self, server, nick, msg): self.parent.setConnected() mychumhandle = self.mainwindow.profile().handle mymood = self.mainwindow.profile().mood.value() if not self.mainwindow.config.lowBandwidth(): from time import sleep sleep(0.5) # To prevent TLS from dying </3 helpers.join(self.client, "#pesterchum") helpers.msg(self.client, "#pesterchum", "MOOD >%d" % (mymood))
def list(self, sender, dest, arg=None): if arg: commands = AuthEntry.getForUser(arg) else: commands = AuthEntry.getAll() for command in commands: helpers.msg(self.client, dest, "%s: %s" % (command.user, command.command)) helpers.msgOK(self.client, dest, sender)
def join(self, prefix, arg): log.info('join %s %s' % (prefix, arg)) name = parse_name(prefix)[0] msgs = TellMessage.getForUser(name, arg) for msg in msgs: helpers.msg(self.client, arg, "%s: %s said to tell you %s" % (msg.to_user, msg.from_user, msg.msg)) db.session.delete(msg) db.session.commit()
def part(self,nick,chan,msg): if authed(self,nick,chan): if msg in CHANS: CHANS.remove(msg) config.set('IRC','channels',','.join(CHANS)) helpers.part(cli, msg) helpers.msg(self.client,chan,'%s: OK, I parted %s'%(nick,msg)) else: helpers.msg(self.client,chan,'%s: Um...I am not in %s...'%(nick,msg))
def privmsg(self, nick, chan, msg): try: msg = msg.decode('utf-8') except UnicodeDecodeError: msg = msg.decode('iso-8859-1', 'ignore') # display msg, do other stuff if len(msg) == 0: return # Notice IRC /me (The CTCP kind) if msg[0:8] == '\x01ACTION ': msg = '/me' + msg[7:-1] # silently ignore the rest of the CTCPs if msg[0] == '\x01': handle = nick[0:nick.find("!")] logging.info("---> recv \"CTCP %s :%s\"" % (handle, msg[1:-1])) if msg[1:-1] == "VERSION": helpers.ctcp_reply(self.parent.cli, handle, "VERSION", "Pesterchum %s" % (_pcVersion)) elif msg[1:-1].startswith("NOQUIRKS") and chan[0] == "#": op = nick[0:nick.find("!")] self.parent.quirkDisable.emit(chan, msg[10:-1], op) return handle = nick[0:nick.find("!")] logging.info("---> recv \"PRIVMSG %s :%s\"" % (handle, msg)) if chan == "#pesterchum": # follow instructions if msg[0:6] == "MOOD >": try: mood = Mood(int(msg[6:])) except ValueError: mood = Mood(0) self.parent.moodUpdated.emit(handle, mood) elif msg[0:7] == "GETMOOD": mychumhandle = self.mainwindow.profile().handle mymood = self.mainwindow.profile().mood.value() if msg.find(mychumhandle, 8) != -1: helpers.msg(self.client, "#pesterchum", "MOOD >%d" % (mymood)) elif chan[0] == '#': if msg[0:16] == "PESTERCHUM:TIME>": self.parent.timeCommand.emit(chan, handle, msg[16:]) else: self.parent.memoReceived.emit(chan, handle, msg) else: # private message # silently ignore messages to yourself. if handle == self.mainwindow.profile().handle: return if msg[0:7] == "COLOR >": colors = msg[7:].split(",") try: colors = [int(d) for d in colors] except ValueError: colors = [0,0,0] color = QtGui.QColor(*colors) self.parent.colorUpdated.emit(handle, color) else: self.parent.messageReceived.emit(handle, msg)
def welcome(self, server, nick, msg): self.parent.setConnected() helpers.join(self.client, "#pesterchum") mychumhandle = self.mainwindow.profile().handle mymood = self.mainwindow.profile().mood.value() helpers.msg(self.client, "#pesterchum", "MOOD >%d" % (mymood)) chums = self.mainwindow.chumList.chums self.getMood(*chums)
def _parse_cmd_reindex(self, hostmask, chan, cmd): logging.info('!r %s, %s, %s' % (hostmask, chan, cmd)) m = re.match('^\s*$', cmd, re.UNICODE) if not m: helpers.msg(self.cli, chan, 'Usage: !r(eindex all)') return self.sms900.queue_event('REINDEX_ALL', {})
def google(self, chan, data): search = requests.get("http://ajax.googleapis.com/ajax/services/search/web", params={"v": "1.0", "q": data}) res = json.loads(search.text) if len(res["responseData"]["results"]) > 0: url = res["responseData"]["results"][0]["url"] title = res["responseData"]["results"][0]["titleNoFormatting"] helpers.msg(self.client, chan, "%s - %s" % (title, url)) else: helpers.msg(self.client, chan, "nobody cares about %s" % data)
def ison(self, server, nick, nicks): nicklist = nicks.split(" ") getglub = "GETMOOD " logging.info("---> recv \"ISON :%s\"" % nicks) for nick_it in nicklist: self.parent.moodUpdated.emit(nick_it, Mood(0)) if nick_it in self.parent.mainwindow.namesdb["#pesterchum"]: getglub += nick_it if getglub != "GETMOOD ": helpers.msg(self.client, "#pesterchum", getglub)
def join(self, prefix, arg): log.info('join %s %s' % (prefix, arg)) name = parse_name(prefix)[0] msgs = TellMessage.getForUser(name, arg) for msg in msgs: helpers.msg( self.client, arg, "%s: %s said to tell you %s" % (msg.to_user, msg.from_user, msg.msg)) db.session.delete(msg) db.session.commit()
def store_note(self, chan, data): m = re.match(r'^(\S+) (.*)$', data) if m: key = ''.join(ch for ch in m.group(1) if ch not in set(string.punctuation)).lower() note = m.group(2) db = anydbm.open(config.get('yamms', 'notes_db'), 'c') db[key] = note db.close() helpers.msg(self.client, chan, "New note %s: %s" % (key, note))
def invite(self, nickhost, target, chan): nick, host = nickhost.split('!') if nick in self.settings['admins']: if target == self.my_nick and not chan in self.channels: self.channels[chan] = KevinBotGM(self, chan) else: pass # TODO: figure out whether this can happen else: helpers.msg(self.client, nick, 'Only a kevinbot admin can ' + 'add channels.')
def publish_partner_chunk(self): self.in_queue_lock.acquire() print 'chunks to publish: %d' % len(self.in_queue) while len(self.in_queue) > 0: chunk_str = self.in_queue.pop(-1) self.in_queue_lock.release() share_edit = self.session_view.begin_edit() self.session_view.insert(share_edit, self.session_view.size(), b64decode(chunk_str)) self.session_view.end_edit(share_edit) helpers.msg(self.client, self.tgt_nick, '!!MOAR.BACON.PLZ!!')
def partner_accept_session_ondone(self, response_idx): if response_idx == 0: self.session_role = Role.PARTNER self.am_recving_buffer = True helpers.msg(self.client, self.tgt_nick, CollabMessages.START_SHARE_ACK_FMT % self.max_buf_size) print 'IWANTBACON' self.session_view = sublime.active_window().new_file() self.session_view.set_scratch(True) # self.session_view.set_read_only(True) <-- may need a cleanup function if we do this else: self.session_role = None self.tgt_nick = None
def welcome(self, server, nick, msg): self.parent.setConnected() mychumhandle = self.mainwindow.profile().handle mymood = self.mainwindow.profile().mood.value() if not self.mainwindow.config.lowBandwidth(): helpers.join(self.client, "#pesterchum") helpers.msg(self.client, "#pesterchum", "MOOD >%d" % (mymood)) # We override the +T that's set by default, for now, to reenable # CTCP communication. # Because of the potential for spam, Low Bandwidth mode still # disables this...this will likely change in the future. helpers.mode(self.client, mychumhandle, "-T")
def privmsg(self, nick, chan, msg): msg = msg.strip() response = self.getCommand(msg, chan, nick.split('!')[0]) if chan[0] != "#": chan = nick.split('!')[0] print "PM | <{}> {}".format(nick, msg) if msg == "\x01VERSION\x01": """There's no basic ctcp function for some reason as far as I know, so I have to deal with it here. I'll probably have to make one later.""" self.client.send("NOTICE %s \x01VERSION Marzipan, the IRC Cooking Bot ver 0.2.9alpha\x01" % chan) else: print "{} | <{}> {}".format(chan, nick.split('!')[0], msg) self.client.channels[chan].log_user(nick.split('!')[0], msg) if response: helpers.msg(self.client, chan, response)
def _parse_cmd_lookup_carrier(self, hostmask, chan, cmd): logging.info('s! %s %s %s' % (hostmask, chan, cmd)) m = re.match('^\s*(\S+)$', cmd, re.UNICODE) if not m: helpers.msg(self.cli, chan, 'Usage: !l(ookup) <number>') return number = m.group(1) self.sms900.queue_event('LOOKUP_CARRIER', { 'hostmask': hostmask, 'number': number })
def run(self, command, sender, dest, *arg): log.info("running command sender=%s, dest=%s, command=%s, arg=%s", sender, dest, command, arg) if (hasattr(f, 'auth') and not self.client.command_handler.auth(self, command, sender, dest, *arg)): helpers.msg(self.client, dest, "you do not have the required permissions") return try: DefaultBotCommandHandler.run(self, command, sender, dest, *arg) except CommandError, e: helpers.msg(self.client, dest, str(e))
def __call__(self, sender, dest, arg): t = arg.split(' ', 1) target, message = t[0], t[1] sender = parse_name(sender)[0] if TellMessage.getCountForUser(target) >= int( config['tell']['max_msgs']): helpers.msg(self.client, dest, "%s has too many messages already" % target) return msg = TellMessage(sender, target, dest, message) db.session.save(msg) db.session.commit() helpers.msgOK(self.client, dest, sender)
def getMood(self, *chums): chumglub = "GETMOOD " for c in chums: chandle = c.handle if len(chumglub+chandle) >= 350: try: helpers.msg(self.client, "#pesterchum", chumglub) except socket.error: self.parent.setConnectionBroken() chumglub = "GETMOOD " chumglub += chandle if chumglub != "GETMOOD ": try: helpers.msg(self.client, "#pesterchum", chumglub) except socket.error: self.parent.setConnectionBroken()
def sendMessage(self, text, handle): h = unicode(handle) textl = [unicode(text)] def splittext(l): if len(l[0]) > 450: space = l[0].rfind(" ", 0, 430) if space == -1: space = 450 elif l[0][space + 1:space + 5] == "</c>": space = space + 4 a = l[0][0:space + 1] b = l[0][space + 1:] if a.count("<c") > a.count("</c>"): # oh god ctags will break!! D= hanging = [] usedends = [] c = a.rfind("<c") while c != -1: d = a.find("</c>", c) while d in usedends: d = a.find("</c>", d + 1) if d != -1: usedends.append(d) else: f = a.find(">", c) + 1 hanging.append(a[c:f]) c = a.rfind("<c", 0, c) # end all ctags in first part for i in range(a.count("<c") - a.count("</c>")): a = a + "</c>" #start them up again in the second part for c in hanging: b = c + b if len(b) > 0: return [a] + splittext([b]) else: return [a] else: return l textl = splittext(textl) try: for t in textl: helpers.msg(self.cli, h, t) except socket.error: self.setConnectionBroken()
def _parse_cmd_send_sms(self, hostmask, chan, cmd): logging.info('s! %s %s %s' % (hostmask, chan, cmd)) m = re.match('^\s*(\S+)\s+(.+)', cmd, re.UNICODE) if not m: helpers.msg(self.cli, chan, 'Usage: !s(end) <contact|number> <msg..>') return destination = m.group(1) msg = m.group(2) self.sms900.queue_event('SEND_SMS', { 'hostmask': hostmask, 'number': destination, 'msg': msg })
def report(self, func, oid=None, info="", *args): if self.logchan == None: return elif func == 'record': helpers.msg(self, self.logchan, "Inserted new recipe recording [{}] ({})".format(info, oid) ) elif func == 'quote': helpers.msg(self, self.logchan, "Inserted new quote of {} ({})".format(info, oid) ) elif func == 'add': helpers.msg(self, self.logchan, "Inserted new recipe [{}] ({})".format(info, oid) ) elif info != "": helpers.msg(self, self.logchan, info)
def _parse_cmd_pb_del(self, hostmask, chan, cmd): logging.info('s! %s %s %s' % (hostmask, chan, cmd)) m = re.match('^\s*(\S+)\s*$', cmd, re.UNICODE) if not m: helpers.msg(self.cli, chan, 'Usage: !d(elete) contact [email]') return nickname = None email = None if '@' in m.group(1): email = m.group(1) else: nickname = m.group(1) self.sms900.queue_event('DEL_PB_ENTRY', { 'hostmask': hostmask, 'nickname': nickname, 'email': email })
def _connect_and_run(self): cli = IRCClient(IRCThreadCallbackHandler, host=self.irc_host, port=self.irc_port, nick=self.irc_nick) self.ping_last_reply = time.time() self.ping_sent_at = False self.pong_queue.clear() conn = cli.connect() while True: next(conn) while len(self.cmd_queue) > 0: cmd = self.cmd_queue.popleft() target = cmd[1] msg = cmd[2] logging.info('Handling event (%s) -> (%s, %s)' % (cmd, target, msg)) helpers.msg(cli, target, msg) self._check_connection(cli) time.sleep(0.2)
def privmsg(self, nickhost, chan, msg): if self.busy: return nick, host = nickhost.split('!') if chan == self.my_nick: # user private message # Always respond to !version, !help, !die directly if msg == '!version': helpers.msg(self.client, nick, VERSION) elif msg == '!help' or msg.startswith('!help '): helpers.msg(self.client, nick, HELP_URL) elif msg == '!die': if nick in self.settings['admins']: self.__abort() self.client.send('QUIT :Killed by admin') exit(0) else: helpers.msg(self.client, nick, 'Not authorized!') else: # The !abort and !kick commands require a channel argument. # The !quit and !role commands do not. args = msg.split() if len(args) == 0: return if args[0] == '!abort' or args[0] == '!kick': if len(args) >= 2: if args[1] in self.channels: self.channels[args[1]]._usermsg( nick, ' '.join([args[0]] + args[2:]) ) else: helpers.msg( self.client, nick, 'Channel %s does not exist!' % args[1] ) else: for game in self.channels.values(): if nick in game.players: game._usermsg(nick, msg) else: # channel message; dispatch to appropriate GM self.channels[chan]._chanmsg(nick, msg)
class BotCommands(DefaultBotCommandHandler): def __init__(self, client): DefaultBotCommandHandler.__init__(self, client) working_set = getPkgResourcesWorkingSet() extendCommandClass(working_set, self, 'oyoyo_bot.commands', client) for command, fnc in config['commands'].iteritems(): ep = pkg_resources.EntryPoint.parse("%s = %s" % (command, fnc)) if not ep.dist: ep.dist = pkg_resources.get_distribution('oyoyo_bot') extendCommandClassWithEP(self, ep, client) @protected def getVisibleCommands(self, obj=None): obj = obj or self cmds = DefaultBotCommandHandler.getVisibleCommands(self, obj) if config['help'].as_bool('hide_auth_commands'): return [c for c in cmds if not hasattr(getattr(obj, c), 'auth')] else: return ["@%s"%c if hasattr(getattr(obj, c), 'auth') else c for c in cmds] @protected def run(self, command, sender, dest, *arg): log.info("running command sender=%s, dest=%s, command=%s, arg=%s", sender, dest, command, arg) if (hasattr(f, 'auth') and not self.client.command_handler.auth(self, command, sender, dest, *arg)): helpers.msg(self.client, dest, "you do not have the required permissions") return try: DefaultBotCommandHandler.run(self, command, sender, dest, *arg) except CommandError, e: helpers.msg(self.client, dest, str(e)) except Exception, e: log.error('command %s raised %s' % (command, e)) log.error(traceback.format_exc()) helpers.msg(self.client, dest, "sorry, there was an error")
def help(self, sender, dest, arg=None): """list all available commands or get help on a specific command""" logging.info('help sender=%s dest=%s arg=%s' % (sender, dest, arg)) if not arg: commands = self.getVisibleCommands() commands.sort() helpers.msg(self.client, dest, "available commands: %s" % " ".join(commands)) else: try: f = self.get(arg) except CommandError, e: helpers.msg(self.client, dest, str(e)) return doc = f.__doc__.strip() if f.__doc__ else "No help available" if not inspect.ismethod(f): subcommands = self.getVisibleCommands(f) if subcommands: doc += " [sub commands: %s]" % " ".join(subcommands) helpers.msg(self.client, dest, "%s: %s" % (arg, doc))
def unblockedChum(self, handle): h = str(handle) try: helpers.msg(self.cli, h, "PESTERCHUM:UNBLOCK") except socket.error: self.setConnectionBroken()