class STRS: name = "Telemonitor" description = "Telegram bot for monitoring your system." reboot = "Rebooting the system" shutdown = "Shutting down the system" message_startup = code("System was booted") message_shutdown = code("System is shutting down")
async def process_callback_button1(callback_query: types.CallbackQuery): ''' ask of gas ''' await bot.answer_callback_query(callback_query.id) if callback_query.from_user.id in ids: await Form.gas_num.set() await bot.send_message(callback_query.from_user.id, 'Getting started.\nSend me the numbers on the gas meter to ' 'the point.') else: # if user not in right ids, send messege to admin await bot.send_message(callback_query.from_user.id, md.text( f'Привет {callback_query.from_user.first_name}.\nI do not know if you live in the owner is apartment, but ' f'I will send your data to him. If anything, he will write to you. {emojize(":stuck_out_tongue_closed_eyes:")} ' )) await bot.send_message(chat_id=admin, text=md.text(md.text(f'Someone unknown tried to testify'), md.text(f'Name:', md.code(callback_query.from_user.full_name)), md.text(f'Username:'******'ID:', md.code(callback_query.from_user.id)), md.text(f'language:', md.code( callback_query.from_user.language_code)), sep='\n', ), parse_mode=ParseMode.MARKDOWN)
async def cmd_start(message: types.Message): # Create a temporary session session = bot.create_temp_session() content = [] # Make request (without proxy) async with session.get(GET_IP_URL) as response: content.append( text(':globe_showing_Americas:', bold('IP:'), code(await response.text()))) # This line is formatted to '🌎 *IP:* `YOUR IP`' # Make request through proxy async with session.get(GET_IP_URL, proxy=bot.proxy, proxy_auth=bot.proxy_auth) as response: content.append( text(':locked_with_key:', bold('IP:'), code(await response.text()), italic('via proxy'))) # This line is formatted to '🔐 *IP:* `YOUR IP` _via proxy_' # Send content await bot.send_message(message.chat.id, emojize(text(*content, sep='\n')), parse_mode=ParseMode.MARKDOWN) # Destroy temp session bot.destroy_temp_session(session)
async def _get_seats_number(message: types.Message, state: FSMContext): logger.info('User %s has set seats: %s', message.from_user.username, message.text) async with state.proxy() as data: seats = message.text.split(',') data['seats'] = seats logger.info('Current state: %s', data) markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True) markup.add("OK", "CANCEL") await TicketOrderState.next() msg = md.text(md.text('Всё правильно?'), md.text(md.italic('Станция отправления: '), md.code(data['from_station'])), md.text(md.italic('Станция прибытия: '), md.code(data['to_station'])), md.text(md.italic('Дата отправления: '), md.code(data['date'])), md.text(md.italic('Номер вагона: '), md.code(data['wagon_number'])), md.text(md.italic('Бронируемые места: '), md.code(','.join(data['seats']))), sep='\n') await message.reply(msg, reply_markup=markup, parse_mode=types.ParseMode.MARKDOWN)
async def systemAnswer(message: Message, text: str = "Ошибка", markup=None): """Возвращающая текст, форматированный как СИСТЕМНОЕ СООБЩЕНИЕ (кастомный тип форматирования в этом проекте)""" if markup: await message.answer(markdown.code(text), reply_markup=markup, parse_mode='MarkdownV2') else: await message.answer(markdown.code(text), parse_mode='MarkdownV2')
async def errors(*args, **partial_data): if "This Session's transaction has been rolled back due to a previous exception during flush" in args: with Session as session: session.rollback() msg = markdown.text(markdown.bold("⚠️ An error occurred:"), markdown.code(args), markdown.code(partial_data), sep="\n") await bot.send_message(ADMIN_ID, msg, parse_mode=ParseMode.MARKDOWN)
async def start(message, state): async def send_message(msg, **kwargs): await bot.bot.send_message(message.chat.id, msg, **kwargs) async with state.proxy() as data: try: rzd_args = { 'bEntire': 'false', 'code0': data['departure'], 'code1': data['destination'], 'dir': '0', 'dt0': data['date'], 'tnum0': data['train'], } params = data['count'] car_type = data['car_type'] except Exception: traceback.print_exc() return prefix = f'@{message.from_user.username} {message.from_user.id} ' mon = monitor.AsyncMonitor( args=rzd_args, cars_type=car_type, delay_base=10, callback=send_message, prefix=prefix, **params, ) bot.messengers[state.user] = mon msg = md.text( md.code(f'{helpers.dump_to_json(rzd_args)}'), md.code(f'{helpers.dump_to_json(params)}'), md.text(f'Count: {params["requested_count"]}, car type: {car_type}'), sep='\n', ) logging.info(f'{prefix}{msg}') await send_message(msg, parse_mode=ParseMode.MARKDOWN) try: await mon.run() await send_message( messages.MONITOR_IS_SHUT_DOWN, parse_mode=ParseMode.MARKDOWN, ) except monitor.RZDNegativeResponse as e: msg = messages.FAILED_TO_START_TEMPLATE.format(str(e)) await send_message(msg) await state.finish() bot.messengers.pop(state.user, None) await send_message(messages.CANCELLED, reply_markup=markups.DEFAULT_MARKUP)
async def check_language(message: types.Message): locale = message.from_user.locale await message.reply(md.text(md.bold('מידע על השפה שלך: '), md.text('🔸', md.bold('קוד מדינה: '), md.code(locale.language)), md.text( '🔸', md.bold('טריטוריה: '), md.code(locale.territory or 'לא ידוע ')), md.text('🔸', md.bold('שם שפה: '), md.code(locale.language_name)), md.text('🔸', md.bold('שם השפה באנגלית: '), md.code(locale.english_name)), sep='\n'), parse_mode=ParseMode.MARKDOWN)
async def receive_new_project_settings(message: types.Message, user: User, state: FSMContext): file = await bot.get_file(message.document['file_id']) settings = io.BytesIO() await file.download(settings) try: s = json.load(settings) async with OrmSession() as session: async with state.proxy() as data: project = await session.get(Project, data['project_id']) project.settings = s await session.commit() await message.reply(text(text('Проект', project.name), text('Новые настройки для проекта', project.name), code(json.dumps(s, indent=4, sort_keys=True)), sep='\n'), parse_mode=types.ParseMode.MARKDOWN) await state.finish() except json.decoder.JSONDecodeError: await message.reply( 'Это совсем не похоже на json-файл, пришлите другой файл', reply_markup=types.ForceReply(selective=True)) except UnicodeDecodeError: await message.reply( 'Это совсем не похоже на json-файл, у него вообще неизвестный бинарный формат, пришлите другой файл', reply_markup=types.ForceReply(selective=True))
async def cmd_status(message: types.Message, state: dispatcher.FSMContext): if state.user in bot.messengers and not bot.messengers[state.user].stop: messenger = bot.messengers[state.user] if messenger.last_time: seconds = (datetime.datetime.now() - messenger.last_time).total_seconds() last_message = md.text( f'Last attempt:', md.bold(f'{seconds:.1f}'), f'seconds ago. {messenger.last_message}', ) else: last_message = '' msg = md.text( md.text('Status: RZD Monitor is', md.bold('active'), '.'), md.text('Params:'), md.code(f'{helpers.dump_to_json(messenger.args)}'), last_message, sep='\n', ) else: msg = md.text( md.text('Status: RZD Monitor is '), md.bold('down'), md.bold('.'), sep='', ) await message.reply( msg, reply_markup=markups.DEFAULT_MARKUP, parse_mode=ParseMode.MARKDOWN, )
async def process_project_settigns_file(message: types.Message, user: User, chat: Chat, state: FSMContext): dt = message.date file = await bot.get_file(message.document['file_id']) settings = io.BytesIO() await file.download(settings) try: s = json.load(settings) async with OrmSession() as session: async with state.proxy() as data: project = Project( owner_user_id=user.id, name=data['project_name'], chat_id=chat.id, period_bucket_mode=human_period_bucket_modes[data['human_period_bucket_mode']], created_dt=dt, settings=s ) session.add(project) await session.commit() await message.reply( text( text('Проект', project.name, 'создан'), text('Примененные настройки:'), code(json.dumps(s, indent=4, sort_keys=True)), sep='\n' ), parse_mode=types.ParseMode.MARKDOWN ) await state.finish() except json.decoder.JSONDecodeError: await message.reply( 'Это совсем не похоже на json-файл, пришлите другой файл', reply_markup=types.ForceReply(selective=True) )
def get_all_posts(self): get = db.connect() user_id = env.int("ADMINS") query = 'SELECT token FROM USERS WHERE user_id=?' get_token = get.execute(query, (user_id, )) token = get_token.fetchone()[0] url = 'https://experts-community.herokuapp.com/api' headers = {'Authorization': f'Token {token}'} resp = requests.get(url, headers=headers) posts = resp.json() count = posts['count'] book = self._book _ = '\n__________________________________\n' for i in range(len(posts['results'])): book.append( (emoji.emojize(":rocket:") * 3 + hitalic(f'Всего {count} страниц.' + emoji.emojize(":rocket:") * 3 + f'{_}')) + '\n' + ('Автор: ' + hunderline( str(posts['results'][i]['author']['first_name']) + ' ' + str(posts['results'][i]['author']['last_name']))) + f'{_}' + 'Название: ' + str(posts['results'][i]['title']) + f'{_}' + 'Содержание: \n' + hitalic(str(posts['results'][i]['content'])) + f'{_}' + 'Дата: ' + code(str(posts['results'][i]['created_at'][:10])), ) return book
async def claim_currency(call: types.CallbackQuery): """Set cashback currency and suggest last escrow address.""" currency = call.data.split()[1] cursor = (database.cashback.find({ "id": call.from_user.id, "currency": currency, "address": { "$ne": None } }).sort("time", pymongo.DESCENDING).limit(1)) last_cashback = await cursor.to_list(length=1) if last_cashback: address = last_cashback[0]["address"] keyboard = InlineKeyboardMarkup(row_width=1) keyboard.add( InlineKeyboardButton( i18n("confirm_cashback_address"), callback_data=f"claim_transfer {currency} {address}", ), InlineKeyboardButton( i18n("custom_cashback_address"), callback_data=f"custom_cashback_address {currency}", ), ) await call.answer() await tg.edit_message_text( i18n("use_cashback_address {address}").format( address=markdown.code(address)), call.message.chat.id, call.message.message_id, reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN, ) else: return await custom_cashback_address(call)
async def process_has_corona(message: types.Message, state: FSMContext): async with state.proxy() as data: data['has_corona'] = message.text corona_states = { "Yes": "do", "No": "do not", "Not certain": "do not know if you" } # Remove keyboard markup = types.ReplyKeyboardRemove() # And send message await bot.send_message( message.chat.id, md.text( md.text('Hi! Nice to meet you,', md.bold(data['firstname'])), md.text('Age:', md.code(data['age'])), md.text('Gender:', data['gender']), md.text('Height:', data['height']), md.text( f'You {corona_states[data["has_corona"]]} have corona'), sep='\n', ), reply_markup=markup, parse_mode=ParseMode.MARKDOWN, ) await state.finish()
async def any_format(message: types.Message): msgtext = text(emojize("Я не знаю, что с этим делать :astonished:"), italic('Я просто напомню, что есть'), code('команда'), "/help") await bot.send_message(message.from_user.id, msgtext, parse_mode=ParseMode.MARKDOWN)
async def get_posts(message: types.Message): get = db.connect() user_id = message.from_user.id query = 'SELECT token FROM USERS WHERE user_id=?' get_token = get.execute(query, (user_id, )) token = get_token.fetchone()[0] url = 'https://experts-community.herokuapp.com/api' headers = {'Authorization': f'Token {token}'} resp = requests.get(url, headers=headers) posts = resp.json() count = posts['count'] await message.answer(f'Всего на сайте опубликовано {count} постов.') book = [] for i in range(len(posts['results'][:2])): await message.answer( (emoji.emojize(":rocket:") * 10) + '\n' + ('Автор:) ' + hunderline( str(posts['results'][i]['author']['first_name']) + ' ' + str(posts['results'][i]['author']['last_name']))) + '\n' + 'Название: ' + str(posts['results'][i]['title']) + '\n' + 'Содержание: ' + hitalic(str(posts['results'][i]['content'])) + '\n' + 'Дата: ' + code(str(posts['results'][i]['created_at'][:10])) + '\n' + (emoji.emojize(":rocket:") * 10))
async def get_logs(message: types.Message): check_id(message.from_user) logger.info(f"{message.from_user.username} do getlog command") if message.from_user.id == ADMIN_ID: try: int(message.text[9:]) except ValueError: await message.chat.do(types.ChatActions.UPLOAD_DOCUMENT) await message.reply_document(types.InputFile(f"logs/current.log"), caption="The logs file", reply_markup=key) else: await message.chat.do(types.ChatActions.TYPING) logs = (open(f"logs/current.log", "r").readlines())[-int(message.text[9:]):] log = str() for i in logs: log += i msg = markdown.text(markdown.italic("logs:"), markdown.code(log), sep="\n") try: await message.reply(msg, parse_mode=ParseMode.MARKDOWN, reply_markup=key) except MessageIsTooLong: await message.reply(markdown.bold("Too much logs ! ❌"), reply_markup=key)
async def unknown_message(msg: types.Message): ''' echo bot for not message ''' message_text = md.text( emojize('I do not know what to do about it :astonished:'), md.italic('\nI will just remind,'), 'you that there', md.code('is a command'), '/help') await msg.reply(message_text, parse_mode=types.ParseMode.MARKDOWN)
async def cmd_start(message: types.Message): content = [] # Make request (without proxy) ip = await fetch(GET_IP_URL) content.append(text(':globe_showing_Americas:', bold('IP:'), code(ip))) # This line is formatted to '🌎 *IP:* `YOUR IP`' # Make request through proxy ip = await fetch(GET_IP_URL, bot.proxy, bot.proxy_auth) content.append( text(':locked_with_key:', bold('IP:'), code(ip), italic('via proxy'))) # This line is formatted to '🔐 *IP:* `YOUR IP` _via proxy_' # Send content await bot.send_message(message.chat.id, emojize(text(*content, sep='\n')), parse_mode=ParseMode.MARKDOWN)
async def calculationInlineQueryHandler(inline_query: InlineQuery): answer = str(eval(inline_query.query.replace("=", "").replace(",", "."))) messToUser = markdown.code(inline_query.query.replace( " ", "")) + markdown.code(answer) items = [ InlineQueryResultArticle( id=str(time()), title='Результат вычислений:', thumb_url='https://i.ibb.co/QmWSC1N/Untitled-2.png', description=answer, input_message_content=InputTextMessageContent( messToUser, parse_mode='MarkdownV2')) ] await bot.answer_inline_query(inline_query.id, results=items, cache_time=50000000)
async def cmd_start(message: types.Message): # fetching urls will take some time, so notify user that everything is OK await types.ChatActions.typing() content = [] # Make request (without proxy) async with aiohttp.ClientSession() as session: ip = await fetch(GET_IP_URL, session) content.append(text(':globe_showing_Americas:', bold('IP:'), code(ip))) # This line is formatted to '🌎 *IP:* `YOUR IP`' # Make request through bot's proxy ip = await fetch(GET_IP_URL, bot.session) content.append(text(':locked_with_key:', bold('IP:'), code(ip), italic('via proxy'))) # This line is formatted to '🔐 *IP:* `YOUR IP` _via proxy_' # Send content await bot.send_message(message.chat.id, emojize(text(*content, sep='\n')), parse_mode=ParseMode.MARKDOWN)
async def eval_cmd(message: types.Message): check_id(message.from_user) logger.info(f"{message.from_user.username} do eval command") if message.from_user.id == ADMIN_ID: msg = markdown.text(markdown.italic("eval:"), markdown.code(eval(message.text[6:])), sep="\n") await message.reply(msg, parse_mode=ParseMode.MARKDOWN, reply_markup=key)
async def unknown_message(msg: types.Message): message_text = text(emojize('Я не знаю, что с этим делать :astonished:'), italic('\nЯ просто напомню,'), 'что есть', code('команда'), '/help') if msg.content_type == "text": with open("source/history.txt", 'a') as f: f.write( str(msg.date) + " [" + str(msg.chat.id) + "] " + msg.chat.first_name + ": " + msg.text + "\n") await msg.reply(message_text, parse_mode=ParseMode.MARKDOWN)
async def total_message(id, count, name_sender = None, add_gas=0): ''' last message ''' if id == admin: #send message to admin await bot.send_message(id, f'{name_sender} sent data') await bot.send_message(id, md.text( md.text('Gas - ', md.bold(count.gas_cost)), md.text('Water - ', md.bold(count.water_cost)), md.text('Electricity - ', md.bold(count.el_cost)), md.bold(f'AMOUNT {count.mouth} for a month:'), md.code(round(count.tot + add_gas, 2)), sep='\n' ), parse_mode=ParseMode.MARKDOWN)
async def budget_handler(callback: types.CallbackQuery): if callback.data == 'budget_add': await callback.message.edit_text(text='Выберите категорию.', reply_markup=dp['kb'].budget_category()) await Page.budget_add.set() if callback.data == 'bugdet_today': expenses = await dp['db'].last_day() summ = sum([exp[1] for exp in expenses]) expense_strings = [str(exp[3]).split(' ')[-1][:-3] + ' - ' + exp[0] + ' - ' + str(exp[1]) + 'р. ' + ' ' + exp[2] for exp in expenses] await callback.message.edit_text(text=text(bold('Расходы на день'), code(f'Всего: {summ}р.'), '\n'.join(expense_strings), sep='\n\n'), reply_markup=dp['kb'].budget_amount()) await Page.budget_last.set() if callback.data == 'budget_month': expenses = await dp['db'].last_month() summ = sum([exp[1] for exp in expenses]) expense_strings = [exp[3][8:-3] + ' - ' + exp[0] + ' - ' + str(exp[1]) + 'р. ' + ' ' + exp[2] for exp in expenses] await callback.message.edit_text(text=text(bold('Расходы за месяц'), code(f'Всего: {summ}р.'), '\n'.join(expense_strings), sep='\n\n'), reply_markup=dp['kb'].budget_amount()) await Page.budget_month.set() await callback.answer()
async def cmd_wanip(message: types.Message): try: log.info(f'Command \"/wanip\" from user {message.from_user.id}') if message.from_user.id not in ALLOWED_IDS: await message.answer( 'Sorry. You have no permission to use this command') return ip = get_wan_ip() await message.answer(md.text('Your WAN IP address \- ', md.code(ip)), parse_mode=ParseMode.MARKDOWN_V2) except Exception as err: log.error(f'[/wanip] {err}')
async def get_db(message: types.Message): check_id(message.from_user) logger.info(f"{message.from_user.username} do getdb command") if message.from_user.id == ADMIN_ID: with Session as session: users = dict() for u in session.query(User).all(): users[u] = u.__dict__ msg = markdown.text(markdown.italic("db:"), markdown.code(users), sep="\n") await message.reply(msg, parse_mode=ParseMode.MARKDOWN, reply_markup=key)
async def new_name_handler(message: types.Message): new_name = generate_chat_name() if is_group(message) and member_can_change_info(message): try: await message.chat.set_title(new_name) except (exceptions.ChatAdminRequired, exceptions.BadRequest): await message.reply( f'{code(new_name)}\n\n{bold(ANSWERS["admin_required"])}') elif is_group(message) and not random.randint(0, 5): await message.reply(ANSWERS['message_not_from_admin']) else: await message.reply(code(new_name))
async def errors_handler(update: types.Update, exception: Exception): """Handle exceptions when calling handlers. Send error notification to special chat and warn user about the error. """ if isinstance(exception, MessageNotModified): return True log.error("Error handling request {}".format(update.update_id), exc_info=True) chat_id = None if update.message: update_type = "message" from_user = update.message.from_user chat_id = update.message.chat.id if update.callback_query: update_type = "callback query" from_user = update.callback_query.from_user chat_id = update.callback_query.message.chat.id if chat_id is not None: try: exceptions_chat_id = config.EXCEPTIONS_CHAT_ID except AttributeError: pass else: await tg.send_message( exceptions_chat_id, "Error handling {} {} from {} ({}) in chat {}\n{}".format( update_type, update.update_id, markdown.link(from_user.mention, from_user.url), from_user.id, chat_id, markdown.code(traceback.format_exc(limit=-3)), ), parse_mode=types.ParseMode.MARKDOWN, ) await tg.send_message( chat_id, i18n("unexpected_error"), reply_markup=start_keyboard(), ) return True
async def process_gender(message: types.Message, state: FSMContext): async with state.proxy() as data: data['gender'] = message.text # Remove keyboard markup = types.ReplyKeyboardRemove() # And send message await bot.send_message( message.chat.id, md.text( md.text('Принято,', md.bold(data['name'])), md.text('Возраст:', md.code(data['age'])), md.text('Стрижка:', data['gender']), md.text('\n'), md.text('Ожидайте сейчас подберем вам ближайшую дату...'), sep='\n', ), reply_markup=markup, parse_mode=ParseMode.MARKDOWN, ) await bot.send_message( message.chat.id, 'Принятые данные можно пересылать администратору или мастеру, ' 'также боту можно задать календарь для того чтобы он сам вел диалог и ' 'выбирал ближайшую дату для записи. Можно также задать прайс (с ценами ' 'рисунками) и систему оплаты\n.Подключить бота к Базе Данных, ' 'к CRM системе или к сайту и ' 'может выполнять ту же механическую работу вместо администратора, ' 'менеджера по продажам и т.д. т.е. все те действия где не требуется ' 'личного пристутствия человека или голосовые ответы (звонки и ' 'прочее), Все эти процессы можно автоматизировать... \n\nДалее ' 'пересылаем ссобщение администратору, тем самым сократив ему время на ' 'диалоги и т.д. Админу останется только выбрать дату и ответить боту, ' 'чтоб бот уведомил клиента о записи, или админ может написать клиенту ' 'напрямую.. ') await bot.send_message( message.chat.id, 'Если хотите узнать более подробно о работе ботов, напишите создателю ' 'этого демо-бота @vildan_valeev\n\nНачать заново нажмите /start') # Finish conversation await state.finish()