async def send_chat_action( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description="Unique identifier for the target chat or username of the target channel (in the format @channelusername)", regex=r"@[a-zA-Z][a-zA-Z0-9_]{2,}"), action: ChatAction = Query(..., description='Type of action to broadcast. Choose one, depending on what the user is about to receive: "typing" for text messages, "upload_photo" for photos, "record_video" or "upload_video" for "videos", "record_audio" or "upload_audio" for audio files, "upload_document" for general files, "find_location" for location data, "record_video_note" or "upload_video_note" for video notes. Additionally added by this API implementation are "play_game", "choose_contact" and "cancel".'), ): from ....main import _get_bot bot = await _get_bot(token) try: entity = await get_entity(bot, chat_id) # end try except ValueError: raise HTTPException(404, detail="chat not found?") # end try client = bot action: str = actions_api_to_telethon_mapping[action] # noinspection PyProtectedMember action: TypeSendMessageAction = _ChatAction._str_mapping[action.lower()] await client( request=SetTypingRequest( peer=entity, action=action, ) ) return r_success()
async def top_images(event: telethon.events.NewMessage.Event): match = event.pattern_match logger.info("New query: " + match.group(0)) await event.client(SetTypingRequest(event.input_chat, SendMessageUploadPhotoAction(0))) results = (await pixiv.get_pixiv_results(int(match.group(2) or 0) * MAX_GROUPED_MEDIA, # user gives page num nsfw=bool(match.group(1))))[:MAX_GROUPED_MEDIA] try: images = await event.client( [UploadMediaRequest(event.input_chat, InputMediaPhotoExternal(result['url'], 86000)) for result in results] ) except telethon.errors.MultiError as e: logger.warning("UploadMedia returned one or more errors") logging.debug('error: %s', e, exc_info=True) images = filter(None, e.results) if not images: logger.exception("All UploadMedia requests failed") return images = [InputSingleMedia(InputMediaPhoto(InputPhoto(img.photo.id, img.photo.access_hash, b'')), '') for img in images] try: await event.client(SendMultiMediaRequest(event.input_chat, images)) except (telethon.errors.UserIsBlockedError, telethon.errors.RPCError): # TODO: add other relevant errors logger.exception("Failed to send multimedia")
async def send_video_note(event): msg = event.message try: filename = msg.media.document.attributes[1].file_name except Exception: filename = 'video_noname.mp4' chat = await event.get_chat() replied_msg_id = None if event.reply_to_msg_id: replied_msg_id = event.reply_to_msg_id await client(SetTypingRequest(chat, SendMessageRecordRoundAction())) if not os.path.exists(filename): filename = await client.download_media(event.message, file=filename) await asyncio.sleep(0.5) await event.delete() document_attribute = [ DocumentAttributeVideo(duration=0, w=260, h=260, round_message=True, supports_streaming=True), DocumentAttributeFilename(filename) ] await client.send_file(chat, filename, caption='', file_name=str(filename), allow_cache=False, part_size_kb=512, thumb=None, attributes=document_attribute, reply_to=replied_msg_id) return
def set_typing(self, user: '******', typing: bool = True, action: type = SendMessageTypingAction) -> Awaitable[bool]: return user.client( SetTypingRequest( self.peer, action() if typing else SendMessageCancelAction()))
async def send_python_zen(event): with io.open('zen.txt', 'r', encoding='utf-8') as zen_fp: text = ''.join(zen_fp.readlines()) await asyncio.sleep(0.5) await client( SetTypingRequest(event.input_chat, SendMessageTypingAction())) await asyncio.sleep(2.5) await event.reply(text, parse_mode='Markdown')
def update_handler(event): if isinstance(event.message.to_id, PeerChannel): group_id = event.message.to_id.channel_id elif isinstance(event.message.to_id, PeerChat): group_id = event.message.to_id.chat_id if event.message.from_id == quizarium_bot.user_id: text = event.message.message if 'QUESTION' in text or 'ВОПРОС' in text: index = 1 if 'Round' in text or 'Раунд' in text: index = 2 questions[group_id] = text.split('\n')[index] print(questions[group_id]) if questions[group_id] in data: time.sleep(random.randrange(0, 3)) client( SetTypingRequest(event.message.to_id, SendMessageTypingAction())) time.sleep(random.randrange(2, 9)) client.send_message(event.message.to_id, data[questions[group_id]]) client( SetTypingRequest(event.message.to_id, SendMessageCancelAction())) print('A:', data[questions[group_id]]) elif not questions[group_id] in data: for regex in solutions: result = re.search(regex, text.split('\n')[0]) if result and questions[group_id]: data[questions[group_id]] = result.group(1) with open('db.json', 'w') as db: json.dump(data, db) print(len(data)) break
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) actions = {} actions["ra"] = SendMessageRecordAudioAction() actions["rv"] = SendMessageRecordVideoAction() actions["ua"] = SendMessageUploadAudioAction(0) actions["up"] = SendMessageUploadPhotoAction(0) actions["uv"] = SendMessageUploadVideoAction(0) actions["rr"] = SendMessageRecordRoundAction() actions["mt"] = SendMessageTypingAction() actions["ud"] = SendMessageUploadDocumentAction(0) action = actions["mt"] if input_str: action = actions[input_str] await borg(SetTypingRequest(event.chat_id, action)) await event.delete()