def addreport(): try: data = json.loads(request.data) data = { 'email': decode_jwt(data.get('authtoken'))['email'], 'longitude': float(data.get('longitude')), 'latitude': float(data.get('latitude')), 'image': data.get('image'), 'description': data.get('description'), 'tags': data.get('tags') } if data['longitude'] == None or data['latitude'] == None or data['email'] == None: success = False else: report_id = add(data) userdata = users.find({"phone": {"$exists": True}}) for user in userdata: send(user['phone']) if report_id != None: success = True else: success = False if success == False: return json.dumps({"status": "error"}) else: return json.dumps({"status": "success"}) except: traceback.print_exc() return json.dumps({"status": "error"})
def start(room_id): temp = glob.room_mark[room_id] users = temp.keys() #分配角色 assign_role.assign(room_id) #发送房间和用户信息 r = RoomInfo.objects.get(r_id=room_id) #数据库对象不能直接解析成json data = {'r_id': r.r_id, 'owner': r.owner, 'player_num': r.player_num} json = demjson.encode(data) send_message.send(room_id, json) user_info = [] data = {'name': 'a', 'room_id': 0, 'role': 0, 'alive': True} for i in users: u = PlayerInfo.objects.get(name=i) data['name'] = u.name data['room_id'] = u.room_id #... user_info.append(data) json = demjson.encode(user_info) send_message.send(room_id, json) return
def callback(ch, method, propertites, body): recbody = body.decode("utf-8") recbody = json.loads(body) print(recbody) print(type(recbody)) engine = recbody["engine"] if engine=="email": content = recbody["content"] mailhost = recbody["mailhost"] subject = recbody["subject"] mailport = recbody["mailport"] sender = recbody["sender"] password = recbody["password"] receiver = recbody["receiver"] SM.send(content, mailhost, mailport, subject, sender, password, receiver) elif engine=="dd": notice = recbody["notice"] title = recbody["notice"] mstype = recbody["mstype"] token = recbody["ddtoken"] SM.dingding(notice, mstype, title, token) elif engine=="emaildd": content = recbody["content"] mailhost = recbody["mailhost"] subject = recbody["subject"] mailport = recbody["mailport"] sender = recbody["sender"] password = recbody["password"] receiver = recbody["receiver"] notice = recbody["notice"] title = recbody["notice"] mstype = recbody["mstype"] token = recbody["ddtoken"] SM.send(content, mailhost, mailport, subject, sender, password, receiver) SM.dingding(notice, mstype, title, token)
def select_seat(r_id, u_id, seat): result = 'false' used_seat = glob.room_player_seat[r_id].values() if int(seat) < 1 or int(seat) > glob.room_player_num[r_id]: result = 'false' elif seat in used_seat: result = 'false' else: glob.room_player_seat[r_id][u_id] = seat #这代表着一个人可以选多次座位 result = 'true' message = { 'type': '3', 'room_request_id': str(glob.room_request_id[r_id]), 'user_id': u_id, 'seat': seat, 'result': result } json = demjson.encode(message) send_message.send(r_id, json) if len(glob.room_player_seat[r_id]) == glob.room_player_num[r_id]: #全都选好位置 room = RoomInfo.objects.get(room_id=r_id) newstr = "" id_list = room.player_id.split(',') for i in range(len(id_list)): if i == len(id_list): newstr = newstr + str(glob.room_player_seat[r_id][id_list[i]]) else: newstr = newstr + str( glob.room_player_seat[r_id][id_list[i]]) + "," room.player_seat = newstr room.save() return
def m_new(myConnection, sql): config = get_config("setting") url_new = config['sites']['url'] data_new = beauti.getData(url_new) list_id_new = beauti.getId(data_new) values_new = sql.query(myConnection, 'new') for ids in list_id_new: if ids[0] not in values_new: sql.insert(myConnection, 'new', ids[0]) send(config["telegram"]["token"], config["telegram"]["chat_id"], ids[1])
def m_do(myConnection, sql): config = get_config("setting") url_do = config['sites']['url_do'] data_do = beauti_do.getData(url_do) list_id_do = beauti_do.getId(data_do) values_do = sql.query(myConnection, 'do') for ids in list_id_do: if ids[0] not in values_do: sql.insert(myConnection, 'do', ids[0]) send(config["telegram"]["token"], config["telegram"]["chat_id"], ids[1])
def test(r_id, u_id, seat): message = { 'type': '3', 'room_request_id': str(100), 'user_id': u_id, 'seat': seat, 'result': 'true' } json = demjson.encode(message) send_message.send(r_id, json) return
def connet_couples(r_id, u_id, o1_id, o2_id): glob.room_couples_id[r_id].append(o1_id) glob.room_couples_id[r_id].append(o2_id) message = { 'type': '16', 'room_request_id': str(glob.room_request_id[r_id]), 'user1_id': o1_id, 'user2_id': o2_id } json = demjson.encode(message) send_message.send(r_id, json) return
def send_message(self, message): students_format = "" for i in range(len(self.students_names) - 1): students_format += self.students_names[i] + ", " students_format += self.students_names[-1] patterns = { "{{team_?id}}": self.team_id, "{{team_?name}}": self.team_name, "{{coach_?n?a?m?e?}}": self.coach_name, "{{all_students}}": students_format } for item in patterns.items(): message = re.sub(item[0], item[1], message) for phone_number in self.phone_numbers: send(message, phone_number)
def process(message,data): type = data['type'] room_id = data['room_id'] user_name = data['user_name'] message = {} #处理确认消息 if type == 0: r_request_id = data['r_request_id'] if r_request_id == glob.room_request_id: glob.room_mark[room_id][user_name] = 1 return #非确认消息 request_id = data['request_id'] #判断该请求是否已被处理 if request_id < glob.user_request_id['user_name']: # message['type'] = 1 # message['user_name'] = user_name # json = demjson.encode(message) # send_message.send(room_id,json) return elif request_id > glob.user_request_id['user_name']: message['type'] = 2 message['room_request_id'] = glob.room_request_id[room_id] message['user_name'] = user_name message['error_message'] = 'error in request_id' json = demjson.encode(message) send_message.send(room_id, json) return else: # if type == 1: # #create_room.create() # elif type == 2: # #join_room.join() # else: # message['type'] = 2 # message['room_request_id'] = glob.room_request_id[room_id] # message['user_name'] = user_name # message['error_message'] = 'error in type' # json = demjson.encode(message) # send_message.send(room_id, json) return
def day_vote(r_id, u_id, o_id): glob.room_sheriff_select[r_id][u_id] = o_id glob.room_select_num[r_id] = glob.room_select_num[r_id] + 1 if (glob.room_sheriff_id[r_id] == u_id): glob.room_sheriff_select[r_id][-1] = o_id glob.room_select_num[r_id] = glob.room_select_num[r_id] + 1 if (glob.room_sheriff_id[r_id]!='-1' and glob.room_select_num[r_id] == glob.room_alive_num[r_id] + 1) \ or (glob.room_sheriff_id[r_id]=='-1' and glob.room_select_num[r_id] == glob.room_alive_num[r_id]): list = glob.room_sheriff_select[r_id] v = list.values() temp = Counter(v).most_common(2) #平票 if (len(temp) > 1 and temp[0][1] == temp[1][1]): message = { 'type': '17', 'room_request_id': str(glob.room_request_id[r_id]), 'result': 'false', 'sheriff_id': '-1', 'list': list } json = demjson.encode(message) send_message.send(r_id, json) else: result = Counter(v).most_common(1)[0][0] player_state_change.kill(r_id, o_id) message = { 'type': '17', 'room_request_id': str(glob.room_request_id[r_id]), 'result': 'true', 'sheriff_id': str(result), 'list': list } json = demjson.encode(message) send_message.send(r_id, json) room_state_change.change(0, r_id) #glob.room_request_content[r_id].append(json) glob.room_select_num[r_id] = 0 glob.room_sheriff_list[r_id] = [] glob.room_sheriff_select[r_id] = {} return
def join_compaign_sheriff(r_id, u_id, sheriff): if sheriff == 'true': glob.room_sheriff_list[r_id].append(u_id) glob.room_select_num[r_id] = glob.room_select_num[r_id] + 1 if glob.room_select_num[r_id] == glob.room_alive_num[r_id]: glob.room_select_num[r_id] = 0 message = { 'type': '8', 'room_request_id': str(glob.room_request_id[r_id]), 'list': glob.room_sheriff_list[r_id] } json = demjson.encode(message) send_message.send(r_id, json) #glob.room_request_content[r_id].append(json) glob.room_sheriff_list[r_id] = [] room_state_change.change(0, r_id) return
def sheriff_vote(r_id, u_id, o_id): glob.room_sheriff_select[r_id][u_id] = o_id glob.room_select_num[r_id] = glob.room_select_num[r_id] + 1 if glob.room_select_num[r_id] == glob.room_alive_num[r_id]: list = glob.room_sheriff_select[r_id] v = list.values() temp = Counter(v).most_common(2) #平票 if (len(temp) > 1 and temp[0][1] == temp[1][1]): message = { 'type': '9', 'room_request_id': str(glob.room_request_id[r_id]), 'result': 'false', 'sheriff_id': '-1', 'list': list } json = demjson.encode(message) send_message.send(r_id, json) else: result = Counter(v).most_common(1)[0][0] glob.room_sheriff_id[r_id] = result room = RoomInfo.objects.get(room_id=r_id) room.sheriff_id = o_id room.save() message = { 'type': '9', 'room_request_id': str(glob.room_request_id[r_id]), 'result': 'true', 'sheriff_id': str(result), 'list': list } json = demjson.encode(message) send_message.send(r_id, json) room_state_change.change(0, r_id) #glob.room_request_content[r_id].append(json) glob.room_select_num[r_id] = 0 glob.room_sheriff_list[r_id] = [] glob.room_sheriff_select[r_id] = {} return
def initiate(contacts_grouped, schedules, messages, messages_ITA, transactions, MID_counter, initiator, timeB): # ASSUMPTION: When a node is selected to initiate, it keeps initiating the message # every interval until max_relay is reached # Search for nodes in contact with the initiator at timeB b_trace = contacts_grouped[initiator] receivers = b_trace[(b_trace['start'] <= timeB) & (b_trace['end'] >= timeB)] messages.append(Message(MID_counter, initiator, timeB)) # For all receivers, call send(), timeB is the receive time # If no receivers, push to messages_ITA if not (receivers.empty): for index, receiver in receivers.iterrows(): if receiver['node1'] == initiator: if (not st.receiver_status_check) | (status_check( receiver['node2'], schedules, timeB)): send(messages, messages_ITA, transactions, MID_counter, receiver['node2'], timeB) else: # if receiver not online yet, push message to messages_ITA messages_ITA[MID_counter, initiator] = timeB else: if (not st.receiver_status_check) | status_check( receiver['node1'], schedules, timeB): send(messages, messages_ITA, transactions, MID_counter, receiver['node1'], timeB) else: # if receiver not online yet, push message to messages_ITA messages_ITA[MID_counter, initiator] = timeB else: # ASSUMPTION: If no one receives the message, append to messages_ITA # Equivalently, this means keep initiating until MAX_DELAY is met # This assumption slows down the operation by so much messages_ITA[MID_counter, initiator] = timeB return
def duty_check(): while 1: year, month, day, hour, minute, second = get_webservertime( 'www.baidu.com').split(' ') f = open('duty.txt', 'r').read().split('\n') [date, name_list] = f[1].split(' ') if [month, day] == date.split('-'): name_list = eval(name_list) for name in name_list: send(name) f.remove(f[1]) g = open('temp.txt', 'w') for i in f: g.write(i) g.write('\n') g.close() os.remove('duty.txt') os.rename('temp.txt', 'duty.txt') time.sleep(604800)
def server(): # 接收消息 data = request.get_data().decode('utf-8') data = eval(data) # 避免自我回复 #print(str(data.get("FromQQ").get("UIN"))==self_id) if str(data.get("FromQQ").get("UIN")) == self_id: return "" # 处理消息 message = message_operate.get_message(data) # 回复消息,仅当接收到的消息不为空时发送 if (message != ""): send_message.send(self_id, message) # 传出空值 return ""
def sendmail(): """ json: { "content": xxx, "mailhost": xxx, "mailport": xxx, "subject": xxx, "sender": xxx, "password": xxx, "receiver": xxx } """ jsonself = request.get_json() content = jsonself['content'] mailhost = jsonself['mailhost'] mailport = jsonself['mailport'] subject = jsonself['subject'] sender = jsonself['sender'] password = jsonself['password'] receiver = jsonself['receiver'] SM.send(content, mailhost, mailport, subject, sender, password, receiver) return jsonify(jsonself)
def main(): thai = ThaiCovid19() df = pd.DataFrame(thai, index=[0]) scope = ['https://www.googleapis.com/auth/spreadsheets' ] #ให้ทำการ auth scope เข้า sheet ครับ credentials = ServiceAccountCredentials.from_json_keyfile_name( "./eighth-opus-237810-c056aa9b0bca.json", scope) gc = gspread.authorize(credentials) sheet = gc.open_by_url( 'https://docs.google.com/spreadsheets/d/1gkFP_xeW_Rsb348vthtWfytIOoC-mc9AgdPss6rwaAw/edit?usp=sharing' ) wks = sheet.get_worksheet(0) #wks = worksheet df2 = gspread_dataframe.get_as_dataframe(wks) df2 = df2.iloc[:, :17] if df.iloc[0, 0] != df2.iloc[0, 0]: print('New Data Updated') df2 = df.append(df2, ignore_index=True, sort=False) gspread_dataframe.set_with_dataframe(wks, df2) df_json = df.to_json('./covid19.json', orient='records') print('File Saved In Local') uploaded = upload_to_aws('./covid19.json', bucket_name, 'covid19.json') if uploaded: print('File Uploaded to S3 Success') send_message.send(message="Covid19 : File Uploaded to S3 Success", spaces='spaces/AAAARA65rqo', thread=None) else: print('File Upload to S3 Failed') send_message.send(message="Covid19 : File Upload to S3 Failed", spaces='spaces/AAAARA65rqo', thread=None) else: print('No Data Update') send_message.send(message="Covid19 : No Data Update", spaces='spaces/AAAARA65rqo', thread=None) pass
def action(r_id, u_id, o_id, act, con): message = {} room = RoomInfo.objects.get(room_id=r_id) if act == '0': #杀人 player_state_change.kill(r_id, o_id) message = { 'type': '7', 'room_request_id': str(glob.room_request_id[r_id]), 'change': { o_id: "false" }, 'list': [u_id] } json = demjson.encode(message) #send_message.send(r_id,json) glob.room_request_content[r_id].append(json) elif act == '1': #救人 player_state_change.save(r_id, o_id) message = { 'type': '7', 'room_request_id': str(glob.room_request_id[r_id]), 'change': { o_id: "true" }, 'list': [u_id] } json = demjson.encode(message) #send_message.send(r_id, json) glob.room_request_content[r_id].append(json) elif act == '2': #狼人选人 glob.room_wolf_select[r_id][u_id] = o_id if len(glob.room_wolf_select[r_id] ) == glob.room_aliver_wolf_num[r_id]: #所有狼人都选完人 list = glob.room_wolf_select[r_id] v = list.values() #所有被选者 result = Counter(v).most_common(1)[0][0] #票数最多的id #杀了这个被选中的人 player_state_change.kill(r_id, result) message = { 'type': '6', 'room_request_id': str(glob.room_request_id[r_id]), 'id': result } json = demjson.encode(message) #send_message.send(r_id, json) glob.room_request_content[r_id].append(json) glob.room_wolf_select[r_id] = {} elif act == '3': #给警徽 room.sheriff_id = o_id room.save() message = { 'type': '10', 'room_request_id': str(glob.room_request_id[r_id]), 'list': { u_id: o_id } } json = demjson.encode(message) #send_message.send(r_id, json) glob.room_request_content[r_id].append(json) elif act == '4': #不给警徽 room.sheriff_id = '-1' room.save() message = { 'type': '10', 'room_request_id': str(glob.room_request_id[r_id]), 'list': { u_id: '-1' } } json = demjson.encode(message) #send_message.send(r_id, json) glob.room_request_content[r_id].append(json) elif act == '5': # 自爆 player_state_change.kill(r_id, u_id) player_state_change.kill(r_id, o_id) message = { 'type': '7', 'room_request_id': str(glob.room_request_id[r_id]), 'change': { u_id: 'false', o_id: "false" }, 'list': [u_id] } json = demjson.encode(message) #send_message.send(r_id, json) glob.room_request_content[r_id].append(json) room_state_change.change(1, r_id) elif act == '6': #狼人聊天 message = { 'type': '14', 'room_request_id': str(glob.room_request_id[r_id]), 'user_id': u_id, 'content': con } json = demjson.encode(message) send_message.send(r_id, json) else: message['type'] = '1' message['room_request_id'] = str(glob.room_request_id[r_id]) message['user_id'] = u_id message['error_message'] = 'error in action' json = demjson.encode(message) send_message.send(r_id, json) return
df_json = df.to_json('./covid19.json', orient='records') print('File Saved In Local') uploaded = upload_to_aws('./covid19.json', bucket_name, 'covid19.json') if uploaded: print('File Uploaded to S3 Success') send_message.send(message="Covid19 : File Uploaded to S3 Success", spaces='spaces/AAAARA65rqo', thread=None) else: print('File Upload to S3 Failed') send_message.send(message="Covid19 : File Upload to S3 Failed", spaces='spaces/AAAARA65rqo', thread=None) else: print('No Data Update') send_message.send(message="Covid19 : No Data Update", spaces='spaces/AAAARA65rqo', thread=None) pass if __name__ == '__main__': try: main() except: print('Something went wrong') send_message.send(message="Something Went Wrong in Covid19.py", spaces='spaces/AAAARA65rqo', thread=None)
def process(data): type = data['type'] room_id = data['room_id'] user_id = data['user_id'] message = {} #处理确认消息 if type == '0': r_request_id = data['room_request_id'] if int(r_request_id) == glob.room_request_id[room_id]: glob.room_mark[room_id][user_id] = 1 return #非确认消息 request_id = data['request_id'] #判断该请求是否已被处理 if int(request_id) < glob.user_request_id[user_id]: print globlalala print glob.user_request_id[user_id] print reqlalala print request_id return elif int(request_id) > glob.user_request_id[user_id]: message['type'] = '1' message['room_request_id'] = str(glob.room_request_id[room_id]) message['user_id'] = user_id message['error_message'] = 'error in request_id' json = demjson.encode(message) send_message.send(room_id, json) return else: print 4 glob.user_request_id[user_id] = glob.user_request_id[user_id] + 1 if type == '1': message['type'] = '18' message['room_request_id'] = str(glob.room_request_id[room_id]) if methods.lock_room(room_id, user_id) == False: message['result'] = 'false' json = demjson.encode(message) send_message.send(room_id, json) else: message['result'] = 'true' json = demjson.encode(message) send_message.send(room_id, json) room_state_change.change(0, room_id) elif type == '2': seat = data['seat'] methods.select_seat(room_id, user_id, seat) elif type == '3': assign_role.assign(data) #房间状态改变为查看手牌 room_state_change.change(0, room_id) elif type == '4': methods.next_step(room_id, user_id) elif type == '5': object_id = data['object_id'] act = data['action'] con = data['content'] actions.action(room_id, user_id, object_id, act, con) elif type == '6': she = data['sheriff'] methods.join_compaign_sheriff(room_id, user_id, she) elif type == '7': object_id = data['object_id'] methods.sheriff_vote(room_id, user_id, object_id) elif type == '8': methods.leave(room_id, user_id) elif type == '9': object1_id = data['object1_id'] object2_id = data['object2_id'] methods.connet_couples(room_id, user_id, object1_id, object2_id) elif type == '10': object_id = data['object_id'] methods.day_vote(room_id, user_id, object_id) elif type == '100': seat = data['seat'] methods.test(room_id, user_id, seat) return
def change(type,r_id): room = RoomInfo.objects.get(room_id = r_id) round = room.round state = room.state rule = room.rule time = 'night' guard_die_mark = False # 状态转移 role_alive = 'true' # 求各种角色的状态 cupid_alive = 'false' guard_alive = 'false' witch_alive = 'false' seer_alive = 'false' hunter_alive = 'false' if state >= 3 : # 游戏结束的判断 owner_id = glob.room_owner_id[r_id] id_list = glob.room_mark[r_id].keys() game_over = True # True 代表结束 if owner_id not in id_list: # 房主离开游戏 message = {'type': '12', 'room_request_id': str(glob.room_request_id[r_id]), 'reason': '3', 'request_content': glob.room_request_content[r_id]} json = demjson.encode(message) send_message.send(r_id, json) close_room.close(r_id, 3) return # 判断狼人是否还有存活的 for i in id_list: role = glob.user_role[i] alive = glob.user_alive[i] if role == 'wolf' and alive == 'true': game_over = False break if game_over == True: message = {'type': '12', 'room_request_id': str(glob.room_request_id[r_id]), 'reason': '1', 'request_content': glob.room_request_content[r_id]} json = demjson.encode(message) send_message.send(r_id, json) close_room.close(r_id, 1) return game_over = True # 判断好人是否存活 if rule == 0: for i in id_list: role = glob.user_role[i] alive = glob.user_alive[i] if role != 'wolf' and alive == 'true': game_over = False break else: for i in id_list: role = glob.user_role[i] alive = glob.user_alive[i] if role != 'wolf' and role != 'village' and alive == 'true': game_over = False break if game_over == True: message = {'type': '12', 'room_request_id': str(glob.room_request_id[r_id]), 'reason': '0', 'request_content': glob.room_request_content[r_id]} json = demjson.encode(message) send_message.send(r_id, json) close_room.close(r_id, 0) return # 判断丘比特和情侣是否赢 game_over = True couples = glob.room_couples_id[r_id] if len(couples) > 0: if (glob.user_role[couples[0]] == 'wolf' and glob.user_role[couples[1]] != 'wolf') or ( glob.user_role[couples[0]] != 'wolf' and glob.user_role[couples[1]] == 'wolf'): for id in id_list: if id in couples: if glob.user_alive[id] == 'false': game_over = False else: if glob.user_alive[id] == 'true': game_over = False else: game_over = False if game_over == True: message = {'type': '12', 'room_request_id': str(glob.room_request_id[r_id]), 'reason': '2', 'request_content': glob.room_request_content[r_id]} json = demjson.encode(message) send_message.send(r_id, json) close_room.close(r_id, 2) return for i in range(len(id_list)): role = glob.user_role[id_list[i]] alive = glob.user_alive[id_list[i]] if role == 'cupid': cupid_alive = alive elif role == 'guard': guard_alive = alive elif role == 'witch': witch_alive = alive elif role == 'seer': seer_alive = alive elif role == 'hunter': hunter_alive = alive if state == 1: state = state+1 elif state == 2: state = state+1 elif state == 3: #查看手牌 #第一夜,丘比特存在 if round == 1 and glob.room_role_number[r_id]['cupid'] != 0: state = state + 1 role_alive = cupid_alive #不是第一夜且守卫存在 | 第一夜,丘比特不存在,守卫存在 elif (round !=1 and glob.room_role_number[r_id]['guard'] != 0) or (round == 1 and glob.room_role_number[r_id]['cupid'] == 0 and glob.room_role_number[r_id]['guard'] != 0): state = 6 role_alive = guard_alive else: state = 7 elif state == 4: #丘比特 #待处理 state = state+1 elif state == 5: #情侣 if glob.room_role_number[r_id]['guard'] == 0: state = 7 else: state = state+1 role_alive = guard_alive elif state == 6: #守卫 state = state+1 elif state == 7: #狼人 if glob.room_role_number[r_id]['witch'] == 0: if glob.room_role_number[r_id]['seer'] == 0: if round == 1: state = 10 else: #判断猎人死没死 if glob.room_role_number[r_id]['hunter'] != 0 and hunter_alive == 'false' and guard_die_mark==False: time = 'night' state = 15 else: state = 13 else: state = 9 role_alive = seer_alive else: state = state+1 role_alive = witch_alive elif state == 8: #女巫 if glob.room_role_number[r_id]['seer'] == 0: if round == 1: state = 10 else: # 判断猎人死没死 if glob.room_role_number[r_id]['hunter'] != 0 and hunter_alive == 'false' and guard_die_mark==False: time = 'night' state = 15 else: state = 13 else: state = state+1 role_alive = seer_alive elif state == 9: #预言家 if round == 1: state = 10 else: # 判断猎人死没死 if glob.room_role_number[r_id]['hunter'] != 0 and hunter_alive == 'false' and guard_die_mark==False: time = 'night' state = 15 else: state = 13 elif state == 10: if type == 1: state = boom(r_id) else: state = state+1 elif state == 11: if type == 1: state = boom(r_id) else: state = state+1 elif state == 12: if type == 1: state = boom(r_id) else: if round == 1: #第一天 if glob.room_role_number[r_id]['hunter'] != 0 and hunter_alive == 'false' and guard_die_mark==False: time = 'night' state = 15 else: if glob.room_player_die[r_id] == False: state = 16 else: glob.room_player_die[r_id] = False state = 17 else: state = state+1 elif state == 13: if type == 1: state = boom(r_id) else: state = state+1 elif state == 14: #不能自爆 #猎人死 if glob.room_role_number[r_id]['hunter'] != 0 and hunter_alive == 'false' and guard_die_mark==False: time = 'day' state = 15 else: state = 16 elif state == 15: #不能自爆 guard_die_mark = True if round == 1 and time == 'night': state = 17 else: state = 16 elif state == 16: #投票遗言不能自爆 round = round + 1 # 第一夜,丘比特存在 if round == 1 and glob.room_role_number[r_id]['cupid'] != 0: state = state + 1 role_alive = cupid_alive # 不是第一夜且守卫存在 | 第一夜,丘比特不存在,守卫存在 elif (round != 1 and glob.room_role_number[r_id]['guard'] != 0) or ( round == 1 and glob.room_role_number[r_id]['cupid'] == 0 and glob.room_role_number[r_id][ 'guard'] != 0): state = 6 role_alive = guard_alive else: state = 7 elif state == 17: #夜晚遗言阶段,第一夜且有人死了 state = 13 else: message = {'type': '1', 'room_request_id': str(glob.room_request_id[r_id]), 'user_id': '-1','error_message':'error in room state'} json = demjson.encode(message) send_message.send(r_id, json) return room.round = round room.state = state room.save() # message = {'type':'5','room_request_id':str(glob.room_request_id[r_id]),'room_state':room.state, # 'role_alive':role_alive,'request_content':glob.room_request_content[r_id]} message = {'type':'5','room_request_id':str(glob.room_request_id[r_id]),'room_state':room.state,'role_alive':role_alive} json = demjson.encode(message) send_message.send(r_id,json) glob.room_request_content[r_id] = [] return
def assign(data): r_id = data['room_id'] wolf_num = data['wolf_num'] seer_num = data['seer_num'] hunter_num = data['hunter_num'] village_num = data['village_num'] witch_num = data['witch_num'] cupid_num = data['cupid_num'] guard_num = data['guard_num'] rule = data['rule'] glob.room_role_number[r_id]['wolf'] = int(wolf_num) glob.room_role_number[r_id]['seer'] = int(seer_num) glob.room_role_number[r_id]['hunter'] = int(hunter_num) glob.room_role_number[r_id]['witch'] = int(witch_num) glob.room_role_number[r_id]['cupid'] = int(cupid_num) glob.room_role_number[r_id]['guard'] = int(guard_num) room = RoomInfo.objects.get(room_id = r_id) room.rule = int(rule) id_list = glob.room_mark[r_id].keys() id_role = {} #id -> role num = glob.room_player_num[r_id] #房间人数 #先默认是village for i in range(len(id_list)): id_role[id_list[i]] = 'village' # 分配角色 i = 0 n = 0 while (i < int(wolf_num)): n = random.randint(0,num-1) if(id_role[id_list[n]] == 'village'): id_role[id_list[n]] = 'wolf' i = i + 1 i = 0 while (i < int(seer_num)): n = random.randint(0,num-1) if(id_role[id_list[n]] == 'village'): id_role[id_list[n]] = 'seer' i = i + 1 i = 0 while (i < int(hunter_num)): n = random.randint(0,num-1) if(id_role[id_list[n]] == 'village'): id_role[id_list[n]] = 'hunter' i = i + 1 i = 0 while (i < int(witch_num)): n = random.randint(0,num-1) if(id_role[id_list[n]] == 'village'): id_role[id_list[n]] = 'witch' i = i + 1 i = 0 while (i < int(cupid_num)): n = random.randint(0,num-1) if(id_role[id_list[n]] == 'village'): id_role[id_list[n]] = 'cupid' i = i + 1 i = 0 while (i < int(guard_num)): n = random.randint(0,num-1) if(id_role[id_list[n]] == 'village'): id_role[id_list[n]] = 'guard' i = i + 1 # 填写房间和用户信息 glob.room_aliver_wolf_num[r_id] = int(wolf_num) key = id_role.keys() for id in key: glob.user_role[id] = id_role[id] id_list = room.player_id.split(',') rolestr = "" for i in range(len(id_list)): if i == len(id_list): rolestr = rolestr + id_role[id_list[i]] else: rolestr = rolestr + id_role[id_list[i]] + "," room.player_role = rolestr room.save() #发送信息 message = {'type': '4', 'room_request_id': str(glob.room_request_id[r_id]), 'list': id_role} json = demjson.encode(message) send_message.send(r_id, json) #glob.room_request_content[r_id].append(json) #room_state_change.change(0,r_id) return
def process(data): type = data['type'] room_id = data['room_id'] user_id = data['user_id'] message = {} #处理确认消息 if type == '0': print 3 r_request_id = data['room_request_id'] if int(r_request_id) == glob.room_request_id[room_id]: glob.room_mark[room_id][user_id] = 1 return #非确认消息 request_id = data['request_id'] #判断该请求是否已被处理 if int(request_id) < glob.user_request_id[user_id]: return elif request_id > glob.user_request_id[user_id]: message['type'] = '1' message['room_request_id'] = str(glob.room_request_id[room_id]) message['user_id'] = user_id message['error_message'] = 'error in request_id' json = demjson.encode(message) send_message.send(room_id, json) return else: print 4 glob.user_request_id[user_id] = glob.user_request_id[user_id] + 1 if type == '1': if methods.lock_room(room_id, user_id) == False: message['type'] = '1' message['room_request_id'] = str(glob.room_request_id[room_id]) message['user_id'] = user_id message['error_message'] = 'error in lock room' json = demjson.encode(message) send_message.send(room_id, json) elif type == '2': seat = data['seat'] methods.select_seat(room_id, user_id, seat) elif type == '3': assign_role.assign(data) elif type == '4': num = data['need_num'] methods.next_step(room_id, user_id, num) elif type == '5': object_id = data['object_id'] act = data['action'] con = data['content'] actions.action(room_id, user_id, object_id, act, con) elif type == '6': she = data['sheriff'] methods.join_compaign_sheriff(room_id, user_id, she) elif type == '7': object_id = data['object_id'] methods.sheriff_vote(room_id, user_id, object_id) elif type == '8': methods.leave(room_id, user_id) elif type == '9': object1_id = data['object1_id'] object2_id = data['object2_id'] methods.connet_couples(room_id, user_id, object1_id, object2_id) elif type == '100': seat = data['seat'] methods.test(room_id, user_id, seat) return
def run_simulation(contacts_file): global messages global messages_ITA global transactions global MID_counter time_begin = datetime.now() ############################# Data Preparation ############################ print('Start preparing data for the simulation') # Generates message ID (MID) MID_counter = 0 # messages initiated messages = [] # {[MID,receiver] : timeR} messages_ITA = {} # messages received: {[MID,receiver] : timeR - timeB} transactions = {} set_sim = Settings_Simulation(st.START, st.INITIATE_DURATION, st.MAX_DELAY, st.INITIATE_INTERVAL, st.NUM_INITIATE, st.PERCENT_NODES_USED, st.sender_status_check, st.receiver_status_check) contacts = pd.read_csv(contacts_file) # NOTE: the delay/drop rates for different schedules should be tested # Previous runs have shown if all nodes share the same receive schedule, # then the delivery delay decreases and drop rate decreases PID = np.concatenate((contacts['node1'].unique(),contacts['node2'].unique())) PID = np.unique(PID) num_phone_total = len(PID) print('Select a portion (setting.PERCENT_NODES_USED) of contact traces') # Subset a group of nodes contacts = node_select(contacts, num_phone_total, set_sim.perc_nodes) num_phone_chosen = int(np.floor(num_phone_total*set_sim.perc_nodes)) print('Group contact traces by nodes') # Split the contact traces by nodes; this provides a speed advantage contacts_grouped = split_by_node(contacts) # Update PID, necessary when only a subset of nodes is used PID = list(contacts_grouped.keys()) schedules = create_schedule(PID, st.seed_schedule) ########################################################################### #################### Message Propagation Simulation ####################### print('Start message propagation simulation!!') for t in range(set_sim.start, set_sim.init_dur + set_sim.max_delay + 1): if t <= set_sim.start+set_sim.init_dur: # Initiate, select NUM_INITIATE nodes from available nodes, call initiate() if t % set_sim.init_int == 0: # It's entirely possible that no one is nearby to receive the message initiators = random.sample(PID, set_sim.num_init) if (len(initiators) > 0): for initiator in initiators: initiate(contacts_grouped, schedules, messages, messages_ITA, transactions, MID_counter, initiator, t) MID_counter = MID_counter + 1 # At each t, update messages_ITA # Drop messages past MAX_DELAY since timeReceived messages_ITA = {k:v for k,v in messages_ITA.items() if v+set_sim.max_delay >=t} if bool(messages_ITA): # ASSUMPTION: Messages do not jump more than once at t # This is because we cannot add to dictionary while looping over it # TODO: add a loop inside the loop to do chained jumps keys = list(messages_ITA) for key in keys: sender = key[1] # If check_sender/check_receiver is False, the message can be sent all the time # If True, then check phone status if (not set_sim.check_sender) | (status_check(sender, schedules, t)): grouped_sender = contacts_grouped[sender] receivers = grouped_sender[(grouped_sender['start']<=t) & (grouped_sender['end']>=t)] #if not empty if not(receivers.empty): for index, receiver in receivers.iterrows(): if receiver['node1'] == sender: if (not set_sim.check_receiver) | status_check(receiver['node2'], schedules, t): send(messages, messages_ITA, transactions, key[0], receiver['node2'], t) else: if (not set_sim.check_receiver) | status_check(receiver['node1'], schedules, t): send(messages, messages_ITA, transactions, key[0], receiver['node1'], t) print("The time is", t) ########################################################################### ######################## Key Metrics Calculation ########################## if (not transactions): delay_mean = "No successfully initiated messages" drop_rate = 1 return ([delay_mean, drop_rate]) # Calculate average delivery delay delay_mean = sum(transactions.values())/len(transactions) # Calculate drop rate messages_total = len(messages) MID_list,receiver_list = zip(*list(messages_ITA)) messages_success = len(set(MID_list)) print("Number of total messages initiated: ", messages_total) print("Number of successful messages initiated: ", messages_success) drop_rate = (messages_total - messages_success) / messages_total timer = datetime.now()-time_begin print('The simulation is a success!!') print('This simulation took', timer) return ([delay_mean, drop_rate])
def do_sendmessage(self, line): line = line.split() address = line[0] message = ' '.join(line[1:]) send_message.send(message, address)
def getUrl(): print(inputUrl.get()) print(textInput.get(0.0, 'end')) send_message.send(inputUrl.get(), textInput.get(0.0, 'end')) tkinter.messagebox.showinfo('Prompt', 'Sent successfully!')
def action(r_id,u_id,o_id,act,con): message = {} room = RoomInfo.objects.get(room_id = r_id) if act == '0': #杀人 player_state_change.kill(r_id,o_id) role = glob.user_role[u_id] message = {'type':'7','room_request_id':str(glob.room_request_id[r_id]), 'change':{o_id:"false"},'role':role} json = demjson.encode(message) send_message.send(r_id,json) #glob.room_request_content[r_id].append(json) elif act == '1': #救人 player_state_change.save(r_id,o_id) role = glob.user_role[u_id] message = {'type': '7', 'room_request_id': str(glob.room_request_id[r_id]), 'change': {o_id: "true"}, 'role': role} json = demjson.encode(message) send_message.send(r_id, json) #glob.room_request_content[r_id].append(json) elif act == '2': #狼人选人 message = {'type': '6', 'room_request_id': str(glob.room_request_id[r_id]),'action':'0', 'wolf_id': u_id, 'object_id':o_id, 'result':'true'} json = demjson.encode(message) send_message.send(r_id, json) elif act == '3': #给警徽 glob.room_sheriff_id[r_id] = o_id room.sheriff_id = o_id room.save() message = {'type': '10', 'room_request_id': str(glob.room_request_id[r_id]), 'list': {u_id:o_id}} json = demjson.encode(message) send_message.send(r_id, json) #glob.room_request_content[r_id].append(json) elif act == '4': #不给警徽 glob.room_sheriff_id[r_id] = '-1' room.sheriff_id = '-1' room.save() message = {'type': '10', 'room_request_id': str(glob.room_request_id[r_id]), 'list': {u_id: '-1'}} json = demjson.encode(message) #send_message.send(r_id, json) glob.room_request_content[r_id].append(json) elif act == '5': # 自爆 player_state_change.kill(r_id, u_id) #player_state_change.kill(r_id, o_id) role = glob.user_role[u_id] message = {'type': '7', 'room_request_id': str(glob.room_request_id[r_id]), 'change': {u_id:'false'}, 'role': role} json = demjson.encode(message) send_message.send(r_id, json) #glob.room_request_content[r_id].append(json) room_state_change.change(1,r_id) elif act == '6': #狼人聊天 message = {'type': '14', 'room_request_id': str(glob.room_request_id[r_id]), 'user_id':u_id,'content':con} json = demjson.encode(message) send_message.send(r_id, json) elif act == '7': #狼人杀人 if r_id not in glob.room_wolf_select: glob.room_wolf_select[r_id] = o_id glob.room_wolf_select_num[r_id] = 1 else: if glob.room_wolf_select[r_id] != o_id: message = {'type': '6', 'room_request_id': str(glob.room_request_id[r_id]), 'action': '1', 'wolf_id': u_id,'object_id': o_id,'result':'false'} else: message = {'type': '6', 'room_request_id': str(glob.room_request_id[r_id]), 'action': '1', 'wolf_id': u_id, 'object_id': o_id, 'result': 'true'} glob.room_wolf_select_num[r_id] = glob.room_wolf_select_num[r_id] + 1 json = demjson.encode(message) send_message.send(r_id, json) if glob.room_wolf_select_num[r_id] == glob.room_aliver_wolf_num[r_id]: #所有狼人都选完人 if o_id != glob.room_protect_id[r_id]: #不是被守护的人 #杀了这个被选中的人 player_state_change.kill(r_id, o_id) role = "wolf" message = {'type': '7', 'room_request_id': str(glob.room_request_id[r_id]), 'change': {o_id: "false"}, 'role': role} json = demjson.encode(message) send_message.send(r_id, json) #glob.room_request_content[r_id].append(json) glob.room_wolf_select[r_id] = {} elif act == '8': #守卫 if o_id != glob.room_protect_id[r_id]: glob.room_protect_id[r_id] = o_id message = {'type':'15', 'room_request_id': str(glob.room_request_id[r_id]), 'user_id':o_id} json = demjson.encode(message) glob.room_request_content[r_id].append(json) else: message['type'] = '1' message['room_request_id'] = str(glob.room_request_id[r_id]) message['user_id'] = u_id message['error_message'] = 'error in guard the same person' json = demjson.encode(message) send_message.send(r_id, json) else: message['type'] = '1' message['room_request_id'] = str(glob.room_request_id[r_id]) message['user_id'] = u_id message['error_message'] = 'error in action' json = demjson.encode(message) send_message.send(r_id, json) return