def add_to_db(self): """ add user in db """ self._add_new_user() bot.send_message(self.tg_id, lang[self.lang]['city_save'])
def process_phone_step(message): try: chat_id = message.chat.id user = user_dict[chat_id] if message.contact: number = message.contact.phone_number else: number = message.text if not (carrier._is_mobile(number_type(parse(number)))): raise Exception if conn.exist_phone(user.phone_number): raise PhoneExists # Get last 10 characters user.phone_number = f'8{number[-10:]}' markup = types.ReplyKeyboardRemove(selective=False) msg = bot.send_message(chat_id, config.l10n[user.language]['name'], reply_markup=markup) bot.register_next_step_handler(msg, process_name_step) except PhoneExists: msg = bot.send_message(message.chat.id, config.l10n[user.language]['number_exists'], reply_markup=utils.gen_reply_markup([], 1, False, False)) bot.register_next_step_handler(msg, process_phone_step) except Exception: buttons = (config.l10n[user.language]['send_contact'], ) msg = bot.send_message(message.chat.id, config.l10n[user.language]['number_invalid'], reply_markup=utils.gen_reply_markup( buttons, 1, False, True)) bot.register_next_step_handler(msg, process_phone_step)
def add_start_handler(message): bot.send_message(message.chat.id, 'Добавьте новое место') update_state(message) execute( 'insert into place(chat_id, address, location) values ({}, null, null);' .format(message.chat.id)) global _last_index _last_index = execute('select max(id) from place')[0]
def add_confirmation_handler(message): if 'нет' in message.text: execute('delete from place where chat_id = {} and id = {}'.format( message.chat.id, _last_index)) bot.send_message(message.chat.id, 'Отменено') else: bot.send_message(message.chat.id, 'Успешно сохранено') update_state(message)
def update_city(self, value): """ update in db column city for user """ if WeatherBit.check_city(value, weather): self._update_user_data(self.tg_id, 'city', value) return True else: bot.send_message(self.tg_id, lang[self.lang]['city_not_found']) return False
def update_subscribe(self): """ update in db column subscribe for user """ if self.subscribe == 0: self._update_user_data(self.tg_id, 'subscribe', 1) else: self._update_user_data(self.tg_id, 'subscribe', 0) bot.send_message(self.tg_id, lang[self.lang]['status_upd']) self.create_user_menu()
def send_welcome(message): try: chat_id = message.chat.id if (message.chat.type == "private"): bot.send_message( chat_id, 'Здравствуйте, это телеграм бот потребительского кооператива "Елимай-2019". Выберите язык на котором хотите продолжить переписку', reply_markup=utils.gen_inline_markup(config.languages, 2)) else: bot.send_message(chat_id, "Бот работает в личном чате") except Exception: bot.reply_to(message, 'oooops')
def update_lang(self, message): """ update in db column lang for user """ if 'English' in message.text: self.lang = 'en' self._update_user_data(self.tg_id, 'lang', 'ru') bot.send_message(self.tg_id, lang[self.lang]['success']) elif 'Русский' in message.text: self.lang = 'ru' self._update_user_data(self.tg_id, 'lang', 'en') bot.send_message(self.tg_id, lang[self.lang]['success']) self.create_user_menu()
def process_name_step(message): try: chat_id = message.chat.id name = message.text user = user_dict[chat_id] user.name = name lang = 2 if user.language == "kz" else 3 city_name = conn.select_city(user.city)[0][lang] bot.send_message( chat_id, f'{config.l10n[user.language]["name_single"]}: {user.name}\n' f'{config.l10n[user.language]["number_single"]}: {user.phone_number}\n' f'{config.l10n[user.language]["city_single"]}: {city_name}') save_data(message) except Exception: bot.reply_to(message, 'oooops')
def _send_file(self, file_descriptor, ext, caption): if ext in ('.jpg', '.png'): return bot.send_photo( chat_id=self.rule.chat_id, photo=file_descriptor, caption=caption, ) elif ext == '.txt': return bot.send_message( chat_id=self.rule.chat_id, text=file_descriptor.read().decode(), ) elif ext == '.md': return bot.send_message( chat_id=self.rule.chat_id, text=file_descriptor.read().decode(), parse_mode='Markdown', ) elif ext == '.html': return bot.send_message( chat_id=self.rule.chat_id, text=file_descriptor.read().decode(), parse_mode='HTML', ) elif ext == '.mp3': return bot.send_message( chat_id=self.rule.chat_id, audio=file_descriptor, caption=caption, ) elif ext == '.ogg': return bot.send_voice( chat_id=self.rule.chat_id, voice=file_descriptor, caption=caption, ) else: return bot.send_document( chat_id=self.rule.chat_id, data=file_descriptor, caption=caption, )
def create_user_menu(self): """ Create inline keyboard """ markup = types.ReplyKeyboardMarkup(resize_keyboard=1) if self.lang == 'ru': markup.row('Прогноз на сегодня', 'Прогноз на завтра') markup.row( 'Прогноз на неделю', 'Изменить язык', ) markup.row('Сменить город', f'Подписка на рассылку{self._check_sub()}') bot.send_message(self.tg_id, 'Выберите действие:', reply_markup=markup) else: markup.row('Forecast today', 'Forecast tomorrow') markup.row('Weekly forecast', 'Change language') markup.row('Change city', f'Subscribe to sending{self._check_sub()}') bot.send_message(self.tg_id, 'Choose action:', reply_markup=markup)
def save_data(message): try: chat_id = message.chat.id user = user_dict[chat_id] id = None if conn.exist_user(user.telegram_id) and not conn.select_user( user.telegram_id)[7]: tpl = [ user.name, user.city, user.phone_number, user.language, user.decision, user.telegram_id ] id = conn.update_user(tpl) else: tpl = (user.name, user.city, user.phone_number, user.language, user.telegram_id, user.username, user.decision) if not conn.exist_user(user.telegram_id): id = conn.add_user(tpl) city = conn.select_city(user.city)[0][3] now = datetime.now().strftime("%d/%m/%Y %H:%M:%S") user_tpl = (id, user.name, city, user.phone_number, user.language, user.telegram_id, user.username, now) worksheet.append_row(user_tpl) if id is not None: lang = 3 username = '' if user.username == None else f'@{user.username}' bot.send_message(os.getenv("GROUP_CHAT_ID"), f'ID: {id}\n' f'Имя: {user.name}\n' f'Имя пользователя: {username}\n' f'Город: {conn.select_city(user.city)[0][lang]}\n' f'Номер: {user.phone_number}\n' f'Язык: {user.language}', disable_notification=True) bot.send_message( chat_id, config.l10n[user.language]['success_registration']) del user except Exception: bot.reply_to(message, 'oooops')
def request_list_handler(message): last_10 = execute('select * from place order by id desc limit 10;') if type(last_10) is list and last_10 is not None: for place in last_10: bot.send_message(message.chat.id, place[2] + ' по адресу ' + place[3]) elif last_10 is not None: bot.send_message(message.chat.id, last_10[2] + ' по адресу ' + last_10[3]) else: bot.send_message(message.chat.id, 'У вас нет сохраненных данных')
def pereodic_send_links(): while True: try: chatlinks = ChatLink.select().dicts() for chat in chatlinks: chat_id = chat['chat_id'] link = chat['link'] card_urls = parse(link) new_urls = [u for u in card_urls if CACHE.get(format_key_for_cache(chat_id, u)) is None] if new_urls: bot.send_message(chat_id, '-' * 5) for url in new_urls: CACHE[format_key_for_cache(chat_id, url)] = url bot.send_message(chat_id, url) if new_urls: bot.send_message(chat_id, '-' * 5) except Exception as e: # никогда не прекращаем работу print(e) time.sleep(random.randrange(60 * 5, 60 * 15))
def clear_db(message): clear_storage() markup = types.ReplyKeyboardRemove(selective=False) bot.send_message(message.chat.id, "База данных была сброшена", reply_markup=markup)
def main_scenario(message): user_document = get_user_info(message.from_user.id) set_scenario(user_document, "on_main_menu_scenario") markup = get_main_menu_markup() bot.send_message(message.chat.id, text="Главное меню", reply_markup=markup)
def show_all_users(message): usernames = [element["userinfo"]["username"] for element in get_users()] bot.send_message(message.chat.id, ", ".join(usernames))
def send_welcome(message): bot.send_message(message.chat.id, text("start_message")) state_manager(message)
def start_handler(message): help_str = '/add - добавление места, если ввели неправильно, в конце введите \'нет\'\n' \ '/list - вывод последних 10 мест\n' \ '/reset - удалить все ваши места\n' bot.send_message(message.chat.id, help_str)
def add_location_handler(message): execute( 'update place set location = \'{}\' where chat_id = {} and id = {};'. format(message.text, message.chat.id, _last_index)) update_state(message) bot.send_message(message.chat.id, 'Подтвердите сохранение')
def add_place_handler(message): execute( 'update place set address = \'{}\' where chat_id = {} and id = {};'. format(message.text, message.chat.id, _last_index)) bot.send_message(message.chat.id, 'Добавьте адрес') update_state(message)
def send_contacts(message): try: chat_id = message.chat.id bot.send_message(chat_id, 'Наш сайт https://elimai2019.kz/') except Exception: bot.reply_to(message, 'oooops')
def callback_query(call): chat_id = call.message.chat.id if call.data in ("cb_ru", "cb_kz"): language = 'kz' if call.data == 'cb_kz' else 'ru' user = User(language) user_dict[chat_id] = user bot.answer_callback_query(call.id, config.l10n[user.language]['language']) # video = open( # '/home/sam/Documents/Projects/elimaiga/promo_kz.mp4', 'rb') # bot.send_video(chat_id, video) video = 'VIDEO_ID_KZ' if language == 'kz' else 'VIDEO_ID_RU' bot.send_video(chat_id, os.getenv(video), caption=config.l10n[user.language]['video']) user.username = call.message.chat.username user.telegram_id = str(call.message.chat.id) if not DEV_MODE: time.sleep(7) choices = { 'cb_yes': config.l10n[user.language]['yes'], 'cb_no': config.l10n[user.language]['no'], } bot.send_message(chat_id, config.l10n[user.language]['offer'], reply_markup=utils.gen_inline_markup(choices, 2)) elif call.data in ("cb_no", "cb_yes"): if call.data == "cb_no": try: user = user_dict[chat_id] bot.edit_message_text(config.l10n[user.language]['deny'], chat_id, call.message.message_id) bot.answer_callback_query(call.id, config.l10n[user.language]['no']) if not conn.exist_user(str(chat_id)): tpl = (user.name, user.city, user.phone_number, user.language, user.telegram_id, user.username, user.decision) res = conn.add_user(tpl) except Exception: bot.reply_to(call.message, 'oooops') else: try: user = user_dict[chat_id] user.decision = True bot.answer_callback_query(call.id, config.l10n[user.language]['yes']) lang = 2 if user.language == "kz" else 3 if conn.exist_user(user.telegram_id) and conn.select_user( user.telegram_id)[7]: res = conn.select_user(user.telegram_id) bot.send_message( chat_id, config.l10n[user.language]['already_registered']) else: res = conn.select_cities() cities = [] for i in range(len(res)): cities.append(res[i][lang]) callbacks = [] for i in range(len(res)): callbacks.append('cb_city_' + str(res[i][0])) cities = dict(zip(callbacks, cities)) msg = bot.send_message( chat_id, f"{user.name}, {config.l10n[user.language]['city']}", reply_markup=utils.gen_inline_markup(cities, 1)) except Exception: bot.reply_to(call.message, 'oooops') else: city = int(call.data.split('_')[-1]) user = user_dict[chat_id] user.city = city buttons = (config.l10n[user.language]['send_contact'], ) msg = bot.send_message(chat_id, config.l10n[user.language]['number'], reply_markup=utils.gen_reply_markup( buttons, 1, False, True)) bot.register_next_step_handler(msg, process_phone_step)
def reset_handler(message): execute('delete from place where chat_id = {};'.format(message.chat.id)) bot.send_message(message.chat.id, 'Ваши записи успешно удалены')