def got_payment(message): my_bot.reply_to(message, 'Ура! Оплата на `{} {}` прошла успешно!\n\n' 'Вы получаете статус Premium пользователя бота 😎' ''.format(message.successful_payment.total_amount / 100, message.successful_payment.currency), parse_mode='Markdown')
def users_stats(message): with open(config.FileLocation.bot_logs, 'r', encoding='utf-8') as file: file_text = file.read() users_commands = re.findall('(?:User )(\d+)(?:.*called)', file_text) users_callbacks = re.findall('(?:User )(\d+)(?:.*callbacked)', file_text) user_commands_counter = Counter(users_commands) users_callbacks_counter = Counter(users_callbacks) table, tables = [], [] for user_id, user in my_data.data.items(): table.append([ user['who'], user_commands_counter[user_id], users_callbacks_counter[user_id] ]) if len(table) % 75 == 0: tables.append(table) table.clear() if len(table) != 0: tables.append(table) for table in tables: text = tabulate(table, headers=('Пользователь', 'Команд', 'Кнопок'), tablefmt='simple') my_bot.reply_to(message, '<pre>{}</pre>'.format(text), parse_mode='HTML')
def update_bot(message): if not hasattr(update_bot, 'check_sure'): update_bot.check_sure = True return my_bot.reply_to(message, 'Ух, ухожу на обновление...') user_action_log(message, 'remotely ran update script.') os.execl('/bin/bash', 'bash', 'utils/__bot_update.sh')
def reply_time(self, message): split = re.findall('/(\w*)(?:@\w*)?\s*([\d/]*)', message.text)[0] cmd = split[0] try: day = datetime.today() if split[1] == '' else datetime.strptime(split[1], '%d/%m/%y') except ValueError: day = datetime.today() text, keyboard = self.reply_time_data(message.from_user.id, cmd, day) my_bot.reply_to(message, text, reply_markup=keyboard, parse_mode='HTML')
def camera_n_show(message): split = message.text.split() if len(split) == 2 and split[1].isdigit() and border(int(split[1])) == int( split[1]): camera_show(message, int(split[1])) else: ans = ('Использование: {}, N={}..{}').format(code('/camera [N]'), CameraView.MIN_CAM_NUM, CameraView.MAX_CAM_NUM) my_bot.reply_to(message, ans)
def user_state(self, message): today = datetime.today() payload = (('AcsTabelIntermediadateSearch[staff_id]', my_data.get_user_name(message.from_user.id)), ('AcsTabelIntermediadateSearch[date_pass_first]', self.time_format(today)), ('AcsTabelIntermediadateSearch[date_pass_last]', self.time_format(today))) response = requests.get(self.acs_url, auth=(tokens.auth_login, tokens.auth_pswd), params=payload) answer = self.state_format(response.text) if response.ok else self.asc_unaccessible_error my_bot.reply_to(message, answer, parse_mode='HTML')
def on_vacation_now(message): vacations = _on_vacation_get(datetime.date(datetime.today())) if vacations: text = '🌴 {}:\n'.format(bold('Сейчас в отпуске')) for item in vacations: text += '{} — до {}\n'.format(code(item[0]), item[1].strftime('%d.%m')) else: text = '💻️ Сейчас нет сотрудников в отпуске!\n' my_bot.reply_to(message, text, parse_mode='HTML')
def command_notify_all(message): user_action_log(message, 'called ' + message.text) split = message.text.split(' ', 1) if len(split) > 1: subs_notify(my_data.list_users(), '{}\n\n{}'.format(bold('Оповещение пользователей бота'), split[1]), me=message.from_user.id) else: my_bot.reply_to(message, 'Использование: /notify_all [ваше сообщение]')
def command_day(message): user_action_log(message, 'called ' + message.text) split = message.text.split(' ', 1) if len(split) > 1: subs_notify( config.admin_ids, 'Обратная связь от {}: {}' ''.format( link(my_data.data[str(message.from_user.id)]['who'], message.from_user.id), split[1])) my_bot.reply_to(message, 'Сообщение отправлено!') else: my_bot.reply_to(message, 'Использование: /feedback [ваше обращение]')
def register_user_finish(self, message): self.data[str(message.from_user.id)]['settings'] = UserSettings() self.save() my_bot.reply_to(message, '✅ Данные сохранены', parse_mode='HTML', disable_web_page_preview=True) with open(config.FileLocation.cmd_help, 'r', encoding='utf-8') as file: my_bot.send_message(message.from_user.id, file.read(), parse_mode='HTML', disable_web_page_preview=True) quit(0)
def birthdays_show(message): drs = birthdays_get() if len(drs) == 0: my_bot.reply_to(message, my_acs.asc_unaccessible_error, parse_mode='HTML') return text = 'Ближайшие дни рождения {}:\n\n'.format(random.choice(happy_emoji)) for date, name in drs: text += '{} — {}\n'.format(date, code(name)) my_bot.reply_to(message, text, parse_mode='HTML')
def stats(message): users_count = len(my_data.list_users()) alerts_count = 0 for user in my_data.data.values(): alerts_count += len(user.get('alert_users', [])) with open(config.FileLocation.bot_logs, 'r', encoding='utf-8') as file: file_text = file.read() user_commands = re.findall('(?:User )(\d+)(?:.*called)', file_text) user_callbacks = re.findall('(?:User )(\d+)(?:.*callbacked)', file_text) commands = re.findall('(?:User.*called )(/\w*)(?:\s)', file_text) user_commands_counter = Counter(user_commands) user_callbacks_counter = Counter(user_callbacks) user_id = str(message.from_user.id) user_commands_count = user_commands_counter[user_id] user_callbacks_count = user_callbacks_counter[user_id] user_pos = user_commands_counter.most_common().index( (user_id, user_commands_count)) + 1 all_commands_count = sum(user_commands_counter.values()) all_callbacks_count = sum(user_callbacks_counter.values()) days_from_birthday = (datetime.today() - datetime(year=2018, month=2, day=9)).days text = f'Бот родился 9 февраля 2018 и сегодня его {bold(days_from_birthday)} день!\n' \ f'Пользователей бота: {bold(users_count)}\n' \ f'Команд вызвано: {bold(all_commands_count)}\n' \ f'Суммарно отслеживаемых сотрудников: {bold(alerts_count)}\n\n' text += 'Вы использовали {} команд и находитесь на {} месте, вызвав {}% команд\n\n' \ ''.format(bold(user_commands_count), bold(user_pos), bold(round(100 * user_commands_count / all_commands_count, 2))) text += 'Вами нажато кнопок: {}, всеми: {}\n\n'.format( bold(user_callbacks_count), bold(all_callbacks_count)) top_count = 5 commands_counter = Counter(commands) commands_most = commands_counter.most_common(top_count) text += f'Топ {top_count} команд по вызовам:\n' for i in range(top_count): text += f' {i+1}. {commands_most[i][0]} — {bold(commands_most[i][1])}\n' my_bot.reply_to(message, text, parse_mode='HTML')
def command_help(message): user_action_log(message, 'called ' + message.text) with open(config.FileLocation.cmd_help, 'r', encoding='utf-8') as file: my_bot.reply_to(message, file.read(), parse_mode='HTML', disable_web_page_preview=True) if message.from_user.id in config.admin_ids: with open(config.FileLocation.cmd_help_admin, 'r', encoding='utf-8') as file: my_bot.reply_to(message, file.read(), parse_mode='HTML', disable_web_page_preview=True)
def commands(message): with open(config.FileLocation.bot_logs, 'r', encoding='utf-8') as file: file_text = file.read() commands = re.findall('(?:User.*called )(/\w*)(?:\s)', file_text) commands_counter = Counter(commands) commands_most = commands_counter.most_common() text = 'Список команд бота:\n\n' count = 1 for cmd in commands_most: text += '{}. {} — {}\n'.format(count, *cmd) count += 1 my_bot.reply_to(message, '{}'.format(text), parse_mode='HTML')
def list_alert_name(self, message): users = self.data[str(message.from_user.id)].get('alert_users') if users is not None and len(users) > 0: my_bot.reply_to( message, '📣️ Ваш список оповещений:\n— <code>{}</code>\n\n' 'Используйте /alert_add и /alert_erase для управления списком, ' 'и /settings для настройки оповещений.' ''.format('</code>\n— <code>'.join(users)), parse_mode='HTML') else: my_bot.reply_to( message, '📣️ Ваш список оповещений пуст.\n\n' 'Используйте /alert_add и /alert_erase для управления списком, ' 'и /settings для настройки оповещений.')
def check_password(self, message): if tokens.access_pswd != '' and message.text == tokens.access_pswd: if self.data.get(str(message.from_user.id)) is None: self.data[str(message.from_user.id)] = {} self.data[str(message.from_user.id)]['authenticated'] = 'True' user_action_log(message, 'successfully registered') my_bot.reply_to(message, '✅ Пароль верный!') subs_notify( config.admin_ids, '✨ Новый пользователь: {}'.format( link_user(message.from_user))) self.data[str(message.from_user.id)]['who'] = user_name( message.from_user) self.register_user(message) else: user_action_log(message, 'entered wrong password') my_bot.reply_to( message, '⛔ Пароль не подошел!\n\nВызывай /start для новой попытки.')
def command_start(message): user_action_log(message, 'called ' + message.text) split = message.text.split() if len(split) == 1: if not my_data.is_registered(message): user_action_log(message, 'not registered to call: ' + message.text) my_data.register_user(message) return with open(config.FileLocation.cmd_start, 'r', encoding='utf-8') as file: my_bot.reply_to(message, file.read(), parse_mode='HTML', disable_web_page_preview=True) else: deep_link = split[1] if deep_link.startswith('donate'): donate.donate(message)
def erase_alert_name(self, message): split = message.text.split(' ', 1) if len(split) > 1: if self.data[str( message.from_user.id)].get('alert_users') is not None: if self.data[str(message.from_user.id)]['alert_users'].count( split[1]) != 0: self.data[str(message.from_user.id)]['alert_users'].remove( split[1]) self.save() my_bot.reply_to( message, '📣️ Оповещения о {} выключены!'.format(split[1])) return my_bot.reply_to( message, 'Использование: /alert_erase [ФИО в соответствии записи в {}]\n' 'Ваш список оповещений: /alert'.format(self.asc_link), parse_mode='HTML')
def command_reply(message): user_action_log(message, 'called ' + message.text) if hasattr(message, 'reply_to_message'): split = message.text.split(' ', 1) if len(split) > 1: replying_msg = message.reply_to_message if hasattr(replying_msg, 'entities'): user_ids = [ x.user.id for x in replying_msg.entities if x.type == 'text_mention' ] if len(user_ids) == 1: my_bot.send_message(user_ids[0], '{}: {}'.format( bold('Разработчик'), split[1]), parse_mode='HTML') my_bot.reply_to(message, 'Сообщение отправлено!') return my_bot.reply_to(message, 'Использовать с ответом на фидбек: /reply [ваш ответ]')
def donate(message): if tokens.provider_token == '': my_bot.reply_to(message, 'Не подключен токен оплаты!') return my_bot.send_invoice(message.chat.id, title='Поддержка разработки бота', description='Хочется есть, помогите 😞', provider_token=tokens.provider_token, currency='RUB', prices=[LabeledPrice(label='На сникерс', amount=5000)], start_parameter='donate-50', invoice_payload='donate-50') my_bot.send_invoice(message.chat.id, title='Поддержка разработки бота | Plus', description='Очень хочется есть, помогите 😩', provider_token=tokens.provider_token, currency='RUB', prices=[LabeledPrice(label='На обед', amount=25000)], start_parameter='donate-250', invoice_payload='donate-250')
def in_office_now(self, message): text = self.in_office_now_text(message.from_user.id) my_bot.reply_to(message, text, reply_markup=self.keyboard, parse_mode='HTML')
def users(message): text = 'Список пользователей бота:\n\n' for count, (user_id, user) in enumerate(my_data.data.items(), start=1): text += '{}. {}\n'.format(count, link(user['who'], user_id)) my_bot.reply_to(message, text, parse_mode='HTML')
def show_settings_message(self, message): my_bot.reply_to( message, '⚙️ Ваши настройки\n\nПримечание: при нажатии на кнопки слева ' 'появляется описание настройки', reply_markup=self.generate_settings_buttons())
def camera_n_show(message): split = message.text.split() if len(split) == 2 and split[1].isdigit(): camera_show(message, int(split[1])) else: my_bot.reply_to(message, ('Использование: {}, N=4..12').format(code('/camera [N]')))
def command_log(message): user_action_log(message, 'called ' + message.text) with open(config.FileLocation.bot_logs, 'r', encoding='utf-8') as file: lines = file.readlines()[-100:] for text in cut_long_text(''.join(lines)): my_bot.reply_to(message, '{}'.format(text))