def flip(self, channel, text): """<text> -- Flips <text> over.""" self.table_status = defaultdict(None) if self.use_flippers: if text in ['table', 'tables']: response = random.choice([ random.choice(self.flippers) + " ︵ " + "\u253B\u2501\u253B", self.table_flipper ]) self.table_status[channel] = True elif text == "5318008": out = "BOOBIES" response = random.choice(self.flippers) + " ︵ " + out elif text == "BOOBIES": out = "5318008" response = random.choice(self.flippers) + " ︵ " + out else: response = random.choice( self.flippers) + " ︵ " + multi_replace( text[::-1], self.replacements) else: response = multi_replace(text[::-1], self.replacements) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def giphy(self, command, channel, text): """Searches giphy.com for a gif using the provided search term.""" search_url = self.base_url + '/search' params = { 'q': text, 'limit': 10, 'fmt': "json", 'api_key': self.conf['giphy_api_key'] } r = None response = 'No gif found.' # fetch try: results = requests.get(search_url, params=params) r = results.json() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: response = "Could not get gif".format(e) if 'data' in r and r['data']: gif = random.choice(r['data']) if gif['rating']: response = "{} content rating: {}. (Powered by GIPHY)".format( gif['images']['downsized_large']['url'], gif['rating'].upper()) else: response = "{} - (Powered by GIPHY)".format(gif['embed_url']) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def imdb(self, channel, text, output): """imdb <movie> - gets information about <movie> from IMDb""" if 'user' not in output or output['user'] == self.conf['bot_id']: return strip = text.strip() re.match(self.id_re, text) if re.match(self.id_re, strip): params = {'i': strip} else: params = {'t': strip} request = requests.get("http://www.omdbapi.com/", params=params, headers=self.headers) content = request.json() if content.get('Error', None) == 'Movie not found!': response = 'Movie not found!' elif content['Response'] == 'True': content['URL'] = 'http://www.imdb.com/title/{}'.format(content['imdbID']) out = '*{Title}* ({Year}) ({Genre}): {Plot}' if content['Runtime'] != 'N/A': out += ' _{Runtime}_.' if content['imdbRating'] != 'N/A' and content['imdbVotes'] != 'N/A': out += ' _{imdbRating}_/10 with _{imdbVotes}_' \ ' votes.' out += ' {URL}' response = out.format(**content) else: response = 'Unknown error.' slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def google_search(self, channel, text): web_url = self.base_url + "/web" params = {'q': " ".join(text.split())} r = requests.get(web_url, params=params, headers=self.headers) soup = BeautifulSoup(r.content, "html.parser") web_results = soup.find('div', id="webResults") if web_results: result_url = requests.get(web_results.find_all( 'a', {'class': 'resultDisplayUrl'})[0]['href'], headers=self.headers).url result_description = soup.find('div', id="webResults").find_all( 'div', {'class': 'resultDescription'})[0].text self.logger.debug(result_url, result_description) response = "{} -- {}".format(result_url, result_description) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True) else: slack_client.api_call("chat.postMessage", channel=channel, text='No results found.', as_user=True)
def say_joke(self, channel): joke = random.choice(self.one_liner) slack_client.api_call("chat.postMessage", channel=channel, text=joke, as_user=True)
def grep(channel, text): query = select([table.c.ts, table.c.user_name, table.c.line]) \ .where(table.c.line.like("%{}%".format(text))) \ .order_by(desc(table.c.ts)) \ .limit(50) lines = database.db.execute(query) template = '```' data = [] for row in lines: if not re.match("^,grep .*", row.line): template += '{} | {}: {}\n' epoch = datetime.datetime.fromtimestamp(row.ts) friendly_time = epoch.strftime('%Y-%m-%d %H:%M:%S') data.append(friendly_time) data.append(row.user_name) data.append(row.line) template += '```' if data: response = template.format(*data) else: response = "No lines found." slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def send_trivia_answer(self, channel): answer = self.get_trivia_answer() response = "The answer was: {}".format(answer) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def dealwithit(self, channel, user): response = '{} {}'.format( random.choice(self.phrases).format(user), random.choice(self.macros)) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def info(self, channel, word): """<factoid> - shows the source of a factoid""" if word in self.factoid_cache[channel]: response = self.factoid_cache[channel][word] else: response = "Unknown Factoid." slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def random_cat(self, channel): # fetch try: request = requests.get(self.base_url, headers=self.headers) request.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: return "Could not get cat: {}".format(e) data = request.json() image = data['file'] slack_client.api_call("chat.postMessage", channel=channel, text=image, as_user=True)
def fight(self, channel, text, user_id): """<nick>, makes you fight <nick> and generates a winner.""" fighter1 = slack_helpers.get_user(user_id) dirty = text.strip() fighter2 = re.sub('[^0-9a-zA-Z_-]+', '', dirty) if random.random() < .5: response = "{}! {}! {}! {} {} over {} with a {} {}.".format(random.choice(self.bang), random.choice(self.bang), random.choice(self.bang), fighter1, random.choice(self.victory), fighter2, random.choice(self.blow_type), random.choice(self.blow)) else: response = "{}! {}! {}! {} {} over {} with a {} {}.".format(random.choice(self.bang), random.choice(self.bang), random.choice(self.bang), fighter2, random.choice(self.victory), fighter1, random.choice(self.blow_type), random.choice(self.blow)) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def weather(self, channel, text): owm = pyowm.OWM(self.conf['weather_api_key']) observation = owm.weather_at_place(text) l = observation.get_location() w = observation.get_weather() temp = w.get_temperature('fahrenheit') wind = w.get_wind() response = "Weather for {} is {}{}. {}. Wind: {}. Humidity: {}".format(l.get_name(), temp['temp'], "F", w.get_detailed_status(), wind['speed'], w.get_humidity()) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def fix(self, channel, text): """fixes a flipped over table. ┬─┬ノ(ಠ_ಠノ)""" response = "no tables have been turned over here, thanks for checking!" if text in ['table', 'tables']: if self.table_status[channel]: response = "┬─┬ノ(ಠ_ಠノ)" self.table_status[channel] = False else: self.flip(channel, text) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def send_new_question(self, channel): q = self.get_trivia_question() self.logger.debug('Question JSON: {}'.format(q)) self.logger.info('Question: {}'.format(q['question'])) self.logger.info('Answer: {}'.format(q['answer'])) response = "[*{}*] {}".format(q['category']['title'], q['question']) if q['value']: response += " _(difficulty: {})_".format(q['value']) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def list_factoids(self, channel): """- lists all available factoids""" reply_text = [] reply_text_length = 0 response = '' for word in self.factoid_cache[channel].keys(): added_length = len(word) + 2 if reply_text_length + added_length > 400: response = ", ".join(reply_text) reply_text = [] reply_text_length = 0 else: reply_text.append(word) reply_text_length += added_length response = ", ".join(reply_text) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def google_image_search(self, channel, text): image_url = self.base_url + "/images" params = {'q': " ".join(text.split())} r = requests.get(image_url, params=params, headers=self.headers) soup = BeautifulSoup(r.content, "html.parser") web_results = soup.find('div', id="webResults") if web_results: linklist = web_results.find_all('a', {'class': 'resultThumbnailLink'}) image = requests.get(random.choice(linklist)['href'], headers=self.headers).url slack_client.api_call("chat.postMessage", channel=channel, text=image, as_user=True) else: slack_client.api_call("chat.postMessage", channel=channel, text='No results found.', as_user=True)
def think(self, output, channel): if self.current: current_answer = self.current['answer'] if 'user' not in output: # this happened return user_id = output['user'] if current_answer == output['text'].lower().strip(): answer = self.get_trivia_answer() if answer: name = slack_helpers.get_user(output['user']) score = database.db.execute( select([table.c.score ]).where(table.c.id == user_id).where( table.c.channel == channel)).fetchone() if score: score = int(score[0]) score += 1 self.db_update(user_id, score, name, channel) else: score = 1 self.db_insert(user_id, score, name, channel) response = "Yay! {} (score: *{}*) answered it correctly: {}".format( name, score, answer) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True) sleep(5) self.send_new_question(channel)
def db_top_scores(channel): query = select([table.c.name, table.c.score]) \ .where(table.c.channel == channel) \ .order_by(desc(table.c.score)) scores = database.db.execute(query) template = '_Top Scores_: ' data = [] for row in scores: template += '*{}*: {}, ' data.append(row.name) data.append(row.score) template = template.rstrip(', ') if data: response = template.format(*data) else: response = "No scores here yet." slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def urban(self, channel, text): """urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com.""" define_url = self.base_url + "/define" random_url = self.base_url + "/random" if text: # clean and split the input text = text.lower().strip() parts = text.split() # if the last word is a number, set the ID to that number if parts[-1].isdigit(): id_num = int(parts[-1]) # remove the ID from the input string del parts[-1] text = " ".join(parts) else: id_num = 1 # fetch the definitions try: params = {"term": text} request = requests.get(define_url, params=params, headers=self.headers) request.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: return "Could not get definition: {}".format(e) page = request.json() if page['result_type'] == 'no_results': return 'Not found.' else: # get a random definition! try: request = requests.get(random_url, headers=self.headers) request.raise_for_status() except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e: return "Could not get definition: {}".format(e) page = request.json() id_num = None definitions = page['list'] if id_num: # try getting the requested definition try: definition = definitions[id_num - 1] def_text = " ".join( definition['definition'].split()) # remove excess spaces def_text = def_text[:200] except IndexError: return 'Not found.' url = definition['permalink'] response = "[{}/{}] {} - {}".format(id_num, len(definitions), def_text, url) else: definition = random.choice(definitions) def_text = " ".join( definition['definition'].split()) # remove excess spaces def_text = def_text[:200] name = definition['word'] url = definition['permalink'] response = "{}: {} - {}".format(name, def_text, url) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def calc(self, channel, text): response = self.aeval(text) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def say_ni(channel): slack_client.api_call("chat.postMessage", channel=channel, text='We are the Knights who say..... "Ni"!', as_user=True)
def list_plugins(channel): response = ' '.join(sorted({k for d in plugin_registry.commands for k in d})) slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
def say_hello_world(channel): slack_client.api_call("chat.postMessage", channel=channel, text="Hello World!", as_user=True)