def run(self, msg, args, callback): """ Run an external script asynchronously. Timeout with a message if the default threshold is reached. """ logger.debug("Executing module %s: %s" % (self.name, args)) # Not sure if this unicode on all platforms by default username = ensure_unicode(msg.Sender.Handle) full_name = ensure_unicode(msg.Sender.FullName) #timeout(execute_module, name, args, callback, default=) def threaded_run(): args.insert(0, unicode(self.path)) logger.debug("Running command line: %s" % " ".join(args)) env = os.environ.copy() env["SKYPE_USERNAME"] = username.encode("utf-8") env["SKYPE_FULLNAME"] = full_name.encode("utf-8") process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, env=env) out = process.communicate()[0] # :E1103: *%s %r has no %r member (but some types could not be inferred)* # pylint: disable=E1103 return out.decode("utf-8") default = "Module %s timeouted in %d seconds" % (self.name, settings.TIMEOUT) thread = ExecutionManagedThread(threaded_run, default, settings.TIMEOUT, callback) thread.start()
def is_valid(path): """ Is this a module we are looking for """ if not path.endswith(".py"): return False f = open(path, "r") line1 = ensure_unicode(f.readline()) line2 = ensure_unicode(f.readline()) f.close() if line1.startswith("#!/sevabot") or line2.startswith("#!/sevabot"): return True return False
def handle_message(self, msg, status): """ Print help text to chat. """ if status == 'SENT': return True body = ensure_unicode(msg.Body) lower = body.lower() words = re.split('(\s+|\n|,)', lower, flags=re.M) if len(words) < 2: return False if False==words[0].startswith(BOT_NAME): return False chat_id = get_chat_id(msg.Chat) # usrs = msg.Chat.Members # aUm = iter(usrs) # for i, x in enumerate(usrs): # msg.Chat.SendMessage(" - %s" % x.FullName) # Check if we match any of our commands for name, cmd in self.commands.items(): patern = re.compile(name) if patern.search(lower) != None: cmd(msg, chat_id) return True return False
def handle_message(self, msg, status): """Override this method to customize a handler. """ # Skype API may give different encodings # on different platforms body = ensure_unicode(msg.Body) logger.debug("Tasks handler got: %s" % body) # Parse the chat message to commanding part and arguments words = body.split(" ") lower = body.lower() if len(words) == 0: return False # Parse argument for two part command names if len(words) >= 2: desc = " ".join(words[2:]) else: desc = None chat_id = get_chat_id(msg.Chat) # Check if we match any of our commands for name, cmd in self.commands.items(): if lower.startswith(name): cmd(msg, status, desc, chat_id) return True return False
def handle_message(self, msg, status): """Override this method to customize a handler. """ body = ensure_unicode(msg.Body) chat_id = get_chat_id(msg.Chat) if len(body) == 0: return False for name, cmd in self.commands.items(): if body == name: cmd(msg, chat_id) return True if self.troller_is_running.get(chat_id): response = self.alice.respond(body) if response: msg.Chat.SendMessage(response) return True else: return False else: return False
def handle_message(self, msg, status): """ Override this method to customize a handler. """ # Parse body into utf8 body = ensure_unicode(msg.Body) # Debug logger.debug('[Duarte] got: {}'.format(body)) # If the separators are not specified, runs of consecutive # whitespace are regarded as a single separator args = body.split() # Empty msg? if not len(args): return False # Find command for name, cmd in self.commands.items(): if name == args[0]: cmd(msg, status, args) return True return False
def handle_message(self, msg, status): """ Override this method to customize a handler """ body = ensure_unicode(msg.Body) logger.debug("Twitter handler got: %s" % body) words = body.split(" ") if len(body): logger.debug(body) words = body.split() if len(words[0]): logger.debug("Has words[0]") if not re.search("(?P<url>https?://twitter[^\s]+)", words[0]): return False else: match = re.search("(?P<url>https?://twitter[^\s]+)", words[0]) matchStr = match.group(0) idnum = matchStr.split("/")[5] if len(idnum): self.print_twitter(msg, status, idnum) return True else: return False return False
def handle_message(self, msg, status): """ Override this method to customize a handler. """ body = ensure_unicode(msg.Body) logger.debug('Call handler got: {}'.format(body)) # If the separators are not specified, runs of consecutive # whitespace are regarded as a single separator words = body.split() if not len(words): return False if words[0] != '!call': return False args = words[1:] if not len(args): # !call simply starts a call self.start_call(msg, status, args) return True for name, cmd in self.commands.items(): if name == args[0]: cmd(msg, status, args) return True return False
def handle_message(self, msg, status): """ Override this method to customize a handler. """ # If you are talking to yourself when testing # Ignore non-sent messages (you get both SENDING and SENT events) if status == "SENDING" or status == "SENT": return if status != "RECEIVED": return False body = ensure_unicode(msg.Body) if len(body) == 0: return False # Check if we match any of our commands a = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body) for text in a: title = self.find_title(text) shortened = self.short(text) self.linkitio(text, msg.Sender.FullName) if 'youtube.com' in text or 'bbc.co.uk' in text or 'imdb.com' in text: if(title): if(shortened): msg.Chat.SendMessage(title + ' - ' + shortened) else: msg.Chat.SendMessage(title + ' - ' + text) return True else: return False return False
def handle_message(self, msg, status): """ Override this method to customize a handler. """ # If you are talking to yourself when testing # Ignore non-sent messages (you get both SENDING and SENT events) if status == "SENDING" or status == "SENT": return if status != "RECEIVED": return False body = ensure_unicode(msg.Body) if len(body) == 0: return False # Check if we match any of our commands a = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body) for text in a: title = self.find_title(text) msg.Chat.SendMessage(title + ' - ' + text) return True return False
def handle_message(self, msg, status): """ Override this method to customize a handler. """ body = ensure_unicode(msg.Body) logger.debug("LLEval handler got: {}".format(body)) if not body.startswith('#!'): return False if status == 'SENT': # Avoid infinite loop caused by self-reproducing code return True m = re.match('#!(?P<lang>\S+)\s+(?P<src>.*)', body, re.DOTALL) if not m: self.help(msg) return True lang = m.group('lang') src = m.group('src') if lang.startswith('/'): # Source code contains language specifier lang = None src = m.group(0) r = self.lleval(lang, src, msg) self.send_eval_result(r, msg) return True
def handle_message(self, msg, status): """Override this method to customize a handler. """ # Skype API may give different encodings # on different platforms body = ensure_unicode(msg.Body) logger.debug("Tasks handler got: %s" % body) # Parse the chat message to commanding part and arguments words = body.split(" ") lower = body.lower() if len(words) == 0: return False # Parse argument for two part command names if len(words) >= 2: desc = " ".join(words[2:]) else: desc = None if lower.startswith("retask"): batcmd = "/usr/bin/php -f /home/vnc/retask/sevabot/base.php %s %s %s" % (msg.Sender.Handle, base64.b64encode(msg.Sender.FullName.encode('utf-8')), base64.b64encode(body.encode('utf-8'))) result = subprocess.check_output(batcmd, shell=True) msg.Chat.SendMessage(result.decode('utf-8')) return True return False
def run(self, msg, args, callback): """ Run an external script asynchronously. Timeout with a message if the default threshold is reached. """ logger.debug("Executing module %s: %s" % (self.name, args)) # Not sure if this unicode on all platforms by default username = ensure_unicode(msg.Sender.Handle) full_name = ensure_unicode(msg.Sender.FullName) chat_name = ensure_unicode(msg.ChatName) #timeout(execute_module, name, args, callback, default=) def threaded_run(): args.insert(0, unicode(self.path)) logger.debug("Running command line: %s" % " ".join(args)) env = os.environ.copy() env["SKYPE_USERNAME"] = username.encode("utf-8") env["SKYPE_FULLNAME"] = full_name.encode("utf-8") env["SKYPE_CHATNAME"] = chat_name.encode("utf-8") env["CHAT_ID"] = get_chat_id(msg.Chat) env["HTTP_HOST"] = settings.HTTP_HOST.encode("utf-8") env["HTTP_PORT"] = str(settings.HTTP_PORT).encode("utf-8") env["SHARED_SECRET"] = settings.SHARED_SECRET.encode("utf-8") env["SEVABOT_HOME"] = settings.SEVABOT_HOME.encode("utf-8") for i, server in enumerate(settings.QA_SERVERS): name = "QA_SERVER" + str(i) env[name] = server.encode("utf-8") env["VERSION_APPENDIX"] = settings.VERSION_APPENDIX.encode("utf-8") env["GIT_REPO"] = settings.GIT_REPO.encode("utf-8") process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, env=env) out = process.communicate()[0] # :E1103: *%s %r has no %r member (but some types could not be inferred)* # pylint: disable=E1103 return out.decode("utf-8") default = "Module %s timeouted in %d seconds" % (self.name, settings.TIMEOUT) thread = ExecutionManagedThread(threaded_run, default, settings.TIMEOUT, callback) thread.start()
def handleMessages(self, msg, status): """ Handle incoming messages. """ logger.info("Incoming %s - %s - %s: %s" % (status, msg.Chat.FriendlyName, msg.FromHandle, ensure_unicode(msg.Body))) self.handler.handle(msg, status)
def handle_message(self, msg, status): """ Override this method to customize a handler. """ logger.info('On Duty') body = ensure_unicode(msg.Body).lower() logger.info('Call handler got: {}'.format(body)) if body != u'ника, кто дежурный?': return False logger.info('Command matched') week_num = datetime.date.today().isocalendar()[1] f = open( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'duty'), 'r') d = f.readlines() f.close() m = ensure_unicode(d[week_num % len(d)]) message_to_send = ensure_unicode(u'Дежурит сегодня ' + m) logger.info(message_to_send) msg.Chat.SendMessage(message_to_send) return True
def cmd_what_is(self, msg, chat_id): """ Print help text to chat. """ # search = re.compile('(?<=что такое\s).\w+') # search = re.compile('(?<=что такое\s)[^\s]*') search = re.compile('(?<=что такое\s)[^?]*') # body = ensure_unicode(msg.Body) lower = body.lower() whatis_text = search.findall(lower) if whatis_text!=None: new_url = "http://ru.wikipedia.org/wiki/"+whatis_text[0].replace (" ", "_") msg.Chat.SendMessage("глянь тут %s" % new_url)
def handle_message(self, msg, status): """ Override this method to customize a handler. """ body = ensure_unicode(msg.Body) logger.debug('URI handler got: {}'.format(body)) uris = re.findall(self.uri_regexp, body) for uri in uris: self.hatena_bookmark(uri, msg) self.notify_already_posted(uri, msg) # May be further processed return False
def handle_message(self, msg, status): """ Handles all the work on the messages and URI checking. """ # if the chat message is from the bot, ignore it. # probably some skype function to fetch your own name, but meh.. if msg.FromHandle == "WHG Bot": return False body = ensure_unicode(msg.Body) words = body.split(" ") # if it's an empty string, ignore it. if len(words) == 0: return False # if the first word someone writes is this if (words[0] == "!gb" or words[0] == "!giantbomb"): # we know they wrote nothing else if len(words) == 1: self.help(msg, status, HELP_TEXT) return True elif len(words) > 1: # if second word is a command, do stuff cmd = (" ").join(words[2:]) if (words[1] == "detailed"): self.game_search(msg, status, cmd, "detailed") return True elif (words[1] == "studio"): self.game_studio(msg, status, cmd) return True elif (words[1] == "franchise"): self.game_franchise(msg, status, cmd) return True else: # if second word is not a command, join everything after !gb # and search for this instead, with less details cmd = (" ").join(words[1:]) self.game_search(msg, status, cmd, "normal") return True else: return False return False
def handle_message(self, msg, status): """ Override this method to customize a handler. """ global timeToSmartChat, timeToChatUserSpecific body = ensure_unicode(msg.Body) logger.debug('Chat handler got: {}'.format(body)) # If the separators are not specified, runs of consecutive # whitespace are regarded as a single separator words = body.split() if not len(words): return False if words[0] == '!'+base_command+'': commandCalled = False if len(words) > 1: if words[1] not in non_admin_commands: if msg.Sender.Handle not in admins: msg.Chat.SendMessage('Nao mandas em mim.') return True args = words[1:] #start_smart for name, cmd in self.commands.items(): if name == args[0]: cmd(msg, status, args) commandCalled = True return True if not commandCalled: msg.Chat.SendMessage(args[0]+' not a valid command for FlipBot. See !flip') return True elif len(words) == 1: self.help(msg, status, words[1:]) return True elif words[0][0] != '!': if timeToSmartChat: self.try_reply(msg,status,words) #if timeToChatUserSpecific: # self.try_reply_user(msg,status,words) #return True return False
def _match(self, item, msg, uri): """ Whether the item matches the message. An item matches only if the message does not contain other than the URI and title. """ body = ensure_unicode(msg.Body) title = item['title'] remainder = body.replace(title, '').replace(uri, '').strip() logger.debug('Matching remainder: {}'.format(remainder)) # Does it look like a scrap? return re.match( '^["#\'()\-=~^|\[\]{}@`;:*,.<>_\s]{0,10}$', remainder )
def handle_message(self, msg, status): """Override this method to have a customized handler for each Skype message. :param msg: ChatMessage instance https://github.com/awahlig/skype4py/blob/master/Skype4Py/chat.py#L409 :param status: - :return: True if the message was handled and should not be further processed """ if status == 'SENT': # Avoid infinite loop caused by self-reproducing code return True test = None body = ensure_unicode(msg.Body) # Parse the chat message to commanding part and arguments # words = body.split('(\s+|\n)') words = re.split('(\s+|\n)', body, flags=re.M) lower = body.lower() a = re.compile(r'''http[s]?://''') if len(words) == 0: return False # if len(words) >= 2: hasLink = a.search(lower) if hasLink != None: urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', lower) for item in urls: test = self.get_link_title(item) if test != None: msg.Chat.SendMessage("%s" % (test)) return False
def handle_message(self, msg, status): body = ensure_unicode(msg.Body) SenderHandle = msg.Sender.Handle OurHandle = self.skype.CurrentUserHandle if SenderHandle == OurHandle: logger.info('recived own chat msg, ignoring') return False else: words = body.split() if not len(words): return False if words[0] in self.othercommands: return False if words[0] != '!irc': if msg.Sender.DisplayName <> "": sendernick = msg.Sender.DisplayName else: sendernick = msg.Sender.Handle call(["/home/skype/irc-msg.sh", sendernick + ": " + body]) logger.info('skype chat msg: ' + body) logger.debug('recived chat msg from ' + msg.Sender.Handle + " : " + msg.Sender.DisplayName) return False args = words[1:] if not len(args): self.help(msg, status, args) return True for name, cmd in self.commands.items(): if name == args[0]: cmd(msg, status, args) return True
def handle_message(self, msg, status): """ Override this method to customize a handler. """ body = ensure_unicode(msg.Body) logger.debug('Call handler got: {}'.format(body)) # If the separators are not specified, runs of consecutive # whitespace are regarded as a single separator words = body.split() handle = msg.Sender.Handle if not len(words) or handle == 'alchemisbot': return True if handle not in self.userlist: self.userlist[handle] = [int(time.time()), 0] if time.time() - self.userlist[handle][0] < self.timeoutTime and self.sp: self.userlist[handle][1] += 1 else: self.userlist[handle][1] = 0 if self.userlist[handle][1] in [4,5]: msg.Chat.SendMessage("Stop flooding, {}! You might get kicked from the chat! Wait {}s before posting again.".format(handle, int(self.timeoutTime-time.time()+self.userlist[handle][0]))) if self.userlist[handle][1] >= 6: msg.Chat.SendMessage("/kick {}".format(handle)) if msg.Sender.Handle in ["fmorisan", "euphoricradioactivity"] and body == "sp": self.sp = not self.sp msg.Chat.SendMessage("sp is now " + ["off","on"][self.sp]) # False is 0, True is 1 # hax because bool is a subclass of int and thus can be used as a list index self.userlist[handle][0] = time.time() return False
def handle_message(self, msg, status): """ Handles all the work on the messages and URI checking. """ # if the chat message is from the bot, ignore it. if msg.FromHandle == "bubbebot": return False body = ensure_unicode(msg.Body) words = body.split(" ") # if it's an empty string, ignore it. if len(words) == 0: return False # Compile regex objects uriRegex = re.compile("(?P<URI>spotify:(?P<type>(album|track|artist)):([a-zA-Z0-9]{22}))") urlRegex = re.compile("http(s)?://open.spotify.com/(?P<type>(album|track|artist))/(?P<URI>([a-zA-Z0-9]{22}))") uriMatch = uriRegex.search(body) # Check for URI match (spotify:track:URI) urlMatch = urlRegex.search(body) # Check for URL match (open.spotify.com/track/URI) matchType = "" if uriMatch: matchType = uriMatch.group("type") uri = uriMatch.group("URI") elif urlMatch: matchType = urlMatch.group("type") uri = "spotify:" + matchType + ":" + urlMatch.group("URI") else: return False if len(uri): # Retrieve the response, and get the JSON from spotify's lookup API. response = requests.get('http://ws.spotify.com/lookup/1/.json?uri=' + uri) data = response.json() # Parse track type JSON (URI/URL was a track i.e spotify:track:) if matchType == "track": album = data["track"]["album"]["name"] albumYear = data["track"]["album"]["released"] track = data["track"]["name"] length = data["track"]["length"] artist = data["track"]["artists"][0]["name"] minutes, seconds = self.convertToMinuteTime(length) self.send_msg(msg, status, "Track: " + track + " (" + repr(minutes) + ":" + repr(seconds).zfill(2) + ") by " + artist) self.send_msg(msg, status, "Album: " + album + " (" + albumYear + ")") # Parse album type JSON (URI/URL was an album i.e spotify:album:) elif matchType == "album": album = data["album"]["name"] artist = data["album"]["artist"] year = data["album"]["released"] self.send_msg(msg, status, "Album: " + album + " (" + year + ") by " + artist) # Parse artist type JSON (URI/URL was an aritst i.e spotify:artist:) elif matchType == "artist": artist = data["artist"]["name"] self.send_msg(msg, status, "Artist: " + artist) return True return False
def handle_message(self, msg, status): """ Override this method to customize a handler """ body = ensure_unicode(msg.Body) imgur = { 0: "http://i.imgur.com/XVO46.gif", 1: "http://i.imgur.com/9eRl9.gif", 2: "http://i.imgur.com/ZhIn2.gif", 3: "http://i.imgur.com/KPDN3.gif", 4: "http://i.imgur.com/2Rt52.gif", 5: "http://i.imgur.com/RVVtI.gif", 6: "http://i.imgur.com/bxHzi.gif", 7: "http://i.imgur.com/GZGaT.gif", 8: "http://i.imgur.com/yr226.gif", 9: "http://i.imgur.com/ZunmH.gif", 10: "http://i.imgur.com/DlltQ.gif", 11: "http://i.imgur.com/OGQ4g.gif", 12: "http://i.imgur.com/eWKdk.gif", 13: "http://i.imgur.com/c2wCA.gif", 14: "http://i.imgur.com/kAtDR.gif", 15: "http://i.imgur.com/y1Icl.gif", 16: "http://i.imgur.com/paQsm.gif", 17: "http://i.imgur.com/lFXj2.gif", 18: "http://i.imgur.com/NTf00.gif", 19: "http://i.imgur.com/9CCnN.gif", 20: "http://i.imgur.com/Tp7C2.gif", 21: "http://i.imgur.com/pKivt.gif", 22: "http://i.imgur.com/TIpk7.gif", 23: "http://i.imgur.com/aZXx7.gif", 24: "http://i.imgur.com/yJ0Fp.gif", 25: "http://i.imgur.com/W0een.gif", 26: "http://i.imgur.com/28xhH.gif", 27: "http://i.imgur.com/RLijq.gif", 28: "http://i.imgur.com/uN3oJ.gif", 29: "http://i.imgur.com/P8QUS.gif", 30: "http://i.imgur.com/KfiuI.gif", 31: "http://i.imgur.com/uSuf5.gif", 32: "http://i.imgur.com/fOYmw.gif", 33: "http://i.imgur.com/5Lw1s.gif", 34: "http://i.imgur.com/usPqv.gif", 35: "http://i.imgur.com/iXu73.gif", 36: "http://i.imgur.com/FT6qJ.gif", 37: "http://i.imgur.com/2U50c.gif", 38: "http://i.imgur.com/cUSOo.gif", 39: "http://i.imgur.com/FLdNC.gif", 40: "http://i.imgur.com/Llnpa.gif", 41: "http://i.imgur.com/7uo3S.gif", 42: "http://i.imgur.com/SRx2n.gif", 43: "http://i.imgur.com/Ovwhb.gif", 44: "http://i.imgur.com/WiNQ5.gif", 45: "http://i.imgur.com/rGeyj.gif", 46: "http://i.imgur.com/Jq6kM.gif", 47: "http://i.imgur.com/XFC97.gif", 48: "http://i.imgur.com/zZtAH.gif", 49: "http://i.imgur.com/PqszG.gif", 50: "http://i.imgur.com/uOdnX.gif", 51: "http://i.imgur.com/BhcYw.gif", 52: "http://i.imgur.com/WfAyl.gif", 53: "http://i.imgur.com/hoV57.gif", 54: "http://i.imgur.com/wOdQK.gif", 55: "http://i.imgur.com/K4Wkn.gif", 56: "http://i.imgur.com/o0jg9.gif", 57: "http://i.imgur.com/jWFWlKU.gif", 58: "http://i.imgur.com/B6jmK9g.gif", 59: "http://i.imgur.com/hMzl9MN.gif", 60: "http://i.imgur.com/XumZOt2.gif", 61: "http://i.imgur.com/9E2JcHc.gif", 62: "http://i.imgur.com/ckcd6tU.gif", 63: "http://i.imgur.com/IUSe71e.gif", 64: "http://i.imgur.com/mI54L2e.gif", 65: "http://i.imgur.com/GRP4xff.gif", 66: "http://i.imgur.com/iJXf3xF.gif", 67: "http://i.imgur.com/l4DEjYb.gif", 68: "http://i.imgur.com/Qg1IKVj.gif", 69: "http://i.imgur.com/iEJ7D8U.gif", 70: "http://i.imgur.com/DMwpTTF.gif", 71: "http://i.imgur.com/AoiVyYk.gif", 72: "http://i.imgur.com/WabJJSa.gif", 73: "http://i.imgur.com/Fo3MGKQ.gif", 74: "http://i.imgur.com/WtdUN3h.gif", 75: "http://i.imgur.com/TAd5e.gif", 76: "http://i.imgur.com/tQOMO.gif", 77: "http://i.imgur.com/5TKih.gif", 78: "http://i.imgur.com/EOl6j.gif", 79: "http://i.imgur.com/cHbW9.gif", 80: "http://i.imgur.com/3evlc.gif", 81: "http://i.imgur.com/WRv1h.gif", 82: "http://i.imgur.com/9jIpx.gif", 83: "http://i.imgur.com/PfK3w.gif", 84: "http://i.imgur.com/O01XE.gif", 85: "http://i.imgur.com/R9ALS.gif", 86: "http://i.imgur.com/7GLeJ.gif", 87: "http://i.imgur.com/Gyf6p.gif", 88: "http://i.imgur.com/em4yL.gif", 89: "http://i.imgur.com/IZPcV.gif", 90: "http://i.imgur.com/XGM8L.gif", 91: "http://i.imgur.com/X8I8V.gif", 92: "http://i.imgur.com/1q6CV.gif", 93: "http://i.imgur.com/Y3tYU.gif", 94: "http://i.imgur.com/H5z9g.gif", 95: "http://i.imgur.com/zmbrt.gif", 96: "http://i.imgur.com/VWa8T.gif", 97: "http://i.imgur.com/W3Wvy.gif", 98: "http://i.imgur.com/7A4ny.gif", 99: "http://i.imgur.com/ShpEo.gif" } if len(body): words = body.split() if msg.FromDisplayName != "WHG Bot": if "(cool)" in body or "8-)" in body: logger.info("cool was sent") i = randrange(0, len(imgur)) self.send_msg(msg, status, "(cool) solbriller " + imgur[i]) return True elif "postkasse" in body: self.send_msg(msg, status, "postkasse") return True elif "god stemning" in body.lower(): self.send_msg(msg, status, "Det er ikke lov å si..") return True else: return False else: return False else: return False return False
def handle(self, msg, status): """Handle command messages. """ # If you are talking to yourself when testing # Ignore non-sent messages (you get both SENDING and SENT events) if status == "SENDING": return # Some Skype clients (iPad?) # double reply to the chat messages with some sort of ACK by # echoing them back # and we need to ignore them as they are not real chat messages # and not even displayed in chat UI if status == "READ": return # Check all stateful handlers for handler in modules.get_message_handlers(): processed = handler(msg, status) if processed: # Handler processed the message return # We need utf-8 for shlex body = ensure_unicode(msg.Body).encode('utf-8') logger.debug(u"Processing message, body %s" % msg.Body) # shlex dies on unicode on OSX with null bytes all over the string try: words = shlex.split(body, comments=False, posix=True) except ValueError: # ValueError: No closing quotation return words = [word.decode('utf-8') for word in words] if len(words) < 1: return command_name = words[0] command_args = words[1:] # Beyond this point we process script commands only if not command_name.startswith('!'): return command_name = command_name[1:] script_module = modules.get_script_module(command_name) if command_name in self.builtins: # Execute a built-in command logger.debug('Executing built-in command {}: {}'.format(command_name, command_args)) self.builtins[command_name](command_args, msg, status) elif script_module: # Execute a module asynchronously def callback(output): if len(output) != 0: msg.Chat.SendMessage(output) script_module.run(msg, command_args, callback) else: msg.Chat.SendMessage("Don't know about command: !" + command_name)
def handle(self, msg, status): """Handle command messages. """ # If you are talking to yourself when testing # Ignore non-sent messages (you get both SENDING and SENT events) if status == "SENDING" or status == "SENT": return # Some Skype clients (iPad?) # double reply to the chat messages with some sort of ACK by # echoing them back # and we need to ignore them as they are not real chat messages # and not even displayed in chat UI if status == "READ": return # Check all stateful handlers for handler in modules.get_message_handlers(): processed = handler(msg, status) if processed: # Handler processed the message return # We need utf-8 for shlex body = ensure_unicode(msg.Body).encode('utf-8') logger.debug(u"Processing message, body %s" % msg.Body) # shlex dies on unicode on OSX with null bytes all over the string try: words = shlex.split(body, comments=False, posix=True) except ValueError: # ValueError: No closing quotation return words = [word.decode('utf-8') for word in words] endWord = words[-1] wordsLength = len(body) #Check to see if the words contain a link. if so find the word that has it and save it if (('http://' in body) or ('https://' in body)): for word in words: if "http://" in word: command_name = "linkCafe" command_args = [word,msg.FromDisplayName] self.run_commands(command_name,command_args,msg,status,'false') return if len(words) < 1: return command_name = words[0] command_args = words[1:] # Beyond this point we process script commands only if (command_name.startswith('!') or command_name == 'hayate'): if command_name == 'hayate': command_name = words[1] command_args = words[2:] else: command_name = command_name[1:] self.run_commands(command_name,command_args,msg,status,'true') elif (body in self.tagWords): command_name = "omu" command_args = [body.replace (" ", "%20")] self.run_commands(command_name,command_args,msg,status,'true') return elif len(words) <= 7 : for word in self.tagWords: if (body.find(word) >= 0 and ((len(words)==1 and (word in words)) or ( len(words) > 1 and (body.find(word+" ")==0) or (" "+word+" " in body) or (body.find(" "+word)==(wordsLength-len(word)-1))))): command_name = "omu" command_args = [word.replace (" ", "%20")] self.run_commands(command_name,command_args,msg,status,'true') return
def handle(self, msg, status): logger.info('Handle') """Handle command messages. """ # If you are talking to yourself when testing # Ignore non-sent messages (you get both SENDING and SENT events) if status == "SENDING": return # Some Skype clients (iPad?) # double reply to the chat messages with some sort of ACK by # echoing them back # and we need to ignore them as they are not real chat messages # and not even displayed in chat UI if status == "READ": return # Check all stateful handlers for handler in modules.get_message_handlers(): logger.info(str(handler)) processed = handler(msg, status) if processed: # Handler processed the message return # We need utf-8 for shlex body = ensure_unicode(msg.Body).encode('utf-8') # shlex dies on unicode on OSX with null bytes all over the string try: words = shlex.split(body, comments=False, posix=True) except ValueError: # ValueError: No closing quotation return words = [word.decode('utf-8') for word in words] if len(words) < 1: return command_name = words[0] command_args = words[1:] # Beyond this point we process script commands only if not command_name.startswith('!'): return command_name = command_name[1:] script_module = modules.get_script_module(command_name) if command_name in self.builtins: # Execute a built-in command logger.debug('Executing built-in command {}: {}'.format( command_name, command_args)) self.builtins[command_name](command_args, msg, status) elif script_module: # Execute a module asynchronously def callback(output): msg.Chat.SendMessage(output) script_module.run(msg, command_args, callback) else: msg.Chat.SendMessage("Don't know about command: !" + command_name)
def handle_message(self, msg, status): """ Override this method to customize a handler """ body = ensure_unicode(msg.Body) if len(body): words = body.split() if len(words[0]): if not re.search("(?P<url>[komplett|mpx]+.[no|se|dk]+/.*/[0-9]+)", body): return False else: match = re.search("(?P<url>[komplett|mpx]+.[no|se|dk]+/.*/[0-9]+)", body) matchStr = match.group(0) if len(matchStr): headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.2; WOW64) " + \ "AppleWebKit/537.36 (KHTML, like Gecko) " + \ "Chrome/30.0.1599.47 Safari/537.36", } html_escape_table = { "&": "&", '"': """, "'": "'", "'": "'", ">": ">", "<": "<", "å": "å", } html_unescape_table = {v:k for k, v in html_escape_table.items()} req = urllib2.Request('https://' + matchStr, headers=headers) sock = urllib2.urlopen(req) #data = sock.read() data = unicode(sock.read(), "utf8") unescape(data, html_unescape_table) #matchTitle = re.search('<title>(.*?)</title>', data) name = re.search('<h1 class="main-header" itemprop="name">([^<]+)</h1>', data).group(1) desc = re.search('<h3 class="secondary-header" itemprop="description">([^<]+)</h3>', data).group(1) price = re.search('<span itemprop="price"[^>]+>([^<]+)</span>', data).group(1) storage = re.search('<span class="stock-details">[\s]+([^<]+)[\s]+</span>', data).group(1) bomb = re.search('<div class="bomb">[\s]+<div class="value">([^<]+)</div>', data) if bomb is None: message = name + "\nPris: " + price + "\n" + storage else: message = name + "\nPris: " + price + "\n" + storage + "\n" + "PÅ TILBUD! (cash) " + bomb.group(1) sock.close() self.send_msg(msg, status, unescape(message, html_unescape_table)) return True else: return False else: return False return False
def handle_message(self, msg, status): """ Override this method to customize a handler """ body = ensure_unicode(msg.Body) y = re.compile(r'(youtu(?:\.be|be\.com)\/(?:.*v(?:\/|=)|(?:.*\/)?)([\w\'-]+))', re.IGNORECASE) v = re.compile(r'(vimeo(?:\.com)\/(?:(?:\/|=)|(?:.*\/)?)([\d]+))', re.IGNORECASE) tv = re.compile(r'(twitch\.tv\/([\w]+)\/([a-z]\/[0-9]+)\/?|justin\.tv\/([\w]+)\/([a-z]\/[0-9]+)\/?)', re.IGNORECASE) ts = re.compile(r'(twitch\.tv\/([\w]+)|justin\.tv\/([\w]+))\/?$', re.IGNORECASE) if len(body): words = body.split() message_y = y.search(body) message_v = v.search(body) message_tv = tv.search(body) message_ts = ts.search(body) if message_y: #url = "https://www.googleapis.com/youtube/v3/videos?id=" + message_y.group(2) + "&key=" + config["yt_api_key"] + "&part=snippet,contentDetails,statistics&fields=items(snippet/channelTitle,snippet/title,contentDetails/duration,statistics/viewCount)" url = "https://www.googleapis.com/youtube/v3/videos" params = { "id" : message_y.group(2), "key" : config["yt_api_key"], "part" : "snippet,contentDetails,statistics", "fields" : "items(snippet/channelTitle,snippet/title,contentDetails/duration,statistics/viewCount)" } new_url = urlencode(params) #request = urllib2.Request() logging.info("URL: " + url) logging.info("NEW URL: " + str(new_url)) #request = urllib2.Request(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"}) try: json_data = urllib2.urlopen(url + "/?%s" % new_url) except urllib2.URLError as e: if hasattr(e, 'reason'): logger.debug('We failed to reach a server.') logger.debug('Reason: ' + e.reason) elif hasattr(e, 'code'): logger.debug('The server couldn\'t fulfill the request.') logger.debug('Error code: ' + e.code) else: data = json.load(json_data) main = data["items"][0] title = main["snippet"]["title"] channel = main["snippet"]["channelTitle"] views = int(main["statistics"]["viewCount"]) views = "{:,}".format(views) #duration = time.strftime("%H:%M:%S", time.gmtime(main["contentDetails"]["duration"])) stats = title + " by " + channel + " - " + views + " views" self.send_msg(msg, status, stats) return True elif message_v: url = "http://vimeo.com/api/v2/video/" + message_v.group(2) + ".json" json_data = urllib2.urlopen(url) data = json.load(json_data)[0] title = data["title"] channel = data["user_name"] views = int(data["stats_number_of_plays"]) views = "{:,}".format(views) stats = title + " by " + channel + " - " + views + " views" self.send_msg(msg, status, stats) return True elif message_tv: vid_id = message_tv.group(3).replace("/", "") vid_id = vid_id.strip(" ") url = "https://api.twitch.tv/kraken/videos/" + vid_id json_data = urllib2.urlopen(url) data = json.load(json_data) if data: title = data["title"] game = data["game"] views = int(data["views"]) views = "{:,}".format(views) streamer = data["channel"]["display_name"] message = title + " by " + streamer + " - " + views + " views." self.send_msg(msg, status, message) return True else: return False elif message_ts: print "MATCHED STREAM" url = "https://api.twitch.tv/kraken/streams/" + message_ts.group(2) #request = urllib2.Request(url, "Accept: application/vnd.twitchtv.v2+json") json_data = urllib2.urlopen(url) data = json.load(json_data) if not data["stream"]: self.send_msg(msg, status, message_ts.group(2) + " is not streaming.") return True else: title = data["stream"]["channel"]["status"] streamer = data["stream"]["channel"]["display_name"] game = data["stream"]["channel"]["game"] viewers = int(data["stream"]["viewers"]) viewers = "{:,}".format(viewers) message = title + " - " + viewers + " viewers" self.send_msg(msg, status, message) return True else: return False else: return False return False
def handle(self, msg, status): """Handle command messages. """ # If you are talking to yourself when testing # Ignore non-sent messages (you get both SENDING and SENT events) if status == "SENDING": return # Some Skype clients (iPad?) # double reply to the chat messages with some sort of ACK by # echoing them back # and we need to ignore them as they are not real chat messages # and not even displayed in chat UI if status == "READ": return # Check all stateful handlers for handler in modules.get_message_handlers(): processed = handler(msg, status) if processed: # Handler processed the message return # We need utf-8 for shlex body = ensure_unicode(msg.Body).encode('utf-8') logger.debug(u"Processing message, body %s" % msg.Body) # shlex dies on unicode on OSX with null bytes all over the string try: words = shlex.split(body, comments=False, posix=True) except ValueError: # ValueError: No closing quotation return words = [word.decode('utf-8') for word in words] if len(words) < 1: return command_name = words[0] command_args = words[1:] ### Gong Li special power! (will not execute normal command) for word in words: gong_list = ["gong", "宮力", "宮博", "fish", "魚"] for gong in gong_list: if gong in word.lower(): command_name = "!gong" paris_list = ["巴黎", "paris", "法國", "france"] sf_list = ["舊金山", "sf", "san francisco"] bj_list = ["北京", "beijing", "中國", "china"] taipei_list = ["台北", "taipei", "台灣", "taiwan"] court_list = ["上訴", "法庭", "法律", "law"] news_list = ["新聞", "news"] yearend_list = ["尾牙", "year-end", "yearend"] for paris in paris_list: if paris in word.lower(): command_name = "!gong" command_args.append("paris") for sf in sf_list: if sf in word.lower(): command_name = "!gong" command_args.append("sf") for bj in bj_list: if bj in word.lower(): command_name = "!gong" command_args.append("bj") for tp in taipei_list: if tp in word.lower(): command_name = "!gong" command_args.append("tp") for court in court_list: if court in word.lower(): command_name = "!gong" command_args.append("court") for news in news_list: if news in word.lower(): command_name = "!gong" command_args.append("news") for yearend in yearend_list: if yearend in word.lower(): command_name = "!gong" command_args.append("yearend") # Only 3% of possibility to trigger POWER OF GONG if command_name == "!gong": if random.randint(1, 100) < 97: return ### End of Gong Li special power! # Beyond this point we process script commands only if not command_name.startswith('!'): return command_name = command_name[1:] script_module = modules.get_script_module(command_name) if command_name in self.builtins: # Execute a built-in command logger.debug('Executing built-in command {}: {}'.format(command_name, command_args)) self.builtins[command_name](command_args, msg, status) elif script_module: # Execute a module asynchronously def callback(output): msg.Chat.SendMessage(output) script_module.run(msg, command_args, callback) else: #msg.Chat.SendMessage("Don't know about command: !" + command_name) pass