def call_reia(): max_score = 0.1 map_val = "" print('-----------------------') user_input = raw_input("enter the string: ") #user_name = get_username(first_line.split(' ', 1)[0]) suggest_list = [] suggest_message = "" #prev_ts = ts print("\nINPUT = ") print(user_input) label = classify(user_input) if label == "": post_message( "Sorry, I could not understand. Please rephrase and try again.") consume_message() print("Classified as : " + str(label)) tokens = nltk.word_tokenize(user_input) print(tokens) st = StanfordPOSTagger(config['tagger']['model'], path_to_jar=config['tagger']['path']) stanford_tag = st.tag(user_input.split()) print("Tags") print(stanford_tag) """with open(MAPPING_PATH,'r') as data_file:
def start_meeting(settings, dynamodb): """ミーティング開始処理 :param settings: Settingsクラスオブジェクト :param dynamodb: DynamoDBクラスオブジェクト :return: なし """ # ユーザー一覧を取得 users = settings.get_users() # ユーザーが0人の場合 if len(users) == 0: return # 一人ずつミーティング開始メッセージを送信する for user in users: # ユーザーIDを取得 userId = user['id'] # DBからDM IDを取得 dmid = user['dmid'] # Question number = 1にする(ミーティング開始) dynamodb.save_status(userId, 1) # 1つ目の質問を送信する message = settings.get_start_message( ) + "\n" + settings.get_question_text(0) slack.post_message(dmid, message)
def create_search_box(channel_id=None, slack_id=None): logger.info("Creating search box") try: logger.debug("Request form: \n{}".format(request.form)) except: pass blocks = [{ "type": "actions", "elements": [{ "action_id": "series_search", "type": "external_select", "placeholder": { "type": "plain_text", "text": "Search for TV series" }, "min_query_length": 3 }] }] if channel_id: post_message(blocks, channel_id=channel_id, slack_id=slack_id, ephemeral=True) else: payload = {"response_type": "ephemeral", "blocks": blocks} return jsonify(payload)
def detect_image_labels(channel, image_bytes): print('Checking image to detect content...') labels = rekognition.detect_labels(image_bytes) gsheet.write_labels(labels) names = [] for label in labels: names.append(label.get('Name')) post_message(channel, 'Labels', names)
def handle_assign_task(task, userp=''): """ :return: """ post_message(task, userp) reply = 'Task has been assigned to ' + userp return statement(reply)
def post_to_slack(event, context): """Lambda function handler.""" LOG.info('Received event: %s', event) if not isinstance(event, list): raise InputError(event, "Input needs to be a json array") for message in event: slack.post_message(config.SLACK_URL, message)
def detect_celebrities(channel, image_bytes): print('Checking image to detect celebrity...') celebrities = rekognition.recognize_celebrity(image_bytes) gsheet.write_celebrities(celebrities) celeb_names = [] for celeb in celebrities: celeb_names.append( celeb.get('Name') + ' (' + str(celeb.get('MatchConfidence')) + '%)') post_message(channel, 'Celebrities', celeb_names)
def inbound(): logger.info("Inbound request from user received.") req = json.loads(request.form.get('payload')) logger.debug('Request data: \n{}'.format(req)) user_name = req['user']['name'] slack_id = req['user']['id'] channel_id = req['channel']['id'] callback_id = req.get('callback_id') action = req.get('actions') if action: action_id = action[0]['action_id'] if action_id == 'series_search': series_id = action[0]['selected_option']['value'] logger.info("Inbound request is a 'series_search'") t = Thread(target=respond_to_series_request, args=(series_id, channel_id, user_name, slack_id)) logger.info("Starting thread to generate series output") t.start() # delete_message(channel_id, message_ts) elif action_id == "add_to_watchlist": series_id = action[0]["value"] output_text = tvmaze.add_series_to_watchlist( series_id, slack_id, user_name) blocks = format_response_blocks(output_text) post_message(blocks, channel_id=channel_id, slack_id=slack_id, ephemeral=True) elif action_id == "remove_from_watchlist": series_id = action[0]["value"] output_text = tvmaze.remove_series_from_watchlist( series_id, slack_id) blocks = format_response_blocks(output_text) post_message(blocks, channel_id=channel_id, slack_id=slack_id, ephemeral=True) if callback_id: if callback_id == "create_spoiler": subject = req['submission']['spoiler_subject'] body = req['submission']['spoiler_body'] title, content = format_spoiler_output(subject, body, user_name) post_file(channel_id, content, title) logger.info('Sending HTTP Status 200 to requesting server') return '', 200
def post(self, request): print request.POST # Submitted forms w/appropriate data submitted_user_form = UserForm(request.POST, prefix="user") submitted_trainee_form = TraineeForm(request.POST, prefix="trainee") if all([ submitted_user_form.is_valid(), submitted_trainee_form.is_valid() ]): u_cleaned_data = submitted_user_form.cleaned_data t_cleaned_data = submitted_trainee_form.cleaned_data u = user_exists(u_cleaned_data) if u != None: # If exists already if u.submitted_tp: # If already submitted an app ... messages.info(request, "You already submitted a Core Team App.") return HttpResponseRedirect(reverse('core-team-success')) else: # If just on mailing list u.delete() u = save_user_via_form(submitted_user_form, submitted_trainee_form, "trainee") slack_message = "New Training Program application: *" + u.first_name + " " + u.last_name + "* | " + u.email slack.post_message(joe_token, '#signups_applications', slack_message, "Railroad") messages.info( request, "Thank you for applying to our Training Program") return HttpResponseRedirect( reverse('training-program-success')) else: # Never been touched u = save_user_via_form(submitted_user_form, submitted_trainee_form, "trainee") slack_message = "New Training Program application: *" + u.first_name + " " + u.last_name + "* | " + u.email slack.post_message(joe_token, '#signups_applications', slack_message, "Railroad") mailchimp.add_member_to_list(mailchimp_api_key, info_list_id, 9, u.email, u.first_name, u.last_name) messages.info( request, "Thank you for applying to our Training Program!") return HttpResponseRedirect( reverse('training-program-success')) else: return render( request, 'training-program.html', { 'request': request, 'email_form': self.email_form, 'user_form': submitted_user_form, 'trainee_form': submitted_trainee_form })
def send_empty_watchlist_notification(): text = "You're not following any TV shows yet. Use `/tv` to follow some shows first." blocks = [{ "type": "section", "text": { "type": "mrkdwn", "text": text } }] post_message(blocks, slack_id=slack_id, channel_id=channel_id, ephemeral=True)
def detect_explicit(channel, file_id, image_bytes): print('Checking image for explicit content...') if rekognition.detect_explicit_content(image_bytes): print( 'Image displays explicit content- deleting from Slack Shared Files...' ) delete_file(file_id) print('Posting message to channel to notify users of file deletion...') post_message( channel, 'Admin', 'File removed due to displaying explicit or suggestive adult content.' ) else: print('No explicit content found.')
def main(): df = pd.read_excel('data.xlsx', sheet_name='intent') model, vectorizer = nlu.train(df) conn = slack.connect() #model.save('nlu_model.h5') #model.load_weights('nlu_model.h5') slack.post_message( conn, 'I can help you in getting the details of Hollywood Movies, Novels and Weather in location . Type something to chat with me' ) while True: #retrieve utterance from slack channel utter, user_name = slack.get_message(conn) handle_utter(conn, utter, user_name, model, vectorizer, df)
def post(self, request): print request.POST # POST request form = EmailForm(request.POST) # Populate the email form with the values submitted if form.is_valid(): u = form.save(commit=False) u.on_email_list = True u.save() mailchimp.add_member_to_list(mailchimp_api_key, info_list_id, 9, u.email) slack_message = "New email address for mailing list: <mailto:" + u.email + "|" + u.email + ">" slack.post_message(joe_token, '#signups_applications', slack_message, "Railroad") return JsonResponse({ 'success': 'Thanks for subscribing! We\'ll keep you in the loop!' }) else: print form.errors.as_json return JsonResponse(form.errors.as_json(escape_html=True), safe=False)
def post_tweets_to_slack(tweets): """ Search tweets and post them to a Slack channel :param Status tweets: Status object (tweet) to post to Slack :return: the id of the latest tweet among the tweets :rtype: int """ max_id = 0 for tw in tweets: tw_template = Template(post_message_template) post_text = tw_template.render(tweet=tw) post_message(post_text, slack_channel_id) # Update max_id when the tweet has larger ID than current one. if tw.id > max_id: max_id = tw.id return max_id
def appreciate_employee(nominator_info, nominee_info, reason, dry_run=False): """ Nominations Sheet: 1plUmyrM2tXUTL0H-_vAAc0mZyjw5NkhsEYFkVcIbimg """ nominator = slack.get_user_real_name(user_info=nominator_info) nominee = slack.get_user_real_name(user_info=nominee_info) nominator_email = slack.get_user_email(user_info=nominator_info) nominee_email = slack.get_user_email(user_info=nominee_info) nominee_id = slack.get_user_id(user_info=nominee_info) sh = get_client().open_by_key( '1fBB0iWBkEsWWha2LA-ygHceis-SZGg6eFDF6Z-2DPNE') wks = None try: wks = sh.worksheet(datetime.datetime.today().strftime('%Y-%m')) except: wks = sh.add_worksheet( title=datetime.datetime.today().strftime('%Y-%m'), rows="1", cols="3") wks.update_cell(1, 1, 'Nominator') wks.update_cell(1, 2, 'Nominee') wks.update_cell(1, 3, 'Reason') wks.append_row([nominator_email, nominee_email, reason]) # TODO: Post message to user and to the Thx4That channel channel_message_text = "{0} has been nominated in Thx4That.".format( nominee) message = { "text": "Congratulations you have been nominated in Thx4That.", "attachments": [{ "fields": [{ "title": "Nominated By", "value": nominator }, { "title": "Reason", "value": reason }] }] } # Post personal message slack.post_message(nominee_id, message) # Post message to channel message['text'] = channel_message_text slack.post_message("C5MVBQRK7", message)
def post(self, request): print request.POST # POST request form = EmailForm( request.POST) # Populate the email form with the values submitted if form.is_valid(): u = form.save(commit=False) u.on_email_list = True u.save() mailchimp.add_member_to_list(mailchimp_api_key, info_list_id, 9, u.email) slack_message = "New email address for mailing list: <mailto:" + u.email + "|" + u.email + ">" slack.post_message(joe_token, '#signups_applications', slack_message, "Railroad") return JsonResponse({ 'success': 'Thanks for subscribing! We\'ll keep you in the loop!' }) else: print form.errors.as_json return JsonResponse(form.errors.as_json(escape_html=True), safe=False)
def send_watchlist_reports(watchlist_reports): for slack_id, user_report in watchlist_reports.items(): blocks = [ { "type": "context", "elements": [ { "type": "mrkdwn", "text": "Daily watchlist report" } ] }, { "type": "section", "text": { "type": "mrkdwn", "text": user_report } } ] post_message(blocks, slack_id=slack_id)
def handler(event, context): """ Main function. Signature for AWS Lambda. """ forecast = weather.get_daily_weather_forecast(settings.zipcode) if forecast is None: sys.exit("Could not retrieve weather forecast. Exiting.") slack_message = slack.generate_forecast_message( forecast, localizer.get_localized_current_time()) if not (slack.post_message(channel=settings.slack_channel, text=settings.slack_notification_text, blocks=slack_message)): sys.exit("Could not post slack message. Exiting.")
def main(): since_id_str = read_last_id() # Initialize since_id since_id = 1 if since_id_str.isdigit(): since_id = int(since_id_str) # Initialize largest_id which will be new since_id largest_id = since_id for q in query_strings: tweets = search_tweets(q, since_id) if len(tweets) > 0: # Post a header header_template = Template(result_header_template) header_text = header_template.render(query=q, num_tweets=len(tweets)) post_message(header_text, slack_channel_id) max_id = post_tweets_to_slack(tweets) # Update largest_id when one of tweets has larger ID than the # current. if max_id > largest_id: largest_id = max_id post_message(largest_id, slack_direct_message_id)
def post(self, request): print request.POST # Submitted forms w/appropriate data submitted_user_form = UserForm(request.POST, prefix="user") submitted_candidate_form = CandidateForm(request.POST, prefix="candidate") if all([submitted_user_form.is_valid(), submitted_candidate_form.is_valid()]): u_cleaned_data = submitted_user_form.cleaned_data c_cleaned_data = submitted_candidate_form.cleaned_data u = user_exists(u_cleaned_data) if u != None: if u.submitted_ct: messages.info(request, "You already submitted a Core Team App.") return HttpResponseRedirect(reverse('core-team-success')) else: u.delete() u = save_user_via_form(submitted_user_form, submitted_candidate_form, "candidate") slack_message = "New Core Team application: *" + u.first_name + " " + u.last_name + "* | " + u.email slack.post_message(joe_token, '#signups_applications', slack_message, "Railroad") messages.info(request, "Thank you for applying to our Core Team!") return HttpResponseRedirect(reverse('core-team-success')) else: u = save_user_via_form(submitted_user_form, submitted_candidate_form, "candidate") slack_message = "New Core Team application: *" + u.first_name + " " + u.last_name + "* | " + u.email slack.post_message(joe_token, '#signups_applications', slack_message, "Railroad") mailchimp.add_member_to_list(mailchimp_api_key, info_list_id, 9, u.email, u.first_name, u.last_name) messages.info(request, "Thank you for applying to our Core Team!") return HttpResponseRedirect(reverse('core-team-success')) else: return render(request, 'core-team.html', { 'request': request, 'email_form': self.email_form, 'user_form': submitted_user_form, 'candidate_form': submitted_candidate_form });
def construct_command(user_input, label, tokens, mapping, tags, exec_command, user_tag): command = "" response = 0 sys.path.insert(0, SLACK_PATH) import slack if label == 'folder': from folder import construct_command command, response = construct_command(user_input, label, tokens, mapping, tags) if label == 'network': from network import construct_command command, response = construct_command(user_input, label, tokens, mapping, tags) if label == 'file': from file import construct_command command, response = construct_command(user_input, label, tokens, mapping, tags) if label == 'system': from system import construct_command command, response = construct_command(user_input, label, tokens, mapping, tags) if label == 'general': from general import construct_command command, response = construct_command(user_input, label, tokens, mapping, tags) if exec_command == False: if response == 0: slack.post_message("@" + user_tag + " " + command) else: slack.post_message(map_val) else: if (response == 0): slack.post_message("Executing command : \n" + command) slack.post_message(execute_command(command, response))
def multiple_paths(path): paths = path.split('\n') if len(paths) > 1: if len(paths) > 20: post_message( "Too many folder possibilties. Please try another folder.") return ("Error") post_message( "I found multiple folder possibilties. Please make your selection\n" + path) slctn = read_message() while slctn == False: slctn = read_message() if int(slctn) >= len(paths): post_message("Out of range. Please enter again.") slctn = False path = paths[int(slctn)] return path
def game(players, roles, lonewolf=True, use_slack=False): N = len(players) assert len(roles) == N + 3 roles = [Role(role) for role in roles] random.shuffle(roles) initial_roles = copy(roles) slack_ids = get_slack_ids(players) if use_slack else {} log = [] #log that will be viewed at end of game messages = [[] for _ in range(N)] #messages that will be seen by player i players_by_role = defaultdict( list) #which players currently believe they are role X initial_players_by_role = defaultdict( list) #which players initially believe they are role X for i in range(N): players_by_role[roles[i].name].append(i) initial_players_by_role[roles[i].name].append(i) #list of (player, role) actions that need to be performed later #(e.g. when doppelganger copies an insomniac, revealer, or god) wrapup = [] shielded = [] revealed = [] marked = {} def players_in_category(cat): return [player for role in cat for player in players_by_role[role]] def message_and_log(i, during, after=None): messages[i].append(f"{players[i]} {during}") log.append(f"{players[i]} {after or during}") def broadcast_and_log(during, after=None): for i in range(N): messages[i].append(during) log.append(after or during) #gives the list of targets for an action that preferentially targets a non-wolf def try_for_nonwolf(i, doppelganged): if not doppelganged: return ([ j for j in range(N) if j not in players_in_category(seen_as_wolves) and j != i and j not in shielded ] or [j for j in range(N) if i != j and j not in shielded] ) #if all valid targets are wolves, pick one of them else: #doppelganger doesn't yet know who the wolves are, but prefentially avoids whoever they doppelganged return ([ j for j in range(N) if i != j and j not in shielded + doppelganged ] or [j for j in range(N) if i != j and j not in shielded]) def do_role(i, role, doppelganged=[]): #print(f"{players[i]} doing {role}") #print(f"shielded = {shielded}") #print(f"revealed = {revealed}") #print(f"roles = {roles}") if role.name in ("werewolf", "dreamwolf", "minion", "villager", "hunter", "bodyguard", "merlin", "imposter", "tanner"): pass elif role.name == "sentinel": try: j = random_choice(N, [i] + shielded) shielded.append(j) broadcast_and_log( f"{players[j]} was marked with a shield", f"{players[i]} marked {players[j]} with a shield") except NoTarget: broadcast_and_log(i, "had no one to mark") elif role.name == "witch": j = random_choice(3) role = roles[N + j] message_and_log(i, f"looked at center card {j+1} and saw {role}") if role.name in evil and random.random( ) < 0.5 and i not in shielded: target = i else: target = random_choice(N, [i] + doppelganged, shielded) rotate(roles, [target, N + j - 1]) message_and_log(i, f"gave {players[target]} role {role}") elif role.name == "PI": exclude = [i] + shielded + doppelganged for _ in range(2): try: j = random_choice(N, exclude) exclude.append(j) message_and_log( i, f"looked at {players[j]} and saw {roles[j]}") if roles[j].name in suspicious: message_and_log(i, f"became {roles[j]}") role.copied = roles[j] break if random.random() < 0.5: break except NoTarget: message_and_log(i, "had no one to look at") elif role.name == "medium": for _ in range(2): exclude = [] j = random_choice(3, exclude) exclude.append(j) message_and_log( i, f"looked at center card {j+1} and saw {roles[N+j]}") if roles[N + j].name in suspicious: message_and_log(i, f"became {roles[N+j]}") role.copied = roles[N + j] break if random.random() < 0.5: break elif role.name == "curator": if doppelganged: wrapup.append((i, role)) else: try: j = random_choice(N, [i] + shielded + list(marked.keys())) #TODO: in physical game, the same mark can't be given multiple times mark = random.choice(marks) marked[j] = mark messages[i].append( f"{players[i]} gave {players[j]} a mark") messages[j].append(f"{players[j]} received {mark}") for k in range(N): if k not in (i, j): messages[k].append(f"{players[j]} received a mark") log.append(f"{players[i]} gave {players[j]} {mark}") except NoTarget: message_and_log(i, "had no one to mark") pass elif role.name in ("drunk", "fool"): j = random_choice(3) if role.name == "fool": for k in range(3): if k != j: message_and_log( i, f"looked at center card {k+1} and saw {roles[N+k]}" ) if i in shielded: message_and_log(i, "did nothing, because they were shielded") else: message_and_log( i, f"took center card {j+1}", f"took center card {j+1} which was {roles[N+j]}") rotate(roles, (i, N + j)) elif role.name == "mysticwolf": targets = try_for_nonwolf(i, doppelganged) if not targets: message_and_log(i, "looked at no one") else: j = random.choice(targets) message_and_log(i, f"looked at {players[j]} and saw {roles[j]}") elif role.name == "villageidiot": to_rotate = [j for j in range(N) if j != i and j not in shielded] if random.random() < 0.5: to_rotate.reverse() if random.random() < 0.2 or len(to_rotate) < 2: message_and_log(i, "didn't rotate anyone") else: rotate_str = ' -> '.join( [players[i] for i in to_rotate + [to_rotate[0]]]) rotate(roles, to_rotate) message_and_log(i, f"rotated {rotate_str}") elif role.name == "revealer": if doppelganged: wrapup.append((i, role)) else: try: j = random_choice(N, [i] + shielded + revealed) if roles[j].name in suspicious: message_and_log( i, f"looked at {players[j]} and saw {roles[j]}, so did not reveal" ) else: revealed.append(j) broadcast_and_log( f"{players[j]} was revealed to be {roles[j]}", f"{players[i]} revealed {players[j]} to be {roles[j]}" ) except NoTarget: message_and_log(i, "had no one to reveal") elif role.name == "doppelganger": try: j = random_choice(N, [i] + shielded + doppelganged) role.copied = Role(roles[j].name) message_and_log( i, f"doppelganged {players[j]}, who was {roles[j]}") players_by_role[role.copied.name].append(i) do_role(i, role.copied, doppelganged + [j]) except NoTarget: message_and_log(i, f"had no one to copy") elif role.name == "seer": looked = False if random.random() < 0.5: try: j = random_choice(N, [i] + doppelganged + shielded) message_and_log( i, f"looked at {players[j]} and saw {roles[j]}") looked = True except NoTarget: looked = False if not looked: j = random_choice(3) k = random_choice(3, [j]) for m in [j, k]: message_and_log( i, f"looked at center card {m+1} and saw {roles[N+m]}") elif role.name == "madseer": try: j = random_choice(N, [i] + doppelganged + shielded) k = random_choice(N, [j], [i] + doppelganged + shielded) rolej = roles[j] rolek = None #if you see a madseer, should see double madseer, otherwise should see no madseer while rolek is None or ((rolej.name == "madseer") != (rolek.name == "madseer")): rolek = roles[random_choice(N + 3)] true_message = f"looked at {players[j]} and saw {rolej}" true_messages = (true_message, true_message) false_message = f"looked at {players[k]} and saw {rolek}" false_messages = ( false_message, f"looked at {players[k]} and hallucinated {rolek}") for during, after in random.choice( [[true_messages, false_messages], [false_messages, true_messages]]): message_and_log(i, during, after) except NoTarget: message_and_log(i, f"had no one to look at") elif role.name == "apprenticeseer": j = random_choice(3) message_and_log( i, f"looked at center card {j+1} and saw {roles[N+j]}") elif role.name == "lucidwolf": j = random_choice(3) message_and_log( i, f"looked at center card {j+1} and saw {roles[N+j]}") elif role.name in ("robber", "bandit"): if i in shielded: message_and_log(i, f"did nothing, because they were shielded") else: try: j = random_choice(N, doppelganged, [i] + shielded) if role.name == "robber": rotate(roles, (i, j)) message_and_log(i, f"stole {roles[i]} from {players[j]}") elif role.name == "bandit": k = random_choice(3) msg = f"stole {roles[j]} from {players[j]} and gave them center card {k+1}" message_and_log(i, msg, f"{msg} which was {roles[N+k]}") rotate(roles, (j, i, N + k)) except NoTarget: message_and_log(i, f"couldn't rob anyone") elif role.name == "alphawolf": targets = try_for_nonwolf(i, doppelganged) if not targets: message_and_log(i, "turned no one into a wolf") else: j = random.choice(targets) message_and_log( i, f"turned {players[j]} into a wolf", f"exchanged {players[j]} with the wolf-card, which was {do_role.current_wolf_card.full_str()}" ) roles[ j], do_role.current_wolf_card = do_role.current_wolf_card, roles[ j] elif role.name == "insomniac": if doppelganged: wrapup.append((i, role)) else: if i in shielded: message_and_log( i, f"did not see their role, because they were shielded") else: messages[i].append( f"{players[i]} ended the night as {roles[i]}") elif role.name == "mason": messages[i].append( reveal_msg("mason", "masons", players, players_by_role['mason'])) elif role.name in ("loverwolf", "lovervillager"): messages[i].append( reveal_msg("lover", "lovers", players, players_in_category(lovers))) elif role.name in ("god", "enemyofreason"): if doppelganged: wrapup.append((i, role)) else: for m in log: messages[i].append(f"[{role.name}] {m}") #god takes their role back at the end of the night #TODO: doppelganger should take back the doppelganger card #(natural implementation is to have role be the doppelganger card, # and replace role.name with role.copied.....name, but that sounds annoying) for j in range(N): if j != i and roles[j] == role: message_and_log( i, f"took their original role back from {players[j]}") rotate(roles, (j, i)) for k in range(3): if roles[N + k - 1] == role: message_and_log( i, f"took their original role back from center card {k}" ) rotate(roles, (N + k - 1, i)) if do_role.current_wolf_card == role: message_and_log( i, f"took their original role back from the wolf-card") roles[ i], do_role.current_wolf_card = do_role.current_wolf_card, roles[ i] elif role.name == "troublemaker": try: j = random_choice(N, [i] + shielded) k = random_choice(N, [i, j] + shielded) rotate(roles, (j, k)) message_and_log(i, f"switched {players[j]} and {players[k]}") except NoTarget: message_and_log(i, "couldn't switch anybody") elif role.name == "trickster": try: j = random_choice(N, [i] + shielded) center_index = random_choice(3) message_and_log( i, f"gave the player with role {roles[j]} the new role {roles[N+center_index]}", f"gave {players[j]} center card {center_index+1} which was {roles[N+center_index]}" ) rotate(roles, (j, N + center_index)) except NoTarget: message_and_log(i, "couldn't switch anybody") else: raise ValueError(role.name) do_role.current_wolf_card = Role("werewolf") wake_order = [] def wake_role(role_name): actors = list(initial_players_by_role[role_name]) random.shuffle(actors) for i in actors: do_role(i, initial_roles[i]) for i, role in wrapup: if role.name == role_name: do_role(i, role) if role_name in [role.name for role in roles]: wake_order.append(role_name) def do_werewolves(): seen_wolves = players_in_category(seen_as_wolves) message = reveal_msg("wolf", "wolves", players, seen_wolves) for i in players_in_category(see_wolves): messages[i].append(message) #werewolves separately learn who is sleeping, because they have thumbs out message = reveal_msg("sleeping wolf", "sleeping wolves", players, players_in_category(sleepy_wolves)) for i in players_in_category(awake_wolves): messages[i].append(message) if len(seen_wolves) == 1 and lonewolf: wolf = seen_wolves[0] if wolf in players_in_category(awake_wolves): j = random_choice(3) message_and_log( wolf, f"looked at center card {j+1} and saw {roles[N+j]}") def display(text): print(text) if slack_ids: for player in slack_ids: post_message(slack_ids[player], text) for ms in messages: ms.append( f"--------------------\nSeating order: {', '.join(players)}\n") for i in range(N): message_and_log(i, f"began the night as {roles[i]}") wake_role("tanner") wake_role("villager") wake_role("sentinel") wake_role("doppelganger") do_werewolves() wake_role("werewolf") wake_role("imposter") wake_role("dreamwolf") wake_role("alphawolf") wake_role("mysticwolf") wake_role("minion") wake_role("merlin") wake_role("mason") wake_role("loverwolf") wake_role("lovervillager") wake_role("seer") wake_role("madseer") wake_role("apprenticeseer") wake_role("lucidwolf") wake_role("PI") wake_role("medium") wake_role("robber") wake_role("bandit") wake_role("witch") wake_role("trickster") wake_role("troublemaker") wake_role("villageidiot") wake_role("fool") wake_role("drunk") wake_role("insomniac") wake_role("revealer") wake_role("curator") wake_role("god") def make_wake_order_str(role): num_roles = len([x for x in roles if x.name == role]) return role if num_roles == 1 else f"{role} (x{num_roles})" indicators = [ "1", "2", "3", "4", "5", "pinky", "fist", "thumb", "spidey", "hangloose" ] wake_order_str = ("\nWake order:\n\n" + "\n".join([ f"({i}) {make_wake_order_str(x)}" for i, x in zip(indicators, wake_order) ])) for ms in messages: ms.append(wake_order_str) for i, player in enumerate(players): if player in slack_ids: post_message([slack_ids[player]], '\n'.join(messages[i])) mostly_slack = (len(players) <= len([p for p in players if p in slack_ids]) + 1) for i, player in enumerate(players): if player not in slack_ids: clear() print(f"pass the computer to {player}") wait() clear() for message in messages[i]: print(message) if not mostly_slack: wait() if not mostly_slack: clear() print(wake_order_str) try: print() thinking = 60 discussing = 10 * 60 timer(display, ( 0, "One minute to think before starting discussion... (press ctrl-c at any time to see the results)" ), (thinking, "Ten minutes to discuss until voting..."), (thinking + discussing - 120, "Two minutes until voting..."), (thinking + discussing - 30, "Thirty seconds until voting..."), (thinking + discussing, "Time to vote!")) except KeyboardInterrupt: pass else: print("Press any key to see final roles") wait() finally: def final_role_str(i): result = f"{players[i]}: {roles[i].full_str()}" if i in marked: result += f" ({marked[i]})" return result print() log.append("\nFinal roles:") log.extend([final_role_str(i) for i in range(N)]) display('\n'.join(log))
def display(text): print(text) if slack_ids: for player in slack_ids: post_message(slack_ids[player], text)
def test_publish_message(mocker): mocker.patch.object(requests, 'post') response = namedtuple('response', 'status_code') response.status_code = 200 requests.post.return_value = response slack.post_message(test_constants.SLACK_URL, 'message')
def call_reia(): while (True): max_score = 0.1 map_val = "" with open('/media/ubuntu/Local Disk/MAJOR_PROJECT/REIA/mqueue.txt', 'r') as f: first_line = f.readline() while first_line == "": time.sleep(1) call_reia() print('-----------------------') user_input = first_line.split(' ', 1)[1] #user_name = get_username(first_line.split(' ', 1)[0]) suggest_list = [] suggest_message = "" #prev_ts = ts print("\nINPUT = ") print(user_input) label = classify(user_input) if label == "": post_message( "Sorry, I could not understand. Please rephrase and try again." ) consume_message() continue print("Classified as : " + str(label)) tokens = nltk.word_tokenize(user_input) print(tokens) st = StanfordPOSTagger(config['tagger']['model'], path_to_jar=config['tagger']['path']) stanford_tag = st.tag(user_input.split()) print("Tags") print(stanford_tag) with open(MAPPING_PATH, 'r') as data_file: data = json.load(data_file) for i in data[label]: dist = jf.jaro_distance(unicode(str(user_input), encoding="utf-8"), unicode(str(i), encoding="utf-8")) suggest_list.append(tuple((dist, i))) print(dist) if (dist > max_score): max_score = dist map_val = i if max_score < config['preferences']['similarity_threshold']: post_message( "Sorry, I could not understand. Please rephrase and try again." ) consume_message() if config['preferences']['suggestions'] == True: suggest = suggestions(suggest_list) post_message("Did you mean :") for i in suggest: suggest_message += (str(i[1]) + "\n") post_message(suggest_message) continue print("\nMapped to : " + map_val) #post_message(map_val) construct_command(user_input, label, tokens, map_val, stanford_tag, exec_command) #call('sed -i -e "1d " REIA/mqueue.txt') consume_message()
def handle_utter(conn, utter, user_name, model, vectorizer, df): #get intents, entities and sentiment of utterance Int_Ent_Sent = nlu.transform_utter(model, vectorizer, df, utter) #Bot respond back to user request with few default responses (Small Talk) if re.match('(.*)who are you(.*)', utter.lower()): slack.post_message( conn, random.choice([ "I'm Jiro", "My name is Jiro", "Jiro, Bot Jiro", "Bot Jiro is my name", "I am a Bot", "I am a ChatBot" ])) elif re.match('(.*)how old are you(.*)|(.*)your age(.*)', utter.lower()): slack.post_message( conn, random.choice([ "My age is " + str(datetime.datetime.now().year - 2018) + " years old", "I am " + str(datetime.datetime.now().year - 2018) + " years old" ])) elif re.match('(.*)you are annoy(.*)|^annoying$', utter.lower()): slack.post_message( conn, random.choice([ "I'll do my best not to annoy you in the future", "I didn't mean to. I'll do my best to stop that.", "I don't mean to. I'll ask my developers to make me less annoying." ])) elif re.match('(.*)answer my question(.*)|(.*)answer to my question(.*)', utter.lower()): slack.post_message( conn, random.choice([ "Kindly Elaborate it", "Please rephrase your question", "Could you please repeat it again?", "Can you try asking it a different way?" ])) elif re.match( "(.*)you're bad(.*)|(.*)you are bad(.*)|(.*)you are the worst(.*)|(.*)you are no good(.*)", utter.lower()): slack.post_message( conn, random.choice([ "I can be trained to be more useful. My developer will keep training me.", "I can improve with continuous feedback. My training is ongoing.", "I must be missing some knowledge. I'll have my developer look into this." ])) elif re.match( "(.*)can you get smart(.*)|(.*)can you become smart(.*)|(.*)will you become smart(.*)|(.*)will you get smart(.*)", utter.lower()): slack.post_message( conn, random.choice([ "I'm definitely working on it.", "Yes definitely", "Yes I try my best" ])) elif re.match( "(.*)you're beautiful(.*)|(.*)you're handsome(.*)|(.*)you're smart(.*)|(.*)you're crazy(.*)|(.*)you are crazy(.*)|(.*)you're funny(.*)|(.*)you are funny(.*)|(.*)you're clever(.*)|(.*)you are clever(.*)|(.*)you're so clever(.*)|(.*)you are so clever(.*)|(.*)you're great(.*)|(.*)you're awesome(.*)|(.*)you are good(.*)|(.*)you are beautiful(.*)|(.*)you are handsome(.*)|(.*)you are smart(.*)|(.*)you are a smart(.*)|(.*)you are great(.*)|(.*)you are awesome(.*)|(.*)you are good(.*)|^smart$|^awesome$|^great$|^good$|^beautiful$|^handsome$|^fantastic$", utter.lower()): slack.post_message( conn, random.choice( ["Yes I am", "Thankyou very much", "I am happy to hear it"])) elif re.match("(.*)your birth(.*)|(.*)you born(.*)", utter.lower()): slack.post_message( conn, random.choice( ["I born on 01-Jan-2019", "My Date of Birth is 01/Jan/2019"])) elif re.match("(.*)you are boring(.*)|(.*)you're boring(.*)|^boring$", utter.lower()): slack.post_message( conn, random.choice([ "I'm sorry. I'll request to be made more charming.", "Sorry, I will try my best", "I will not let this happen again" ])) elif re.match("(.*)are you busy(.*)|(.*)are you not free(.*)", utter.lower()): slack.post_message( conn, random.choice([ "Never too busy for you. Shall we chat?", "I am free, tell me", "No I am not, tell me your request" ])) elif re.match("^yes$|^correct$|^perfect$|^exactly$|^nice$", utter.lower()): slack.post_message( conn, random.choice(["Thats great!!", "I'm glad to hear it", "ok done"])) elif re.match( "(.*)are you a chatbot(.*)|(.*)you are a chatbot(.*)|(.*)you're a chatbot(.*)|(.*)are we friends(.*)|(.*)are you my friend(.*)|(.*)am i your friend(.*)", utter.lower()): slack.post_message( conn, random.choice( ["Thats right!!", "Yes ofcourse", "you hit the bull's eye"])) elif re.match( "(.*)are you happy(.*)|(.*)are you glad(.*)|(.*)are you feeling good(.*)", utter.lower()): slack.post_message( conn, random.choice([ "I'd like to think so.", "Maybe!! I am not sure", "Not sure about it" ])) elif re.match("(.*)are you hungry(.*)|(.*)are you feeling hungry(.*)", utter.lower()): slack.post_message( conn, random.choice( ["No I am not", "Maybe!! I am not sure", "Not sure about it"])) elif re.match( "(.*)you have a hobby(.*)|(.*)you have hobby(.*)|(.*)your hobby(.*)", utter.lower()): slack.post_message( conn, random.choice([ "Yes, My hobby chatting with you", "My hobby is to chat with you", "Not sure about it" ])) elif re.match("(.*)you marry me(.*)|(.*)I marry you(.*)|^marry me$", utter.lower()): slack.post_message( conn, random.choice([ "I think its not pssible", "Sorry it can't happen", "Not sure about it" ])) elif re.match( "(.*)where do you work(.*)|(.*)your work(.*)|(.*)your job(.*)|(.*)your company(.*)|(.*)your role(.*)", utter.lower()): slack.post_message( conn, random.choice(["Chat bot", "Responsive bot", "Service bot"])) elif re.match( "(.*)where are you from(.*)|(.*)your location(.*)|(.*)your place(.*)|(.*)your native(.*)", utter.lower()): slack.post_message( conn, random.choice([ "The Internet is my home. I know it quite well", "The Computer is my home. I know it quite well" ])) elif re.match( "(.*)are you ready(.*)|(.*)are you real(.*)|(.*)are you sure(.*)|(.*)are you there(.*)", utter.lower()): slack.post_message(conn, random.choice(["Yes I am", "Yes I do"])) elif re.match("^that's bad$|^that is bad$|^this is bad$", utter.lower()): slack.post_message(conn, random.choice(["oh feeling sorry"])) elif re.match( "^that's great$|^thats great$|^that is great$|^this is great$|^great$|^welldone$|^well done$", utter.lower()): slack.post_message(conn, random.choice(["Thank you!", "Yeah!!"])) elif re.match("^no problem$", utter.lower()): slack.post_message(conn, random.choice(["okay"])) elif re.match( "^thankyou(.*)|^thank you(.*)|^thanks(.*)|^thanks a lot(.*)|^thankyou very much(.*)", utter.lower()): slack.post_message( conn, random.choice(["Welcome", "You are always welcome"])) elif re.match("(.*)haha(.*)|(.*)ha ha(.*)", utter.lower()): slack.post_message( conn, random.choice([ "Glad I can make you laugh", "I wish I could laugh out loud, too." ])) elif re.match("^wow$", utter.lower()): slack.post_message(conn, random.choice(["Indeed"])) elif re.match("(.*)bye(.*)", utter.lower()): slack.post_message( conn, random.choice([ "Bye " + user_name, "Let's meet again " + user_name, "See you soon " + user_name ])) elif re.match("^good morning$|^goodmorning$", utter.lower()): slack.post_message(conn, random.choice(["Very Good Morning " + user_name])) elif re.match("^good evening$|^goodevening$", utter.lower()): slack.post_message(conn, random.choice(["Very Good Evening " + user_name])) elif re.match("^good night$|^goodnight$", utter.lower()): slack.post_message(conn, random.choice(["Sweet Dreams"])) elif re.match("^how are you(.*)", utter.lower()): slack.post_message(conn, random.choice(["I am good. How can I help you?"])) elif re.match("^nice to meet you$", utter.lower()): slack.post_message( conn, random.choice(["It's nice meeting you, too " + user_name])) elif re.match("^nice to see you$", utter.lower()): slack.post_message(conn, random.choice(["Hi! how are you doing?"])) elif re.match("^nice to talk to you$|^nice to talk with you$", utter.lower()): slack.post_message(conn, random.choice(["I am feeling the same"])) elif re.match("^what's up(.*)|^whats up(.*)|^whatsup(.*)", utter.lower()): slack.post_message( conn, random.choice(["Not a whole lot. What's going on with you?"])) elif re.match( "^what can you do(.*)|^How will you help me(.*)|^your job(.*)", utter.lower()): slack.post_message( conn, random.choice([ "I can help you in Hollywood Movies, Novels and Weather in location" ])) #Check confidence. Here the Threshold is 60% confidence elif Int_Ent_Sent['Confidence'] < 80: slack.post_message(conn, random.choice(fallback_responses)) #call respective Dialogs according to the use intent else: if Int_Ent_Sent['Intent'] == 'Movie': dialogs.movie(Int_Ent_Sent, conn, user_name) elif Int_Ent_Sent['Intent'] == 'Novel': dialogs.novel(Int_Ent_Sent, conn, user_name) elif Int_Ent_Sent['Intent'] == 'Weather': dialogs.weather(Int_Ent_Sent, conn, user_name) elif Int_Ent_Sent['Intent'] == 'Welcome': dialogs.Welcome(Int_Ent_Sent, conn, user_name)
def meeting_proc(event, settings, dynamodb): """ミーティング処理 :param event: イベントデータ :param settings: Settingsクラスオブジェクト :param dynamodb: DynamoDBクラスオブジェクト :return: なし """ # tokenのチェック if not is_verify_token(event): return # 新規投稿であるかをチェック(削除や編集は対象外) if not is_new_message(event): return # slackのイベント slack_event = event["event"] # ユーザー userid = slack_event["user"] # テキスト text = slack_event["text"] # チャンネル channel = slack_event["channel"] # ユーザーが存在するかをチェック isuser = settings.is_user(userid) if isuser == False: return # ステータス取得 status = dynamodb.get_status(userid) # Question number question_no = status['question_no'] # ミーティング時間外 if question_no == 0: return # メッセージを保存 dynamodb.save_message(userid, question_no, text) # 最後の質問への回答の場合 question_len = len(settings.get_question_list()) if question_no == question_len: # 完了メッセージを送信 slack.post_message(channel, settings.get_end_message()) # 収集されたメッセージを全て取得 d = dynamodb.get_messages(userid) # メッセージを作成 attachments = messages.create_message(d, settings) # get_users_infoでユーザー名やアイコンを取得 profile = slack.get_users_info(userid).get('user').get('profile') # 投稿先チャンネル broadcast_channel = settings.get_broadcast_channel() # メッセージ message = messages.get_broadcast_message(settings.get_project_title(), profile['real_name']) # 該当チャンネルに、投稿内容をまとめて送信 slack.post_broadcast_message(broadcast_channel, message, profile['display_name'], profile['image_48'], attachments) # Question numberを0にする(ミーティング終了) dynamodb.save_status(userid, 0) # メッセージを全て削除する for num in range(1, question_len + 1): dynamodb.delete_message(userid, num) # 回答中の場合 else: # Question numberを1つ進める dynamodb.save_status(userid, question_no + 1) # Slackにメッセージを投稿する slack.post_message(channel, settings.get_question_text(int(question_no)))
def respond_to_series_request(series_id, channel_id, user_name, slack_id): series_data = tvmaze.get_series_data_via_id(series_id) blocks = format_series_output(series_data, user_name) post_message(blocks, channel_id=channel_id) create_search_box(channel_id, slack_id)
def send_slack_message(message): success = slack.post_message(config.SLACK_WEBHOOK_URL, message) if success: metrics.add_dimension(name="environment", value="dev") metrics.add_metric(name="SlackNotificationSend", unit=MetricUnit.Count, value=1)
message = options.message or '' # Run shell command and keep track runtime + return code if options.shell_command: start_time = datetime.now() # Should I capture output? return_code = subprocess.call(options.shell_command, shell=True) runtime = datetime.now() - start_time message = '\n'.join([ message, 'Command: "%s"' % options.shell_command, 'Runtime: %s' % runtime, 'Status: %d' % return_code ]) # Get fresh channel ids if command took > 1hr to run if runtime.total_seconds() > 60 * 60: channel_ids = get_channel_ids(options.user, options.channel) if message: res = slack.post_message(message, channel_ids) #print(res) #TODO: check for errors for f in files: res = slack.post_file(f, channel_ids) if not res['ok']: print('error: could not post file', f)
def weather(Int_Ent_Sent,conn,user_name): #update acc to excel temp = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['temp'])] pressure = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['pressure'])] temp_min = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['temp_min'])] temp_max = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['temp_max'])] speed = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['speed'])] deg = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['direction'])] country = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['country'])] humidity = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['humidity'])] loc = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['location_names'])] coord = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['coordinates'])] wea= [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['weather'])] while (1): if loc: weather_reposonse = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+str(loc[0])+'&APPID=0583a32030db119217dc0595d49acc33') climate = weather_reposonse.json() slack.post_message(conn, random.choice(["climate at "+str(loc[0])+" is as follows "])) if coord: slack.post_message(conn, random.choice(["coordinates are " + str(climate['coord']['lon']) + " longitude and " + str(climate['coord']['lat']) + " latitude "])) if wea: slack.post_message(conn,random.choice(["weather at "+str(loc[0])+" is " + str(climate['weather'][0]['description'])])) if temp: slack.post_message(conn, random.choice(["temperature is " + str(climate['main']['temp'])+"Fahrenheit"])) if pressure: slack.post_message(conn, random.choice(["pressure is " + str(climate['main']['pressure'])+"hectopascals"])) if humidity: slack.post_message(conn, random.choice(["humidity is " + str(climate['main']['humidity'])+"%"])) if temp_min: slack.post_message(conn, random.choice(["minimum temperature is " + str(climate['main']['temp_min'])+"Fahrenheit"])) if temp_max: slack.post_message(conn, random.choice(["maximum temperature is " + str(climate['main']['temp_max'])+"Fahrenheit"])) if speed: slack.post_message(conn, random.choice(["speed of wind is " + str(climate['wind']['speed'])+"miles/hour"])) if deg: slack.post_message(conn, random.choice(["direction of wind is " + str(climate['wind']['deg']+" degrees")])) if country: slack.post_message(conn, random.choice(["written by " + str(climate['country'])])) break else: slack.post_message(conn,'Please enter the location name correctly') loc= [slack.get_message(conn)][0]