def handle_author_name(message): id = parser.get_man_id_by_name(message.text) if id is not None: films_list = parser.get_film_list_by_director_id(id) obtain_films_list(message, films_list) else: bot.send_message(message.chat.id, 'Такой режиссёр не найден')
def handle_help(message): bot.send_message( message.chat.id, "I'll show you most popular shows at https://anilist.co/") bot.send_message(message.chat.id, "The commands are:\n" "\n/help" "\n/start")
def handle_stream_pending_support(json): users = [] query = sql.Customer.select().where(((sql.Customer.link == json['user']))).dicts().execute() for i in query: users.append(i) if users: emit('stream_linked_support', { "user": users[0] }) return; users = [] query = sql.Customer.select().where(((sql.Customer.link == '~') & ~(sql.Customer.link == json['user']))).dicts().execute() for i in query: users.append(i) # Auto-link customer with operator if users != []: sql.Customer.update({sql.Customer.link: json['user']}).where(sql.Customer.chat_id == users[0]['chat_id']).execute() bot.send_message(users[0]['chat_id'], 'Оператор на связи! Вы можете начать диалог с ним прямо сейчас') emit('stream_linked_support', { "user": users[0] })
def on_deleted(self, event): if not event.is_directory: deleted_file_name = os.path.splitext( os.path.basename(event.src_path))[0] logger.info(f'page {deleted_file_name} was deleted') send_message(f'Удалена страница Dokuwiki: {deleted_file_name}', f'')
def handle_callback_query(query): logger.info(query.data) # query.answer() chat_id = query.message.chat.id arr = query.data.split(":") query_type, query_value = arr[0], arr[1] if query_type == 'download_bilibili_cover': # 提取 B 站视频的封面图片 pic_url = services.get_bilibili_cover_img(query_value) bot.send_photo(chat_id=chat_id, photo=pic_url) elif query_type == 'download_bilibili_video': query.edit_message_text(text="小关正在加速为您下载视频,稍后会将下载链接呈上!!!") title = services.download_bilibili_video(query_value) logger.debug('Download {}'.format(title)) download_url = 'https://telegram.pushy.site/download/{}.flv'.format( title) bot.send_message(chat_id=chat_id, text='下载链接为: {}'.format(download_url)) elif query_type == 'download_zhihu_video': download_url = services.get_zhihu_video_download_url( 'https://www.zhihu.com/video/{}'.format(query_value)) query.edit_message_text(text=download_url)
def refer_link(user): text = ''' *КОНКУРС "ПОДКЛЮЧИ КОЛЛЕГУ"* Итак, смотри внимательно, всего 2 условия конкурса:👇 ✅ Тебе нужно участвовать абсолютно во всех активностях и в конкурсах в чат-боте; ✅Тебе необходимо подключить как можно больше коллег. Как это сделать: 1. Под этим сообщением твоя индивидуальная ССЫЛКА. 2. Скопируй её. 3. Именно ЭТУ ссылку тебе необходимо направить коллегам, которые еще не подключены. Ссылку направляй любым удобным способом (электронная почта, WhatsApp, Telegram и д.р.). ‼️Главное, тебе необходимо проверить, чтобы коллеги по твоей ссылке прошли регистрацию и подключились. При выполнении всех этих пунктов - твой ценный балл будет зачтен в твою копилку! Помни, чем больше подключений, тем выше твоя активность. ''' response = bot.send_message(chat_id=user.tg_id, text=text, parse_mode='Markdown') save_message(response, 'income', user.tg_id) link = f'https://t.me/{Config.BOT_NAME}?start=refer_{user.id}' response = bot.send_message(chat_id=user.tg_id, text=link) save_message(response, 'income', user.tg_id)
def message_income_handler(message): try: if message.chat.type == 'group': pass else: # Смотрим, есть ли юзер в одном из чатов, добавленных в БД user_in_chats = [] for chat in Chat.select(): user_status = bot.get_chat_member(chat_id=chat.chat_id, user_id=message.from_user.id).status if user_status != 'left' and user_status != 'kicked': user_in_chats.append(chat) # Если есть, то пытаемся распознать событие if len(user_in_chats) != 0: event_string = bot_event_handler.parse_event(message.text.encode('utf-8')) bot.reply_to(message, "Recognized event:\n" + event_string) else: bot.send_message(message.chat.id, 'Youre not in one of my group chats') # Если удалось распознать эвент # То отправляем распознанное событие и спрашиваем, все ли так # Если все ок, то добавляем эвент в календарь и завершаем разговор # Если не ок, то просим ввести заново # Если не удалось, то пишем, что не удалось и говорим если что обратиться к /help # Если все так, то добавляем эвент # Если нет, то отвечаем, что не удалось его найти ни в одной из групп, где есть бот pass '''''' pass except Exception as e: logger.debug(e.message)
def handle_messages(message): user = users_services.get_user(message.chat.id) if user: optional_of_chosen_action = action_services \ .get_actions_by_message_id_and_phrase(user.state_id, message.text) # There could be problems, when user types message, which fits several actions print(optional_of_chosen_action) if len(optional_of_chosen_action) == 1: chosen_action = optional_of_chosen_action[0] decision: UserDecision = user_decision_services.find_by_action_id( chosen_action.id) if decision is None: bot.send_message( message.chat.id, 'Не знаю что сказать дальше....', ) return try: user.state_id = decision.state_id send_message(user, message) db.session.commit() except Exception: db.session.rollback() raise else: bot.sende_message(message.chat.id, 'Кто это?! Уйди от меня!!!')
def audio_message(update, context): from app import create_app app = create_app(config_class=Config) app.app_context().push() audio = update.message.voice.get_file() audio = audio.download_as_bytearray() rand = str(random.randint(100000,1000000)) filename = rand+"note.ogg" with open(os.path.join(Config.UPLOAD_FOLDER, filename), 'wb') as f: f.write(audio) subprocess.run(['ffmpeg', '-i', os.path.join(Config.UPLOAD_FOLDER, filename), os.path.join(Config.UPLOAD_FOLDER, filename.replace('ogg', 'wav'))]) with sr.AudioFile(os.path.join(Config.UPLOAD_FOLDER, filename.replace('ogg', 'wav'))) as s: r = sr.Recognizer() txt = r.listen(s) text = r.recognize_google(txt, language = 'ru-RU') note = Note() note.text = text note.sound_file = filename note.creator = User.query.filter_by(tg_id=update.message.chat_id).first().id db.session.add(note) db.session.commit() bot.send_message( chat_id=update.message.chat_id, text=f"Заметка сохранена" )
def get_date(message): dates[message.chat.id] = message.text conn[message.chat.id]=sqlite3.connect('mthcs.db') list=get_match(conn[message.chat.id], names[message.chat.id], dates[message.chat.id]) if len(list)!=0: name,score,goals=list[0] answer = 'Матч {Name} закончился со счетом {Score} голы забили {Goals}, Вам понравилась моя работа?'.format(Name=name, Score=score, Goals=goals) keyboard = telebot.types.InlineKeyboardMarkup() key_yes = telebot.types.InlineKeyboardButton(text='Да', callback_data='yes') keyboard.add(key_yes) key_no = telebot.types.InlineKeyboardButton(text='Нет', callback_data='no') keyboard.add(key_no) key_idk = telebot.types.InlineKeyboardButton(text='Не знаю', callback_data='idk') keyboard.add(key_idk) bot.send_message(message.chat.id, text=answer, reply_markup=keyboard) else: answer="Данных по этому матчу найти не удалось :( , Не хотели бы вы нам помочь?" keyboard = telebot.types.InlineKeyboardMarkup() key_yes = telebot.types.InlineKeyboardButton(text='Да', callback_data='Yes') keyboard.add(key_yes) key_no = telebot.types.InlineKeyboardButton(text='Нет', callback_data='No') keyboard.add(key_no) key_idk = telebot.types.InlineKeyboardButton(text='Не знаю', callback_data='Idk') keyboard.add(key_idk) bot.send_message(message.chat.id, text=answer, reply_markup=keyboard)
def main(): long_poll = VkBotLongPoll(bot.vk, bot.group_id) print('VkBot started') for event in long_poll.listen(): user = User.query.get(event.message.from_id) message = None keyboard = None if user is None: message = \ f"Ваш профиль не зарегестрирован на сайте.\n" \ f"Перейдите по ссылке чтобы зарегестрироваться: " \ f"{url_for('auth.login')}" elif not user.notify: user.notify = True db.session.add(user) message = \ "Уведомления включены.\n" \ "Для отключения уведомлений напишите \"Отключить\"" elif 'отключить' in event.message.text.lower(): user.notify = False db.session.add(user) message = \ "Уведомления отключены.\n" \ "Для включения уведомлений напишите любое сообщение." db.session.commit() if message is not None: bot.send_message(peer_id=event.message.peer_id, message=message, keyboard=keyboard)
def handle_stream_close_chat(json): sql.Customer.update({sql.Customer.link: "!"}).where(sql.Customer.chat_id == json['chat_id']).execute() bot.send_message(json['chat_id'], 'Вы завершили диалог с оператором') emit('stream_close_chat', { "chat_id": json['chat_id'], })
def favourite_list(message): try: user = User.query.filter_by(username=message.chat.username).first() bot.send_message(message.chat.id, user.favourite_list()) except Exception as e: if bot.debug(): bot.msg_error(message.chat.id, e, message.text)
def linkSupport(chat_id, manager): sql.Customer.update({sql.Customer.link: manager}).where(sql.Customer.chat_id== chat_id).execute() bot.send_message(chat_id, 'Оператор на связи! Вы можете начать диалог с ним прямо сейчас') return { "chat_id": chat_id, "manager": manager }
def student_name_step(message): try: chat_id = message.chat.id name = message.text try: check_name = Student.query.filter( Student.id == str(chat_id)).first().name bot.send_message(chat_id, text='Вы уже зарегистрировались как студент ' + str(check_name)) except AttributeError: student = Student(id=chat_id, name=name) db.session.add(student) db.session.commit() keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=False) agree = types.KeyboardButton( text='Да, я хочу передать свой телефон', request_contact=True) decline = types.KeyboardButton( text='Нет, я не хочу передавать свой телефон') keyboard.add(agree) keyboard.add(decline) bot.send_message(chat_id, text='Хотите передать свой номер телефона?', reply_markup=keyboard) except Exception as e: bot.reply_to(message, 'Произошла какая-то ошибка, я вас не понял ' + str(e))
def send_post(post: Post): query = db.session.query(Subscription).distinct(Subscription.chat_id) if post.city_id is not None: query = query.filter(Subscription.city_id == post.city_id) if post.position_id is not None: query = query.filter(Subscription.position_id == post.position_id) items = query.all() for subscription in items: if post.image_id: bot.send_photo( chat_id=subscription.chat_id, photo=post.image_id, caption=post.text, parse_mode="Markdown", disable_web_page_preview=False, ) else: bot.send_message( chat_id=subscription.chat_id, text=post.text, parse_mode='Markdown', disable_web_page_preview=False, ) post.date_sent = utc_now() db.session.commit() return items
def process_answer_step(message, questid): try: # user = User.query.filter_by(username=message.chat.first_name).first() user = checkUser(message.chat.first_name) question = Question.query.filter_by(id=questid).first() user.total_question += 1 if question.check(message.text): user.good_question += 1 db.session.commit() markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) markup.add('/next', 'cancel') bot.send_message(message.chat.id, 'Правильно, всего:{}, верно:{}, не верно:{}' \ .format(user.total_question, user.good_question, user.fail_question), reply_markup=markup) else: raise Exception() except Exception as e: user.fail_question += 1 db.session.commit() markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) markup.add('/next', 'cancel') bot.send_message(message.chat.id, 'Ooops , верный ответ : {}, всего:{}, верно:{}, не верно:{}' \ .format(question.question_answer, user.total_question, user.good_question, user.fail_question), reply_markup=markup)
def teacher_table_name_step(message, link, reg): try: chat_id = message.chat.id name = message.text if not reg: table = Tables(url=link, user_id=chat_id, list_name=name) db.session.add(table) db.session.commit() keyboard = types.InlineKeyboardMarkup() add_table = types.InlineKeyboardButton(text="Добавить таблицу", callback_data="link") delete_table = types.InlineKeyboardButton(text="Удалить таблицу", callback_data="delete1") start_test = types.InlineKeyboardButton(text="Начать тест", callback_data="start test") keyboard.add(add_table) keyboard.add(delete_table) keyboard.add(start_test) bot.send_message(chat_id, text='Принято, вот доступные действия:', reply_markup=keyboard) except Exception as e: bot.reply_to(message, 'Произошла какая-то ошибка, я вас не понял ' + str(e))
def user_info(user: models.User, tg_id: int): try: target_user = db_tools.get_user(tg_id) except: return if not target_user: return if target_user.queue_message: place_queue = db_tools.session.query(models.QueueMessage).filter_by( user=target_user, ).first() message = place_queue.message referal_need = place_queue.referal_need else: message, referal_need = 'No', 'No' text = ''' Игрок - {tg_id} Сейчас на - {point} Привёл - {referal_quantity} В очереди - {message} referal_need - {referal_need} '''.format( tg_id=target_user.telegram_id, point=target_user.point, referal_quantity=target_user.referal_quantity, message=message, referal_need=referal_need, ) bot.send_message(user.telegram_id, text)
def get_bot_info(message): # Персона рандомная, или созданная преждевременно? # Если рандомная, возможно в ней хранить chat_id??? persona = Persona.query \ .get(users_services.get_user(message.chat.id).persona_id) print('passport') # a = random.randint(1, 10) * 20 # # bot.send_message(message.chat.id, 'Сила:') # bot.send_message(message.chat.id, a) # # b = random.randint(10, 120) # bot.send_message(message.chat.id, 'Интеллект:') # bot.send_message(message.chat.id, b) # # c = random.randint(1, 10) # bot.send_message(message.chat.id, 'Ловкость:') # bot.send_message(message.chat.id, c) bot.send_message(message.chat.id, f""" * Вес:* {persona.strength} * IQ:* {persona.intelligence} * Бег:* {persona.agility} """, parse_mode='MarkdownV2')
def command_start(message, data): """Handle '/start'""" response = get_start(data['username'], data['lang']) bot.send_message(data['chat_id'], text=response, reply_markup=call_main_keyboard(data['lang']), parse_mode='html')
def button_phenomena(message, data): """Handle button 'phenomena'""" response = hints['phenomena intro'][data['lang']] bot.send_message(data['chat_id'], text=response, reply_markup=gen_markup_phenomena(data['user'].id, data['lang']))
def unticket(chat_id): sql.Customer.update({ sql.Customer.want_help: "no" }).where(sql.Customer.chat_id == chat_id).execute() bot.send_message(chat_id, 'Вы завершили диалог с оператором') return {"chat_id": chat_id}
def add_visit(message): keyboard = telebot.types.InlineKeyboardMarkup() key_yes = telebot.types.InlineKeyboardButton(text="Yes", callback_data="yes, increase") keyboard.add(key_yes) key_no = telebot.types.InlineKeyboardButton(text="No", callback_data="no, don't touch") keyboard.add(key_no) bot.send_message(message.chat.id, "Would you like to score a physical education visit?", reply_markup=keyboard)
def start_command_handler(message): # TODO: implement start logic if message.chat.type == 'group' and bot_utils.is_command_for_bot(cmd_str='start', message_text=message.text): admins = bot.get_chat_administrators(message.chat.id) if any(chat_member.user.id == message.from_user.id for chat_member in admins): bot.send_message(message.chat.id, config.group_start_command_message) else: bot.send_message(message.chat.id, config.user_is_not_admin)
def on_created(self, event): if not event.is_directory: created_file_name = os.path.splitext( os.path.basename(event.src_path))[0] logger.info(f'page {created_file_name} was created') dw_page_url = settings.dokuwiki_url + created_file_name send_message('Создана новая страница Dokuwiki', f'Просмотреть: {dw_page_url}')
def on_modified(self, event): if not event.is_directory: modified_file_name = os.path.splitext( os.path.basename(event.src_path))[0] logger.info(f'page {modified_file_name} was modified') dw_page_url = settings.dokuwiki_url + modified_file_name send_message('Изменена страница Dokuwiki', f'Просмотреть: {dw_page_url}')
def show_unmuted_services(message): data = '' all_services = show_unmuted() if all_services: data = 'Включенные сервисы:\n' + all_services else: data = 'Сервисы отсутствуют' bot.send_message(message.chat.id, data, parse_mode='Markdown')
def handle_genre(message): genre = message.text.lower() if genre not in config['genre_codes']: bot.send_message(message.chat.id, 'Такой жанр не найден') else: code = config['genre_codes'][genre] films_list = parser.get_film_list_by_genre(code) obtain_films_list(message, films_list)
def select_division(message): from app import bot answer = "" sql_con = sqlite3.connect("Bot.db") cursor = sql_con.cursor() cursor.execute( """SELECT divisions_json FROM user_choice WHERE user_id = ?""", (message.chat.id, )) data = cursor.fetchone() cursor.close() sql_con.close() divisions = json.loads(data[0]) division_names = [division["Name"].strip() for division in divisions ] # собираем названия направлений aliases = [division["Alias"].strip() for division in divisions ] # Собираем аббревиатуры каждого направления if message.text in division_names: # Если пользователь выбрал направление, то дальше создаем клавиатуру с выбором ступени обучения: answer += "Выбери ступень:" study_programs_keyboard = telebot.types.ReplyKeyboardMarkup( resize_keyboard=True, one_time_keyboard=False) index = division_names.index(message.text) alias = aliases[index] study_programs = spbu.get_program_levels(alias) # Заполняем клавиатуру значениями: for study_program in study_programs: study_programs_keyboard.row(study_program["StudyLevelName"]) study_programs_keyboard.row("Другое направление") data = json.dumps(study_programs) sql_con = sqlite3.connect("Bot.db") cursor = sql_con.cursor() # заливаем в бд все выборы, которые сделал пользователь: cursor.execute( """UPDATE user_choice SET alias = ?, division_name = ?, study_programs_json = ? WHERE user_id = ?""", (alias, message.text, data, message.chat.id)) sql_con.commit() cursor.close() sql_con.close() # отправляем сообщение пользователю обратно с новой клавиатурой bot.send_message(message.chat.id, answer, reply_markup=study_programs_keyboard) set_next_step( message.chat.id, "select_study_level") # переводим пользователя на следующий этап else: answer += "Пожалуйста, укажи направление:" bot.send_message(message.chat.id, answer) set_next_step(message.chat.id, "select_division")