def change_debt(_: types.Message, value: int, user: dict): new_value = user['debt'] + value action = "увеличен" if value > 0 else "уменьшен" current_time = h.get_current_time() info = { "user_id": user['id'], "value": value, "request_date": current_time, "answer_date": current_time, "approved": True, "is_admin": True, } _ = db.create_application(info) bot.send_message( ADMIN_ID, f"Долг пользователя {h.get_user_full_name(**user)} был {action} на {abs(value):,}.\n" f"Его нынешний долг составляет {new_value:,}.") info = {"debt": new_value} db.update_user(user['id'], info) bot.send_message( user['id'], f"Ваш долг был {action} администратором на {abs(value):,}.\n" f"Новая сумма вашего долга составляет {new_value:,}.")
def __init__(self, rate, chunk_size): self._rate = rate self.chunk_size = chunk_size self._num_channels = 1 self._buff = queue.Queue() self.closed = True self.start_time = get_current_time() self.restart_counter = 0 self.audio_input = [] self.last_audio_input = [] self.result_end_time = 0 self.is_final_end_time = 0 self.final_request_end_time = 0 self.bridging_offset = 0 self.last_transcript_was_final = False self.new_stream = True self._audio_interface = pyaudio.PyAudio() self._audio_stream = self._audio_interface.open( format=pyaudio.paInt16, channels=self._num_channels, rate=self._rate, input=True, frames_per_buffer=self.chunk_size, # Run the audio stream asynchronously to fill the buffer object. # This is necessary so that the input device's buffer doesn't # overflow while the calling thread makes network requests, etc. stream_callback=self._fill_buffer, )
def decline_application(application: dict): info = {"answer_date": h.get_current_time()} db.update_application(application['id'], info) bot.send_message(ADMIN_ID, f"Вы отклонили заявку.") user = db.get_user(application['user_id']) action = "получение" if application['value'] > 0 else "погашение" bot.send_message( user['id'], f"Ваша заявка на {action} суммы в размере {abs(application['value']):,} отклонена.\n" f"Ваш общий долг составляет {user['debt']:,}.")
def connect(): classCode = str(request.headers['Referer']).split("/")[4] if not hasAccessToClass(classCode): return join_room(classCode) io.emit('someone-connected', { 'sender_name': session.get('username'), 'message': session.get('username') + " has joined the chat", 'time': get_current_time() }, room=classCode)
def approve_application(application: dict): info = { "answer_date": h.get_current_time(), "approved": True, } db.update_application(application['id'], info) bot.send_message(ADMIN_ID, f"Вы одобрили заявку.") user = db.get_user(application['user_id']) info = {"debt": user['debt'] + application['value']} db.update_user(user['id'], info) action = "получение" if application['value'] > 0 else "погашение" bot.send_message( user['id'], f"Ваша заявка на {action} суммы в размере {abs(application['value']):,} одобрена.\n" f"Ваш общий долг составляет {user['debt'] + application['value']:,}.")
def handle_message(data): #getting the class code thorugh the URL classCode = str(request.headers['Referer']).split("/")[4] message = data['text'] current_time = get_current_time() last_chat_id = db.execute( "INSERT INTO chats(of_class_code, sender_id, sender_name, message, time) VALUES(:classCode, :user_id, :username, :message, :time)", classCode=classCode, user_id=session.get('user_id'), username=session.get('username'), message=message, time=current_time) io.emit('send-message', { 'sender_name': session.get('username'), 'message': message, 'time': current_time, 'chat_id': last_chat_id }, room=classCode)
def make_request(user_id: int, value: int, is_loan: bool): if is_loan: message_to_user = f"Ваша заявка на получение долга в размере {value:,} отправлена на рассмотрение." message_to_admin = "запросил(-а) в долг сумму" else: message_to_user = f"Ваше уведомление о совершении оплаты в размере {value:,} находится на проверке." message_to_admin = "уменьшил(-а) сумму долга на" value = -value info = { "user_id": user_id, "value": value, "request_date": h.get_current_time(), "is_admin": False, } application = db.create_application(info) bot.send_message(user_id, f"{message_to_user}\n" f"Отмена заявки: /cancel") user = db.get_user(user_id) bot.send_message( ADMIN_ID, f"{h.get_user_full_name(**user)} {message_to_admin} {abs(value):,}\n" f"Одобрить: /approve_{application['id']}\n" f"Отклонить: /decline_{application['id']}")
def upload(class_code): if request.method == "POST": if not isTeacherOfclass(class_code): return render_template("error.html", name="restricted to teachers") if "file" not in request.files: return render_template("upload.html", error=True) File = request.files['file'] if not File.filename: return render_template("upload.html", error=True) if not request.form.get("comment"): comment = " " else: comment = request.form.get("comment") Filename = secure_filename(File.filename) FileData = File.read() db.execute( "INSERT INTO files(file_name, time, comment, class_code, file_data) VALUES(:file_name, :time, :comment, :class_code, :file_data)", file_name=Filename, time=get_current_time(), comment=comment, file_data=FileData, class_code=class_code) return redirect("/class/" + class_code) else: if not isTeacherOfclass(class_code): return render_template("error.html", name="restricted to teachers") class_Data = db.execute("SELECT * FROM classes WHERE code = :code", code=class_code)[0] return render_template( "upload.html", code=class_code, class_name=class_Data['class_name'], isTeacher=class_Data['teacher_id'] == session.get('user_id'))
def listen_print_loop(responses, stream, lights=None): """Iterates through server responses and prints them. The responses passed is a generator that will block until a response is provided by the server. Each response may contain multiple results, and each result may contain multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we print only the transcription for the top alternative of the top result. In this case, responses are provided for interim results as well. If the response is an interim one, print a line feed at the end of it, to allow the next result to overwrite it, until the response is a final one. For the final one, print a newline to preserve the finalized transcription. """ for response in responses: if get_current_time() - stream.start_time > STREAMING_LIMIT: stream.start_time = get_current_time() break if not response.results: continue result = response.results[0] if not result.alternatives: continue transcript = result.alternatives[0].transcript result_seconds = 0 result_nanos = 0 if result.result_end_time.seconds: result_seconds = result.result_end_time.seconds if result.result_end_time.nanos: result_nanos = result.result_end_time.nanos stream.result_end_time = int((result_seconds * 1000) + (result_nanos / 1000000)) corrected_time = (stream.result_end_time - stream.bridging_offset + (STREAMING_LIMIT * stream.restart_counter)) # Display interim results, but with a carriage return at the end of the # line, so subsequent lines will overwrite them. if result.is_final: sys.stdout.write(GREEN) sys.stdout.write('\033[K') sys.stdout.write(str(corrected_time) + ': ' + transcript + '\n') stream.is_final_end_time = stream.result_end_time stream.last_transcript_was_final = True # Exit recognition if any of the transcribed phrases could be # one of our keywords. if re.search(r'\b(exit|ukončit)\b', transcript, re.I): sys.stdout.write(YELLOW) sys.stdout.write('Ukončuji...\n') stream.closed = True break # Keyword spotting matches = kw_spotter([transcript], FLAGS.keywords) kw_decoded = kw_decoder(matches, FLAGS.device_map, FLAGS.location_map, FLAGS.command_map) if kw_decoded: device, locations, command = kw_decoded[0] sys.stdout.write(LIGHT_GREEN) sys.stdout.write( f"device: {device} locations: {locations} command: {command}\n" ) if lights and "light" in device: light_commands(lights, locations, command) kw_decoded.clear() else: sys.stdout.write(RED) sys.stdout.write('\033[K') sys.stdout.write(str(corrected_time) + ': ' + transcript + '\r') stream.last_transcript_was_final = False