async def handle_pause(message: types.Message): """ Pause/resume the song. """ if message.get_command() == '/pause': msg = audioplayer.pause() elif message.get_command() == '/unpause': msg = audioplayer.unpause() else: msg = "Command not valid" await bot.send_message(message.chat.id, msg)
async def handle_pause(message: types.Message): """ Turn the volume up/down. """ # TODO Show keyboard if message.get_command() == '/vol_up': print('Volume up') audioplayer.volume_up() elif message.get_command() == '/vol_down': print('Volume down') audioplayer.volume_down() else: msg = "Volume command not valid" await bot.send_message(message.chat.id, msg)
async def cmd_stats(message: types.Message) -> None: rmsg = message.reply_to_message if message.chat.id < 0 and not message.get_command().partition("@")[2]: return user = (rmsg.forward_from or rmsg.from_user) if rmsg else message.from_user async with pool.acquire() as conn: res = await conn.fetchrow("SELECT * FROM player WHERE user_id = $1;", user.id) if not res: await message.reply( f"No statistics for {user.get_mention(as_html=True)}!", parse_mode=types.ParseMode.HTML, ) return mention = user.get_mention( name=user.full_name + (" \u2b50\ufe0f" if await has_star(user.id) else ""), as_html=True, ) text = f"\U0001f4ca Statistics for {mention}:\n" text += f"<b>{res['game_count']}</b> games played\n" text += f"<b>{res['win_count']} ({res['win_count'] / res['game_count']:.0%})</b> games won\n" text += f"<b>{res['word_count']}</b> total words played\n" text += f"<b>{res['letter_count']}</b> total letters played\n" if res["longest_word"]: text += f"Longest word: <b>{res['longest_word'].capitalize()}</b>" await message.reply(text.rstrip(), parse_mode=types.ParseMode.HTML)
async def style_chosen_handler(message: types.Message, state: FSMContext): shortcut = message.get_command(pure=True) if shortcut: await StylizationRequest.waiting_for_style_chosen.set() task_type = shortcuts_to_task_types[shortcut] style = task_types_to_buttons[task_type] answer_text = f"You requested stylization — {style}.\n\n" else: for task_type, style in task_types_to_buttons.items(): if style in message.text: break else: raise RuntimeError( f"could not find task_type for {message.text} message") answer_text = f"You chose — {style}.\n\n" await state.update_data(task_type=task_type, images=[]) await StylizationRequest.next() keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True) keyboard.add("OK (get results as photos, by default)") keyboard.add("OK (get results as files, less compression)") keyboard.add("Cancel") answer_text += (f"Now please send " f"up to {get_max_pics_per_request(task_type)} images. ") if task_type is TaskType.style_transfer: answer_text += ( "Number of images must be even and images must be sent one by one " "as follows:\n\n\ttarget image #1\n\tstyle image #1" "\n\ttarget image #2\n\tstyle image #2\n\t...") answer_text += ( "\n\nThen please wait until uploading finished " "(otherwise images can be missed) and " "press OK to start processing images or press Cancel at any time " "if you changed your mind and want to do something different.") await message.answer(answer_text, reply_markup=keyboard)
async def cmd_stats(message: types.Message) -> None: rmsg = message.reply_to_message if (message.chat.id < 0 and not message.get_command().partition("@")[2] or rmsg and (rmsg.from_user.is_bot and rmsg.from_user.id != ON9BOT_ID and not rmsg.forward_from or rmsg.forward_from and rmsg.forward_from.is_bot and rmsg.forward_from.id != ON9BOT_ID)): return user = rmsg.forward_from or rmsg.from_user if rmsg else message.from_user async with pool.acquire() as conn: res = await conn.fetchrow("SELECT * FROM player WHERE user_id = $1;", user.id) if not res: await message.reply(f"No statistics for {user.get_mention(as_html=True)}!", parse_mode=types.ParseMode.HTML) return await message.reply( f"\U0001f4ca Statistics for " + user.get_mention(name=user.full_name + (" \u2b50\ufe0f" if user.id in VIP or bool(await amt_donated(user.id)) else ""), as_html=True) + f":\n" f"<b>{res['game_count']}</b> games played\n" f"<b>{res['win_count']} (" f"{'0%' if not res['win_count'] else format(res['win_count'] / res['game_count'], '.0%')})</b> games won\n" f"<b>{res['word_count']}</b> total words played\n" f"<b>{res['letter_count']}</b> total letters played" + (f"\nLongest word used: <b>{res['longest_word'].capitalize()}</b>" if res["longest_word"] else ""), parse_mode=types.ParseMode.HTML )
async def exec(self, message: types.Message): chat_id = message.chat.id if chat_id not in self.cache: self.cache[chat_id] = { "state": "start", "lang": "ru", "address": {} } command = message.get_command() if command in langs: self.cache[chat_id]["lang"] = command current_state, lang = self.cache[chat_id]["state"], self.cache[ chat_id]["lang"] default_response = "" response_function = "" if current_state in list(self.text[lang].keys()) + ["start"]: default_response = self.text[ "start"] if current_state == "start" else self.text[lang][ current_state] response_function = await self.default(message) else: response_function = await self.__getattribute__(current_state)( message) return response_function if response_function else default_response
async def ege_countdown_command(message: types.Message): command = utils.get_relative_command(message.get_command()) date_string, subject_name = config.ege_countdown_commands[command] days_left = utils.get_days_until(datetime.fromisoformat(date_string)) await message.reply( f'До егэ по *{subject_name}* осталось {days_left} дней.', parse_mode=types.ParseMode.MARKDOWN)
async def demo_filter(message: types.Message): # Store some data in context command = data['command'] = message.get_command() or '' args = data['args'] = message.get_args() or '' data['has_args'] = bool(args) data['some_random_data'] = 42 return command != '/bad_command'
async def show_todo(message: types.Message): todo_type = str(message.get_command())[3:-4] txt = 'TO-' + todo_type.upper() + 's:\n' filename = get_filename(message, "list") todos = Storage(filename).get_todos() for todo in todos: txt += str(todo.id) + '. ' + todo.description await message.reply(txt)
async def me_cmd(msg: Message): await msg.delete() print(msg.get_command()) _, action = msg.parse_entities().split(' ', 1) await msg.answer(f"<pre>* " f"{msg.from_user.full_name} " f"{action}" f"</pre>", parse_mode="HTML" )
async def __on_command(self, message: types.Message): cmd = message.get_command() log.debug('Command ' + message.text) cmd = cmd[1:] if cmd in self.__callbacks: try: await self.__callbacks[cmd](message) except Exception: log.warning('Callback exception', exc_info=True) else: log.error('Unknown cmd ' + cmd)
async def send_top(message: types.Message): command = message.get_command() if command == "/popular": reply_markup = keyboards.create_popular_keyboard() elif command == "/top_rated": reply_markup = keyboards.create_top_rated_keyboard() else: reply_markup = keyboards.create_upcoming_keyboard() await message.answer(interface_text['option_choice'], reply_markup=reply_markup)
async def cmd_feedback(message: types.Message) -> None: rmsg = message.reply_to_message if (message.chat.id < 0 and not message.get_command().partition("@")[2] and (not rmsg or rmsg.from_user.id != BOT_ID) or message.forward_from): return arg = message.get_full_command()[1] if not arg: await message.reply("Function: Send feedback to my owner.\n" "Usage: `/feedback@on9wordchainbot feedback`") return await message.forward(ADMIN_GROUP_ID) await message.reply("Feedback sent successfully.")
async def commands(message: types.Message): comm = message.get_command() if comm == "/help": await message.answer( "Specify the settlement in which you are now and the search radius. For instance:" ) await message.answer("Yekaterinburg 50") await message.answer("Sysert. °2 С. Sunny\nBerezovsky. -1 °С. Snow") elif comm == "/start": await message.answer( "Hello! I am a bot that will show you the best places near you. Indicate your location (For example: Yekaterinburg 20)" )
async def send_welcome(message: types.Message): await StylizationRequest.waiting_for_style_chosen.set() if message.get_command(pure=True) != 'request': answer_text = "Hi! I'm a bot for neural style transfer. " else: answer_text = "" await message.answer( answer_text + "Please choose what you want to do:" "\n\t— style transfer to one image from another you'll give" "\n\t— or a one of the provided styles that you want " "to transfer to your images.", reply_markup=choosing_task_keyboard)
async def log_message_about_work(message: types.Message, user: User, chat: Chat, state: FSMContext): dt = message.date async with OrmSession() as session: select_stmt = select(Project) \ .where( Project.chat_id == chat.id ) \ .order_by(Project.id) projects_result = await session.execute(select_stmt) project = projects_result.scalars().first() bucket = PeriodBucket.new(project.period_bucket_mode, dt) items_list = await project.get_for_period(session, bucket) items_num = len(items_list.items) if items_list else 0 if items_num > 0: items_texts = [ item.text for item in sorted(items_list.items, key=lambda i: i.id) ] item_new_status = message.get_command(pure=True) await state.update_data(item_new_status=item_new_status) await state.update_data(items_num=items_num) await state.update_data(items_texts=items_texts) await state.update_data(items_ids=[ item.id for item in sorted(items_list.items, key=lambda i: i.id) ]) if items_num > 1: await ChangeItemStatusForm.item_id.set() keyboard = [[ types.KeyboardButton( f'{i+1}. {txt if len(txt) < 32 else txt[:29] + "..."}') ] for i, txt in enumerate(items_texts)] await message.reply( 'Выберите, пожалуйста, задачу из списка ' f'текущего периода по порядковому номеру от 1 до {items_num}', reply_markup=types.ReplyKeyboardMarkup(keyboard=keyboard, selective=True)) else: items_list.items[0].status = ItemStatus[item_new_status] await session.commit() await message.reply(emojize( text(text('В плане один единственный пункт:'), text(' :pushpin:', items_texts[0]), text(human_item_status[items_list.items[0].status]), sep='\n')), disable_web_page_preview=True) else: await message.answer( 'Извините, у вас ничего не запланировано в ближайшее время')
async def handle_get_style_photo(msg: types.Message, state: FSMContext): chat_id = msg.from_user.id folder_name = 'chat_id_%s' % chat_id await bot.send_message(chat_id, "Style transfer in progress...") file_content = os.path.join(os.getcwd(), folder_name, 'original.jpg') file_style = os.path.join(os.getcwd(), folder_name, 'style.jpg') file_output = os.path.join(os.getcwd(), folder_name, 'result.jpg') # adding a style transfer job to the queue model_name = msg.get_command().lower() queue_transfer_style.put( (model_name, file_content, file_style, file_output, chat_id)) calculations[chat_id] = True await state.finish()
async def plainMessageHandling(message: types.Message): # strip the @usernamebot from incoming commands, to keep this compatible with test bots i saved this username in credentials. message.text = message.text.replace(credentials.botUsername, '') commandText = message.get_command() commandArguments = message.get_args() # commands if commandText: #user commands if '/start' == commandText: # await the functions from the library file, pass the bot oject and the message, # in addition to any other params you might need, like commandText or commandArguments await F.startMessage(bot, message, other_args) # forwards if message.forward_from: if message.forward_from.username == 'Lynnsane' and 'Example Forward' in message.text: await F.functionsExample(bot, message, other, args)
def parse_topics(message: types.Message): topics = [x.strip() for x in message.get_args().split(',') if x.strip()] cmd = message.get_command() user = message.from_user chat = message.chat hub2_log.info( "%s (%s %s) (%s %s) %s", cmd, user.id, user.full_name, chat.id, chat.type, topics, ) event = Event(user, chat) # hub2_log.debug(event) return event, topics
async def _handle_update(self, message: types.Message): command = message.get_command(pure=True) if command and command in self.actions.keys(): action = self.actions.get(command) args = message.get_args().strip().split() # set params in cache [USER_COMMANDS_CACHE[f'command:{message.chat["id"]}'].add(arg) for arg in args] flag, response = action.execute(USER_COMMANDS_CACHE[f'command:{message.chat["id"]}']) # flush cache if success if flag: del USER_COMMANDS_CACHE[f'command:{message.chat["id"]}'] await message.answer(response) else: await message.answer("Hi! available commands are:\n\n" + "\n".join(self.commands_list))
async def command_minecraft(message: types.Message, user: User): # Skip if not superuser sent command to private chat or not to main group if (not user.is_superuser and message.chat.type == "private") \ or (message.chat.id != MAIN_GROUP_ID and message.chat.type != "private"): return False logger.info("User {user_id} try to send message to Minecraft {chat_id}.", user_id=message.from_user.id, chat_id=message.chat.id) if not user.mc_username: await message.reply( "Я не знаю твій нікнейм на сервері, " "будь ласка зв'яжи акаунти за допомогою команди /link " "або зареєструйся на сервері /register.") return False command = message.get_command() text = message.get_args() if not text: await message.reply(f"Напиши своє повідомлення так: {command} test") return False await message.chat.do("typing") try: responce = RCONCommandSender.send( "telegram-chat-response <{username} {confirmed}> {text}".format( username=user.mc_username, text=text, confirmed="✔" if bool(user.mc_username) else "⚠")) logger.info("Server /mc response: ", responce) is_sent = "Message sent to Minecraft Chat." in responce if is_sent: answer = f"Повідомлення доставлено під ніком <b>{user.mc_username}</b>." else: answer = "Повідомлення не доставлено." except: answer = "Сервер вимкнено" await message.reply(answer) return True
async def meta_action(msg: Message): chat = await get_chat(msg.chat.id) command = msg.get_command(pure=True) command = await ActionCommand.get_or_none(chat_id=chat, command=command) if not command: return templates = await command.templates gifs = await command.attachs sender = msg.from_user.full_name repicient = get_repicient(msg) template = choice(templates).text if '{passive}' in template and not repicient: await msg.reply('Либо реплай, либо укажи текстом') return reply = prepare_reply(sender, repicient, template) await msg.reply(reply, parse_mode='HTML') if gifs: gif = choice(gifs).file_id await msg.answer_animation(gif)
async def schedule(session: orm.Session, scheduler: _MessageScheduler, message: types.Message) -> None: db_chat = session.query(Chat).get(message.chat.id) if db_chat is None: logging.error(f"Chat {message.chat.id} not found in database") return dates = utils.search_dates(message.get_args(), db_chat.timezone, message.date) if not dates: await message.reply("Не могу найти дату :(") return deadline = dates[0] if deadline < datetime.datetime.now(tz=datetime.timezone.utc): await message.reply("Эта дата уже прошла!") return bot_message = await message.reply( f"Запланировано на {deadline.strftime('%d.%m.%y %H:%M:%S')}") command = message.get_command() text = message.html_text.lstrip(command) scheduler.add_task(text, deadline, message.chat.id, bot_message.message_id)
async def command_register(message: types.Message, user: User): if not types.ChatType.is_private(message): reply_markup = None if message.get_args(): await message.delete() if user.mc_username and not message.reply_to_message: answer_text = ( f"Ти вже зареєстрований з нікнеймом - <b>{user.mc_username}</b>!\n\n" "Але нагадаю, що для реєстрації " "необхідно перейти в діалог з ботом @nurecraft_bot та повторити команду особисто." ) else: answer_text = ( "Для реєстрації на сервері " "перейдіть в діалог з ботом @nurecraft_bot та повторіть команду.\n\n" "Або просто натисніть кнопку:") reply_markup = types.InlineKeyboardMarkup(inline_keyboard=[[ types.InlineKeyboardButton( "Відкрити бота", url="https://t.me/nurecraft_bot?start=register") ]]) return await message.answer(answer_text, parse_mode="html", disable_web_page_preview=True, reply_markup=reply_markup) logger.info("User {user_id} try to register {chat_id}.", user_id=message.from_user.id, chat_id=message.chat.id) if user.mc_username: return await message.reply( "Ти вже зареєстрований на сервері з нікнеймом: " f"<b>{user.mc_username}</b>") command = message.get_command() args = message.get_args().split() if 0 >= len(args) or len(args) > 2: return await message.reply( f"Напиши своє повідомлення так: <pre>{command} username " "password</pre>\n\nДе <b>username</b> - бажаний нікнейм на " "сервері, <b>password</b> - твій бажаний пароль.") username, password = args await message.chat.do("typing") try: responce = RCONCommandSender.send( "authme register {username} {password}".format(username=username, password=password)) logger.info("Server /register response: " + responce) except: return await message.answer("Сервер вимкнено, спробуй пізніше..") is_success = "пройшла успішно!" in responce await message.reply( responce + 'Тепер ти можеш грати на сервері!' if is_success else responce) if is_success: await user.update(mc_username=username).apply() return True
def get_filename(message: types.Message, end_data: str): chat_id = str(message.chat.id) cut_end = len(end_data) todo_type = str(message.get_command()[3:-cut_end]) return chat_id + '_' + todo_type + '.td'
def is_command(message: types.Message, command: str): return message.is_command() and message.get_command().startswith(f'/{command}')
async def status_report(message: types.Message, chat: Chat): if message.get_command() == '/wsr': start_dt = message.date + relativedelta( weekday=WE(-1), hour=0, minute=0, second=0, microsecond=0) end_dt = message.date + relativedelta(weekday=WE, hour=0, minute=0, second=0, microsecond=0) \ - relativedelta(days=1) else: start_dt = message.date + relativedelta( day=1, hour=0, minute=0, second=0, microsecond=0) end_dt = message.date + relativedelta(months=1, day=1, hour=0, minute=0, second=0, microsecond=0, days=-1) grid = generate_grid(start_dt, end_dt) grid = [[[i[0], i[1]] for i in week] for week in grid] async with OrmSession() as session: select_stmt = select(Project) \ .where( Project.chat_id == chat.id ) \ .order_by(Project.id) projects_result = await session.execute(select_stmt) project = projects_result.scalars().first() from_period = PeriodBucket.new(project.period_bucket_mode, start_dt) todo_lists = await project.get_since(session, from_period, with_log_messages=True) message_content = [] for todo_list in todo_lists: bucket = PeriodBucket.get_by_key(todo_list.period_bucket_key) for todo_item in todo_list.items: message_content.append( text(':spiral_calendar_pad:', str(bucket), ':pushpin:', todo_item.text)) for log_message in todo_item.notes: message_content.append( text(':paperclip:', log_message.text)) message_content.append(text('')) if bucket.start(): for week in grid: for i in week: if i[1].date() == bucket.start().date(): i[0] = i[0].replace('white', 'purple') import io file = io.StringIO(emojize(text(*message_content, sep='\n'))) for week in grid: for i in week: if i[1].date() == datetime.now().date(): if 'white' in i[0] or 'black' in i[0]: i[0] = i[0].replace('circle', 'large_square') else: i[0] = i[0].replace('circle', 'square') grid = [[i[0] for i in week] for week in grid] await message.answer_document( file, caption=emojize( text(text( f'Отчет о проделанной работе с {start_dt.date()} по {end_dt.date()}' ), text(''), text('Пн Вт Ср Чт Пт Сб Вс'), *[text(*week, sep='') for week in grid], sep='\n')))
async def not_command(message: types.Message): return not message.get_command()
async def factorial_msg(message: types.Message): log(message) args = message.get_args() print(args) print(message.get_command()) await bot.send_message(message['chat']['id'], args)
async def cmd_fast_dev_run(message: types.Message, state: FSMContext): async with state.proxy() as data: data["fast_dev_run"] = message.get_command().lower( ) == "/fast_dev_run_true"