def close_participation(event, room, room_id, rooms_dict): print(room) members = get_room_members(room) line_bot_api.push_message( "U0a028f903127e2178bd789b4b4046ba7", TextSendMessage(text=f"this is {func_mode} mode") ) if len(members) < 4: line_bot_api.reply_message( event.reply_token, [TextSendMessage(text=f"最低でも4人必要です。5~8人がおすすめです。"), TextSendMessage(text=f"上の参加ボタンをあと{4-len(members)}人以上に押してもらってから、もう一度「参加を締め切るボタン」を押してください。」")] ) else: line_bot_api.reply_message( event.reply_token, [TextSendMessage(text=f"皆様の役割を個人メッセージでお送りしました。これ以降は、そちらをご参考ください。")] ) rounds = int(room['total_rounds']) line_bot_api.multicast( members, [TextSendMessage(text=f"ゲームID{room_id}に参加します"), TextSendMessage(text=f"全部で{rounds}ラウンドです。")] ) single_round_intro(members, room, room_id, rooms_dict)
def handle_content_message(event): if isinstance(event.message, ImageMessage): ext = 'jpg' elif isinstance(event.message, VideoMessage): ext = 'mp4' elif isinstance(event.message, AudioMessage): ext = 'm4a' else: return message_content = line_bot_api.get_message_content(event.message.id) with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf: for chunk in message_content.iter_content(): tf.write(chunk) tempfile_path = tf.name dist_path = tempfile_path + '.' + ext dist_name = os.path.basename(dist_path) os.rename(tempfile_path, dist_path) line_bot_api.reply_message( event.reply_token, [ TextSendMessage(text='Save content.'), TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name)) ])
def handle_file_message(event): message_content = line_bot_api.get_message_content(event.message.id) with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix='file-', delete=False) as tf: for chunk in message_content.iter_content(): tf.write(chunk) tempfile_path = tf.name dist_path = tempfile_path + '-' + event.message.file_name dist_name = os.path.basename(dist_path) os.rename(tempfile_path, dist_path) line_bot_api.reply_message( event.reply_token, [ TextSendMessage(text='Save file.'), TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name)) ])
def accept_vote(current_round, data_dict, event, rooms_dict, room): guessed_insider = data_dict["insider_guess"] already_voteds = current_round["commons_who_already_voted"] user_id = event.source.user_id if user_id not in already_voteds or func_mode == "one_phone_dev": current_round["insider_guess"].append(guessed_insider) already_voteds.append(user_id) display_names_who_voted = \ [get_display_name_from_json(user_id_who_voted, room) for user_id_who_voted in already_voteds] who_voted_str = '\n'.join(display_names_who_voted) line_bot_api.reply_message( event.reply_token, [TextSendMessage(text=f"投票済みの方:\n{who_voted_str}")] ) elif event.source.user_id in already_voteds: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="あなたは投票済みです。") ) with open('rooms.json', 'w') as room_json: json.dump(rooms_dict, room_json, indent=2)
def callback(): signature = request.headers['X-Line-Signature'] # get request body as text body = request.get_data(as_text=True) app.logger.info("Request body: " + body) # parse webhook body events = [] try: events = parser.parse(body, signature) except InvalidSignatureError: abort(400) for event in events: if isinstance(event, FollowEvent): line_bot_api.reply_message( event.reply_token, [TextSendMessage(text="インサイダー風ゲームBot友だちとなって頂きありがとうございます!\n"), TextSendMessage(text="一緒にゲームをするメンバーがいるルームで、'す'を入力するとスタート!"), TextSendMessage(text="'る'を入力するとルールが表示されます!")] ) if isinstance(event, JoinEvent): line_bot_api.reply_message( event.reply_token, [TextSendMessage(text="インサイダー風ゲームBotを招待していただきありがとうございます!\n"), TextSendMessage(text="'す'を入力するとスタート、'る'を入力するとルールが表示されます!")] ) if isinstance(event, MessageEvent): if isinstance(event.message, TextMessage): text = event.message.text if text in ['s', 'す']: new_room_id = add_room_info_to_json_and_return_room_id() line_bot_api.reply_message( event.reply_token, [TextSendMessage(text="このアカウントを友達登録をしてから、以下の参加ボタンを押してください。"), get_participation_button(new_room_id)] ) if text in ['r', 'rule', 'ルール', 'る', '説明', 'ル']: line_bot_api.reply_message( event.reply_token, [TextSendMessage(text=rule)] ) post_text_to_db(event) if isinstance(event, PostbackEvent): data_str = event.postback.data data_dict = dict(urlparse.parse_qsl(data_str)) room_id = data_dict['room_id'] with open('rooms.json', 'r') as room_json: rooms_dict = json.load(room_json) room = rooms_dict[room_id] current_round_count = len(room["rounds_info"]) nth_round_in_data_dict = -1 if "nth_round" in data_dict.keys(): nth_round_in_data_dict = int(data_dict["nth_round"]) latest_button = True if nth_round_in_data_dict != current_round_count: latest_button = False try: next_action = data_dict['next_action'] except KeyError: next_action = '' if next_action == 'get-participation': display_name = get_display_name(event.source.user_id) new_user = event.source.user_id if new_user not in get_room_members(room) or func_mode == "one_phone_dev": room['members'].append({ 'user_id': event.source.user_id, "score": 0, "display_name": display_name }) with open('rooms.json', 'w') as room_json: json.dump(rooms_dict, room_json, indent=2) line_bot_api.reply_message( event.reply_token, TextSendMessage(text=f'参加受付:{display_name}') ) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text=f'{display_name}は参加済みです。') ) if next_action == 'close': close_participation(event, room, room_id, rooms_dict) if next_action == 'start': if room["rounds_info"][-1]["started"] is False: single_turn_main(room, room_id, event) room["rounds_info"][-1]["started"] = True with open('rooms.json', 'w') as room_json: json.dump(rooms_dict, room_json, indent=2) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="開始済みです") ) if next_action == 'answered' and latest_button: if room['rounds_info'][-1]["answered"] is False: room['rounds_info'][-1]["answered"] = True rooms_dict[room_id] = room real_insider = room['rounds_info'][-1]["insider"] calculate_score_when_insider_guess_was_correct(real_insider, room) with open('rooms.json', 'w') as room_json: json.dump(rooms_dict, room_json, indent=2) start_timestamp = int(data_dict["start_timestamp"]) single_turn_guess_insider(room, room_id, start_timestamp) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="既に正解が出てます。") ) if next_action == 'word_guess_time_up' and latest_button: if room['rounds_info'][-1]["answered"] is False: room['rounds_info'][-1]["answered"] = True real_insider = room['rounds_info'][-1]["insider"] calculate_score_when_word_guess_timed_up(real_insider, room) single_turn_guess_insider_when_time_is_up(room, room_id) with open('rooms.json', 'w') as room_json: json.dump(rooms_dict, room_json, indent=2) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="すでにインサイダー予想に移っています。") ) if "insider_guess" in data_dict and "last_guess" not in data_dict: current_round = room['rounds_info'][-1] accept_vote(current_round, data_dict, event, rooms_dict, room) members = get_room_members(room) if len(current_round["insider_guess"]) >= len(members): # noinspection PyArgumentList c = collections.Counter(current_round['insider_guess'][:len(members)]) vote_result_sorted = c.most_common() has_same_rate, guessed_insiders = has_same_rate_first_place(vote_result_sorted) most_guessed_insider = vote_result_sorted[0][0] if has_same_rate: insider_guess_tournament(room, room_id, members, guessed_insiders) else: result_of_guess_message(room, current_round, most_guessed_insider) if len(room['rounds_info']) == room["total_rounds"]: line_bot_api.multicast( members, TextSendMessage(text=f"{room['total_rounds']}ラウンドが終わりました。ゲームを終了します。") ) else: # single_round_intro(members, room, room_id, rooms_dict) run_date = datetime.datetime.now() + datetime.timedelta(seconds=6) scheduler.add_job(single_round_intro, 'date', run_date=run_date, args=[members, room, room_id, rooms_dict]) if "last_guess" in data_dict: members = get_room_members(room) current_round = room['rounds_info'][-1] last_guessed_insider = data_dict["insider_guess"] result_of_guess_message(room, current_round, last_guessed_insider) if current_round == room["total_rounds"]: line_bot_api.multicast( members, TextSendMessage(text=f"{current_round}ラウンドが終わりました。ゲームを終了します。") ) else: single_round_intro(members, room, room_id, rooms_dict) post_postback_to_db(event) return 'OK'
def handle_join(event): line_bot_api.reply_message( event.reply_token, TextSendMessage(text='Joined this ' + event.source.type))
def text_message_handler_sample(event): text = event.message.text if text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message( event.reply_token, [ TextSendMessage( text='Display name: ' + profile.display_name ), TextSendMessage( text='Status message: ' + profile.status_message ) ] ) else: line_bot_api.reply_message( event.reply_token, TextMessage(text="Bot can't use profile API without user ID")) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message( event.reply_token, TextMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message( event.reply_token, TextMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextMessage(text="Bot can't leave from 1:1 chat")) elif text == 'confirm': confirm_template = ConfirmTemplate(text='Do it?', actions=[ MessageTemplateAction(label='Yes', text='Yes!'), MessageTemplateAction(label='No', text='No!'), ]) template_message = TemplateSendMessage( alt_text='Confirm alt text', template=confirm_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'buttons': buttons_template = ButtonsTemplate( title='My buttons sample', text='Hello, my buttons', actions=[ URITemplateAction( label='Go to line.me', uri='https://line.me'), PostbackTemplateAction(label='ping', data='ping'), PostbackTemplateAction( label='ping with text', data='ping', text='ping'), MessageTemplateAction(label='Translate Rice', text='米') ]) template_message = TemplateSendMessage( alt_text='Buttons alt text', template=buttons_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URITemplateAction( label='Go to line.me', uri='https://line.me'), PostbackTemplateAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackTemplateAction( label='ping with text', data='ping', text='ping'), MessageTemplateAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage( alt_text='Carousel alt text', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'image_carousel': image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerTemplateAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerTemplateAction(label='date', data='date_postback', mode='date')) ]) template_message = TemplateSendMessage( alt_text='ImageCarousel alt text', template=image_carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'imagemap': pass