def publish(self, question) -> None: """ Публикуем данные из объекта Question в Telegram и сохраняем запись в SQLite базу данных. :param question: объект Question или QuestionWithCode :return: None """ # ID всех опубликованных сообщений в Telegram которые связаны с данным опросом. messages_id = [] edit_question_html = self.edit_this_question(question) if question.is_code: """ Для вопроса с кодом, мы отправим две сообщения, одну с изображением кода другую с опросом. """ if question.show_title_in_code: # Не дублировать вопрос в описании изображения, он уже есть в самой изображении. image_caption = edit_question_html else: image_caption = f'{question.title}\n\n{edit_question_html}' send_image = self.telebot.send_photo( chat_id=self.chat_id, photo=question.code_highlight(), caption=image_caption, parse_mode='html') messages_id.append(str(send_image.message_id)) post = self.telebot.send_poll( chat_id=self.chat_id, question=question.title, is_anonymous=question.is_anonymous, options=question.options, type=question.q_type, correct_option_id=question.correct_option_id, explanation=question.explanation, ) messages_id.append(str(post.message_id)) if not question.is_code: edit = self.telebot.send_message(chat_id=self.chat_id, text=edit_question_html, parse_mode='html', disable_web_page_preview=True) messages_id.append(str(edit.message_id)) DBQ.create( **{ 'title': question.title, 'last_checksum': question.checksum, 'json_file': question.short_filepath, 'message_id': ','.join(messages_id), 'created_on': int(time()) })
def question_confirmation_state(message, user, is_entry=False): if is_entry: bot.send_message(message.chat.id, DICTIONARY['ua']['question_confirmation_msg'] % user.current_question, parse_mode="Markdown", reply_markup=get_question_confirmation_keyboard('ua')) else: if message.text == DICTIONARY['ua']['question_confirmation_btn']: question = Question(text=user.current_question, subscribed_users=[]) question.save() bot.send_message(message.chat.id, "Дякуємо Вам за питання!") return return_to_your_state(user) elif message.text == DICTIONARY['ua']['question_decline_btn']: return True, 'ask_mon_question_state' return False, ''
def add_questions(): question_content = request.json['question_content'] question_vote = 0 question_tag = request.json['question_tag'] is_open = 1 new_question = Question(question_content, question_vote, question_tag, is_open) db.session.add(new_question) db.session.commit() return question_schema.jsonify(new_question)
def addQuestion(self, id, title, type, surveyId): engine = create_engine('sqlite:///database.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() newQuestion = Question(id=id, title=title, type=type, surveyId=surveyId) session.add(newQuestion) session.commit() session.close()
def universal_callback_query_handler(reply, user): if reply.data == DICTIONARY['ua']['excursion_1_button']: bot.send_photo(reply.from_user.id, photo=open('img/lego.jpg', 'rb'), caption=DICTIONARY['ua']['excursion_1_msg'], reply_markup=get_inline_back_keyboard('ua')) elif reply.data == DICTIONARY['ua']['excursion_2_button']: bot.send_photo(reply.from_user.id, photo=open('img/party.jpg', 'rb'), caption=DICTIONARY['ua']['excursion_2_msg'], reply_markup=get_inline_back_keyboard('ua')) elif reply.data == DICTIONARY['ua']['excursion_3_button']: bot.send_photo(reply.from_user.id, photo=open('img/vidpochynok.jpg', 'rb'), caption=DICTIONARY['ua']['excursion_3_msg'], reply_markup=get_inline_back_keyboard('ua')) elif reply.data == DICTIONARY['ua']['excursion_4_button']: bot.send_photo(reply.from_user.id, photo=open('img/stendy.jpeg', 'rb'), caption=DICTIONARY['ua']['excursion_4_msg'], reply_markup=get_inline_back_keyboard('ua')) elif reply.data == DICTIONARY['ua']['excursion_5_button']: bot.send_photo(reply.from_user.id, photo=open('img/drawing.jpg', 'rb'), caption=DICTIONARY['ua']['excursion_5_msg'], reply_markup=get_inline_back_keyboard('ua')) elif reply.data == DICTIONARY['ua']['back_to_class_button']: bot.send_photo(reply.from_user.id, photo=open('img/excursion.png', 'rb'), caption=DICTIONARY['ua']['excursion_msg'], reply_markup=get_excursion_button_keyboard('ua')) # button for questions' rating elif reply.data == DICTIONARY['ua']['back_button']: bot.send_photo(reply.from_user.id, photo=open('img/excursion.png', 'rb'), caption=DICTIONARY['ua']['excursion_msg'], reply_markup=get_excursion_button_keyboard('ua')) else: question = Question.objects(question_id=reply.data).first() if question is None: pass else: if user.user_id not in question.subscribed_users: question.subscribed_users.append(user.user_id) question.rating += 1 question.save() else: bot.send_message(reply.from_user.id, "Ви вже підтримали це питання.") bot.answer_callback_query(reply.id)
def add_question(payload): body = request.get_json() try: question = body.get("question", None) category_id = body.get("category_id", None) Type = body.get("Type", None) if exist(Question, question, "question"): abort(422) else: new_q = Question(question=question, category_id=category_id, Type=Type) new_q.insert() except: abort(422) return (jsonify({ "success": True, "added_question_id": new_q.id, "added_question": new_q.question, "Type": new_q.Type, "category": new_q.category.format() }))
def add_question_from_api(json_data): """ Used to add a new question to the database. :param json_data: the question we want to add :return: None """ session = init() try: new_question = Question(label=json_data['label'], value=json_data['value'], info=json_data['info']) session.add(new_question) session.commit() session.close() except: session.rollback() session.close() print("Error: Could not add question from api")
def add_question(label, value, info): """ Used to add a new question to the database. :param label: Question label :param value: Question value :param info: More information about the question :param session: current session :return: None """ session = init() try: new_question = Question(label=label, value=value, info=info) session.add(new_question) session.commit() session.close() except: session.rollback() session.close() print("Error: Could not add question")
def rating_mon_question_state(message, user, is_entry=False): if is_entry: bot.send_message(message.chat.id, "Список питань до МОН:", reply_markup=get_back_button_keyboard('ua')) for _question in Question.objects().order_by('rating'): bot.send_message(message.chat.id, DICTIONARY['ua']['rated_questions_msg'].format( _question.text, _question.rating), parse_mode="Markdown", reply_markup=get_rating_mon_question_keyboard( _question.question_id, 'ua')) else: if message.text == DICTIONARY['ua']['back_button']: return return_to_your_state(user) else: bot.send_message(message.chat.id, DICTIONARY['ua']['no_button'], reply_markup=get_back_button_keyboard('ua')) return False, ''
def bulk_add_example_data(payload): categories = pd.read_csv("initialdata/categories.csv", sep=";") movies = pd.read_csv("initialdata/movies.csv", sep=";") questions = pd.read_csv("initialdata/questions.csv", sep=";") movie_answers = pd.read_csv("initialdata/question_movie_mapping.csv", sep=";", decimal=",") #Add example categories for i, row in categories.iterrows(): new = Category(category=row["Category"]) new.insert() #Add example movies for i, row in movies.iterrows(): new = Movie(title=row["title"], description=row["description"], category_id=row["category_id"]) new.insert() #Add example questions for i, row in questions.iterrows(): new = Question(question=row["question"], category_id=row["category_id"], Type=row["Type"]) new.insert() #Add Question Answers for i, row in movie_answers.iterrows(): for question_id in movie_answers.columns[1:]: new = QuestionMovie(question_id=question_id, movie_id=row["movie_id"], answer=row[question_id]) new.insert() return (jsonify({"success": True}))
from quiz import Quiz from database import Question as DBQ if __name__ == '__main__': quiz = Quiz() for q in quiz.get_all_quiz(): qdb = DBQ.get_or_none(DBQ.json_file == q.short_filepath) if qdb is None: quiz.publish(q) else: if q.checksum != qdb.last_checksum: # Удаляем сообщения из канала quiz.delete_messages(qdb.message_id) # Удаляем запись из БД qdb.delete_instance() quiz.publish(q)
def insert_data(evaluations): for evaluation in evaluations: evaluation_data = {} now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # course info located in first row, first td row = evaluation.xpath('.//tr/td')[0] evaluation_data["source"] = parser.get_data_source(evaluation) evaluation_data["instructor"] = parser.get_instructor_name(row) evaluation_data["course_name"] = parser.get_course_name(row) evaluation_data["semester_full"] = parser.get_full_semester(row) evaluation_data["semester"] = parser.get_semester( evaluation_data["semester_full"]) evaluation_data["year"] = parser.get_year( evaluation_data["semester_full"]) evaluation_data["reg_index"] = parser.get_reg_index(row) evaluation_data["course_code"] = parser.get_course_code(row) evaluation_data['school'] = parser.get_school( evaluation_data["course_code"]) evaluation_data['department'] = parser.get_department( evaluation_data["course_code"]) evaluation_data['course'] = parser.get_course( evaluation_data["course_code"]) evaluation_data['section'] = parser.get_section( evaluation_data["course_code"]) evaluation_data["enrollments"] = parser.get_num_enrollments(row) evaluation_data["responses"] = parser.get_num_responses(row) evals = parser.get_eval_rows(evaluation) parser.get_school(evaluation_data["course_code"]) course_session = session() course = Course(course_name=evaluation_data["course_name"], year=evaluation_data["year"], semester=evaluation_data["semester"], school=evaluation_data['school'], department=evaluation_data['department'], course=evaluation_data['course'], section=evaluation_data['section'], regindex=evaluation_data["reg_index"], source=evaluation_data['source'], enrollments=evaluation_data['enrollments'], responses=evaluation_data['responses'], instructor=evaluation_data["instructor"], created_at=now) course_session.close() course_id = add_course(course_session, course) if course_id == -1: print("Skipping course [{}] - {} - {}".format( course_id, evaluation_data["course_name"], evaluation_data["instructor"])) else: print("Added course [{}] - {} - {}".format( course_id, evaluation_data["course_name"], evaluation_data["instructor"])) evaluation_data["questions"] = evals #print("Instructor {} : {}".format(evaluation_data["instructor"], evals)) evals_json = json.dumps(evaluation_data) evals_json = json.loads(evals_json) for e in evals_json['questions']: #print(evals_json['questions'][e]) q_text = evals_json['questions'][e]['question_text'] q_type = evals_json['questions'][e]['question_type'] responses = evals_json['questions'][e]['response'] question_session = session() question = Question(question_text=bytearray(q_text, 'utf-8'), question_type=q_type, created_at=now) q_id = add_question(question_session, question) question_session.close() answer_session = session() rate_1, rate_2, rate_3, rate_4, rate_5, blank = 0, 0, 0, 0, 0, 0 responses = OrderedDict(sorted(responses.items())) for indx, inc in enumerate(responses): if indx == 0: rate_1 = responses[inc] elif indx == 1: rate_2 = responses[inc] elif indx == 2: rate_3 = responses[inc] elif indx == 3: rate_4 = responses[inc] elif indx == 4: rate_5 = responses[inc] elif indx == 5: blank = responses[inc] answer = Answer(course_id=course_id, question_id=q_id, rating_1=rate_1, rating_2=rate_2, rating_3=rate_3, rating_4=rate_4, rating_5=rate_5, blank=blank, created_at=now) add_answer(answer_session, answer) answer_session.close()