async def posheldfind(chat: Chat, match): async with bot._db_conn.acquire() as conn: query = """ SELECT position.name as position, first_name as fname, last_name as lname, middle_name as mname, time_from, time_to, cabinet.name as cabinet FROM posheld JOIN position ON position.id=posheld.position_id JOIN employee on employee.id=posheld.employee_id JOIN schedule on schedule.employee_id=posheld.employee_id JOIN cabinet on cabinet.id=schedule.cabinet_id WHERE position.name LIKE '%{}%' LIMIT 10; """.format(match.group(1)) result = await (await conn.execute(query)).fetchall() log.debug(result) if result and len(result) == 1: ans = result[0] efio = "{} {} {}".format(ans.lname, ans.fname, ans.mname) return chat.reply('{} {} сейчас в {}'.format( ans.position, efio, ans.cabinet)) return chat.reply('Уточните ваш запрос') return chat.reply('Извините, по вашему запросу ничего не найдено')
def echo(chat: Chat, match): date = datetime.date.today() day_x = datetime.date(year=2019, month=3, day=14,) if date == day_x: return chat.reply("NO, YOU CAN'T TODAY!") else: return chat.reply("Yes, ofcourse, if tests are good and you want to.")
async def create_new_app(chat: Chat, match): private_id = chat.sender["id"] app_name = str(match.group(1)) print(str(private_id) + " " + str(app_name)) if UserData.select().where(UserData.app_name == app_name): return chat.reply("App with this name already exists") else: UserData.create(app_name=app_name, private_id=private_id).save() return chat.reply("App " + str(app_name) + " successfully create")
async def get_proff(chat: Chat, match): async with bot._db_conn.acquire() as conn: query = """ SELECT * FROM employee WHERE CONCAT(last_name,' ',first_name,' ',middle_name,' ') LIKE '%{0}%' LIMIT 10; """.format(match.group(1)) result = await (await conn.execute(query)).fetchall() log.debug(result) if result and len(result) == 1: employee = result[0] schedule_query = """ SELECT cabinet.name, schedule.time_from, schedule.time_to FROM schedule JOIN cabinet ON schedule.cabinet_id=cabinet.id WHERE (curtime() between time_from and time_to) and (weekday(curdate())=weekday) and (employee_id='{}'); """.format(employee.id) schedule = await (await conn.execute(schedule_query)).fetchone() log.debug(schedule) efio = "{} {} {}".format(employee.last_name, employee.first_name, employee.middle_name) if schedule: time_from = str(schedule.time_from)[:-3] time_to = str(schedule.time_to)[:-3] return chat.reply("{} сейчас({}-{}) в {}".format( efio, time_from, time_to, schedule.name)) return chat.reply("Я не знаю, где сейчас {}".format(efio)) if result and len(result) > 1: kb = { 'type': 'InlineKeyboardMarkup', "inline_keyboard": list([[{ 'type': 'InlineKeyboardButton', "text": "{} {} {}".format(i.last_name, i.first_name, i.middle_name), "callback_data": "proff-{}".format(i.id) }] for i in result]) } log.debug(kb) return chat.send_text('Уточните запрос', reply_markup=json.dumps(kb)) return chat.reply("По вашему запросу ничего не найдено")
async def token_handler(self, chat: Chat, math): """Telegram id to API token handler""" self.logger.info("Recieved convert to token request") self.logger.debug("Raw: %s", chat.sender.items()) token = self.token.to_token(tid=chat.sender["id"]) self.logger.debug("Cache info: %s", self.token.to_token.cache_info()) return chat.reply(token)
async def help_handler(self, chat: Chat, math): """Help command handler""" self.logger.info("Recieved help request") help_msg = ("*Message forward bot*\n" "*/token* -- get your API token\n\n" "Please readme [Manual]({url})").format(url=self._api_url) return chat.reply(help_msg, parse_mode="Markdown")
async def square_command(chat: Chat, match): val = match.group(1) try: val = float(val) square = await get_square.call(val) resp = f'Square for {val} is {square}' except: resp = 'Invalid number' return chat.reply(resp)
async def square_command(chat: Chat, match): val = match.group(1) try: val = float(val) square = await get_square.call(val) resp = f"Square for {val} is {square}" except Exception(): resp = "Invalid number" return chat.reply(resp)
async def find_path(chat: Chat, match): async with bot._db_conn.acquire() as conn: query = """ SELECT * FROM cabinet WHERE cabinet.name='{}' AND cabinet.auditoria='1' LIMIT 1; """.format(match.group(1)) start = await (await conn.execute(query)).fetchone() query = """ SELECT * FROM cabinet WHERE cabinet.name='{}' AND cabinet.auditoria='1' LIMIT 1; """.format(match.group(2)) end = await (await conn.execute(query)).fetchone() if not start: return chat.reply('Увы, я не знаю где находится {}'.format( match.group(1))) if not end: return chat.reply('Увы, я не знаю где находится {}'.format( match.group(2))) filename = 'bmstuplan_{}_to_{}'.format(start.id, end.id) command = 'python "bmstumap_admin/manage.py" createpath {} {}'.format( start.id, end.id) foutput = _check(filename, command) log.debug('sending file {}'.format(foutput)) with open(foutput, 'rb') as file: await chat.send_photo(file) await asyncio.wait(0)
async def message(chat: aiotg.Chat, match): db_chat: Chat = await Chat.get(str(chat.id)) if not db_chat: db_chat: Chat = await create_chat_in_db(chat) if chat.message['chat']['type'] == 'group': pass if db_chat.chat_state == ChatState.EXPECT_TIME_WHEN_SEND_NOTIFY: try: hours, minutes = map(int, chat.message['text'].split(':')) from datetime import time time = time(hours, minutes, 0) except Exception: return chat.reply('Что-то не очень похоже на время. что то типа "12:22" я бы понял.') await db_chat.update( chat_state=ChatState.NORMAL, notify_next_date_time=datetime.combine( db_chat.notify_next_date_time.date(), time ), editing_task_id=None ).apply() return chat.reply(f'Устновлено время уведомления - {time:%H:%M}') elif db_chat.chat_state == ChatState.EXPECT_TASK: editing_task = await Task.create( content=chat.message['text'], message_id=str(chat.message['message_id']), chat_id=str(chat.id) ) await db_chat.update( chat_state=ChatState.EXPECT_PERIOD, editing_task_id=editing_task.id ).apply() return chat.reply('Теперь введите периодичность в днях (просто целое число!)') elif db_chat.chat_state == ChatState.EXPECT_PERIOD and db_chat.editing_task_id: try: period = int(chat.message['text']) except Exception: return chat.reply('Что-то не очень похоже на число. что то типа "5" я бы понял, но не это.') task: Task = await Task.get(db_chat.editing_task_id) await db_chat.update(chat_state=ChatState.NORMAL, editing_task_id=None).apply() if not task: chat.reply(f"Уже такой задачи нет. ({db_chat.editing_task_id})") await task.update(period_days=period).apply() return chat.send_text( f'Устанавливлен период {period} {plural_days(period)}.', reply_to_message_id=task.message_id ) return chat.reply('не ожидал что ты что-то мне ' 'тут напишешь без предупреждения ' '(без запроса). Или я что-то не понял.')
def sticker(chat: Chat, sticker: dict): """ Handle stickers In private chat: debug purposes only In groups: deletes some stickers (whitelist of stickersets), may react to usage of others """ # HistoryLogger.log(chat) if chat.type == "private": return chat.reply( f"Sticker set: {sticker['set_name']}, sticker id: {sticker['file_id']}" ) if sticker['set_name'] not in c.ALLOWED_STICKERS: return bot.api_call('deleteMessage', chat_id=chat.id, message_id=chat.message['message_id'])
async def handle_inbound_message(self, chat_obj: Chat, *args, **kwargs): # noinspection PyBroadException try: log.debug( f"Handling inbound message {chat_obj}. args={args} kwargs={kwargs}" ) await self._pre_process_msg(chat_obj) running_command = self.map_chat_id_running_command.get(chat_obj.id) if running_command: if len(args) > 0 and isinstance(args[0], aiotg.CallbackQuery): data = CallbackQueryData(**args[0].src) else: data = MessageData(**chat_obj.message) # noinspection PyProtectedMember running_command._q.put_nowait(data) else: new_command = self._dispatch_initial_message(chat_obj) if new_command: log.info( f"Command '{type(new_command).__name__}' was created") # TODO FIX: save task reference to close correctly on exit asyncio.ensure_future( self._run_command(new_command, chat_obj)) else: chat_obj.reply("Unknown command!") except Exception: log.exception( f"Exception during handling inbound message {chat_obj}")
async def menu(chat: aiotg.Chat, match): markup = await make_menu_markup(chat) chat.reply("Выбери действие:", markup=markup)
async def start(chat: aiotg.Chat, match): db_chat: Chat = await Chat.get(str(chat.id)) if not db_chat: db_chat: Chat = await create_chat_in_db(chat) return chat.reply('Привет. Начни с того что сразу введи дело.') return chat.reply(f'Рад видеть тебя снова {GREETING_BY_STATE[db_chat.chat_state]}')
def ping(chat: Chat, match): return chat.reply('pong')
async def start(chat: Chat, match): return chat.reply("Send me photo of cat or dog.")
async def start(chat: Chat, match): return chat.reply("Send me photo of wheat.")
def start(chat: Chat, match): """ Hello, it's me! """ if c.START_MSG: return chat.reply(c.START_MSG)
def whoami(chat: Chat, match): """ [For debug purposes only] Get telegram user id """ if chat.type == "private": return chat.reply(chat.sender["id"])
async def ping_handler(self, chat: Chat, math): """Healthcheck handler""" self.logger.info("Recived ping request -> return pong") return chat.reply("pong")
async def execute(self, chat: Chat, rematch: match): chat.reply(rematch.group(1))
async def start(chat: Chat, match): return chat.reply("Send me photo of ant or bee.")
def echo(chat: Chat, match): return chat.reply(match.group(1))