def test_effective_message_type(self): test_message = Message(message_id=1, from_user=None, date=None, chat=None) test_message.text = 'Test' assert helpers.effective_message_type(test_message) == 'text' test_message.text = None test_message.sticker = Sticker('sticker_id', 50, 50) assert helpers.effective_message_type(test_message) == 'sticker' test_message.sticker = None test_message.new_chat_members = [User(55, 'new_user', False)] assert helpers.effective_message_type( test_message) == 'new_chat_members' test_update = Update(1) test_message.text = 'Test' test_update.message = test_message assert helpers.effective_message_type(test_update) == 'text' empty_update = Update(2) assert helpers.effective_message_type(empty_update) is None
def process_message(update, context): """Process every new update.""" # pp = pprint.PrettyPrinter(indent=4) # pp.pprint(update.to_dict()) group_id = update.effective_chat.id user_id = update.effective_user.id user_name = get_name(update) msg_type = effective_message_type(update) text = update.effective_message.text if text: msg_length = len(text.split()) else: msg_length = 0 timestamp = update.effective_message.date if DEBUG: debug_msg = ("DEBUG: ON\n\n" f"Group ID: {group_id}\n" f"Type:{msg_type}\n" f"Name:{user_name}\n" f"ID:{user_id}\n" f"Length:{msg_length}\n" f"Date:{timestamp}\n") context.bot.send_message(chat_id=update.effective_chat.id, text=debug_msg) try: db_add_message(group_id, hash_uid(user_id), msg_type, msg_length, timestamp) except ValueError as err: print(f"An error has occurred: {err}\nTrying to add new user.") add_user(hash_uid(user_id), user_name)
def check_update(self, update): message = update.effective_message message_type = effective_message_type(message) if message_type is not None: if message_type == 'text': logger.info(f"{message.chat_id} - User: \"%s\"", message.text) else: logger.info(f"{message.chat_id} - User: %s", message_type) return False
def check_update(self, update: object) -> tp.Optional[tp.Union[bool, object]]: if isinstance(update, Update) and update.effective_message: message = update.effective_message message_type = effective_message_type(message) if message_type is not None: if message_type == 'text': logger.info(f"{message.chat_id} - User: \"%s\"", message.text) else: logger.info(f"{message.chat_id} - User: %s", message_type) return False return None
def test_effective_message_type(self): def build_test_message(**kwargs): config = dict( message_id=1, from_user=None, date=None, chat=None, ) config.update(**kwargs) return Message(**config) test_message = build_test_message(text='Test') assert helpers.effective_message_type(test_message) == 'text' test_message.text = None test_message = build_test_message(sticker=Sticker('sticker_id', 'unique_id', 50, 50, False)) assert helpers.effective_message_type(test_message) == 'sticker' test_message.sticker = None test_message = build_test_message(new_chat_members=[User(55, 'new_user', False)]) assert helpers.effective_message_type(test_message) == 'new_chat_members' test_message = build_test_message(left_chat_member=[User(55, 'new_user', False)]) assert helpers.effective_message_type(test_message) == 'left_chat_member' test_update = Update(1) test_message = build_test_message(text='Test') test_update.message = test_message assert helpers.effective_message_type(test_update) == 'text' empty_update = Update(2) assert helpers.effective_message_type(empty_update) is None
def test_effective_message_type(self): test_message = Message(message_id=1, from_user=None, date=None, chat=None) test_message.text = 'Test' assert helpers.effective_message_type(test_message) == 'text' test_message.text = None test_message.sticker = Sticker('sticker_id', 50, 50) assert helpers.effective_message_type(test_message) == 'sticker' test_message.sticker = None test_message.new_chat_members = [User(55, 'new_user', False)] assert helpers.effective_message_type(test_message) == 'new_chat_members' test_update = Update(1) test_message.text = 'Test' test_update.message = test_message assert helpers.effective_message_type(test_update) == 'text' empty_update = Update(2) assert helpers.effective_message_type(empty_update) is None
def new_post(update: Update, context: CallbackContext): message = update.effective_message if message.media_group_id: media_type = effective_message_type(message) media_id = message.photo[-1].file_id if message.photo else message.effective_attachment.file_id msg_dict = {"media_type": media_type, "media_id": media_id, "caption": message.caption_html, "post_id": message.message_id} jobs = context.job_queue.get_jobs_by_name(str(message.media_group_id)) if jobs: jobs[0].context.append(msg_dict) else: context.job_queue.run_once(callback=media_group_sender, when=2, context=[msg_dict], name=str(message.media_group_id)) return msg = message.copy(chat_id=GROUP_ID) context.bot.pin_chat_message(chat_id=GROUP_ID, message_id=msg.message_id) context.bot_data["messages"][message.message_id] = msg.message_id
def relevant_type(cls, entity: Union[Update, Message]) -> Optional[str]: """ Extracts the type of the message, if it is relevant for the AkaNamen Bot in terms of :attr:`All_TYPES`. If it's not relevant, the output will be :obj:`None`. Note: In contrast to :meth:`telegram.utils.helpers.effective_message_type` , only updates with ``update.message`` are considered. Args: entity: A :class:`telegram.Update` or :class:`telegram.Message` """ if isinstance(entity, Update) and not entity.message: return None type_ = effective_message_type(entity) if type_ in cls.ALL_TYPES: return type_ return None
def wrapped(update, context, *args, **kwargs): if effective_message_type(update) not in MESSAGE_TYPES: return func return func(update, context, *args, **kwargs)
def deforward(bot, msg, lang): logger = Logger.logger chat_id = msg.chat_id message_id = msg.message_id logger.msg( { "channel_id": chat_id, "msg_id": message_id, "action": "messaage deforward" }, tag="channel", log_level=80) # Generate forward info has_msg_link = False if msg.forward_from: # Check username existence if msg.forward_from.username: forward_info = helper_global.value( 'fwd_source', 'Forwarded from:', lang=lang) + '@%s' % msg.forward_from.username else: forward_info = helper_global.value( 'fwd_source', 'Forwarded from:', lang=lang) + '<a href="tg://user?id=%d">%s</a>' % ( msg.forward_from.id, msg.forward_from.first_name + " " + avoidNone(msg.forward_from.last_name)) elif msg.forward_from_chat: # Check channel public/private if msg.forward_from_chat.username: forward_info = helper_global.value( 'fwd_source', 'Forwarded from:', lang=lang ) + 'https://t.me/%s/%s' % (msg.forward_from_chat.username, msg.forward_from_message_id) has_msg_link = True else: forward_info = helper_global.value( 'fwd_source', 'Forwarded from:', lang=lang) + msg.forward_from_chat.title message_type = effective_message_type(msg) new_msg = None # Ignore media group if msg.media_group_id: return msg # Handle by message type if message_type == 'text': has_content_link = False for entity in msg.entities: if entity.type == 'url' or entity.type == 'text_link': has_content_link = True break new_msg = bot.send_message( chat_id=chat_id, text=parse_entity(avoidNone(msg.text), msg.entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True, disable_web_page_preview=(not has_content_link and has_msg_link)).result() elif message_type == 'audio': new_msg = bot.send_audio(chat_id=chat_id, audio=msg.audio.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True).result() elif message_type == 'document': new_msg = bot.send_document( chat_id=chat_id, document=msg.document.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True).result() elif message_type == 'photo': new_msg = bot.send_photo(chat_id=chat_id, photo=msg.photo[-1].file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True).result() elif message_type == 'sticker': new_msg = bot.send_sticker(chat_id=chat_id, sticker=msg.sticker.file_id, disable_notification=True).result() elif message_type == 'video': new_msg = bot.send_video(chat_id=chat_id, video=msg.video.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True).result() elif message_type == 'voice': new_msg = bot.send_voice(chat_id=chat_id, voice=msg.voice.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True).result() if new_msg: bot.delete_message(chat_id=chat_id, message_id=message_id) return new_msg return msg
def handle(update): msg_type = effective_message_type(update) answer = answer_of(msg_type) answer(update)
def listimages(update, context): chat_id = update.effective_message.chat_id user_id = update.message.from_user.id message_types = ['photo', 'video'] upload_date = update.effective_message.date caption = update.message.caption username = update.effective_message.from_user.first_name message_types = [ 'audio', 'game', 'document', 'photo', 'sticker', 'video/mp4', 'video', 'voice' ] mt = helpers.effective_message_type(update.message) if mt in message_types: print("MESSAGE TYPE >>>>>: " + str(mt)) media = [] userId = str(user_id) date = str(upload_date) document = "" cap = str(caption) m = update.message if m.video: file_id = m.video.file_id document = "video/mp4" elif m.document: if m.document.mime_type == 'video/mp4': file_id = m.document.file_id document = "document" if document in message_types: #file_id = update.message.video.file_id current_time = datetime.datetime.utcnow() m = update.message if document == 'video/mp4': file_id = m.video.file_id elif document == 'document': file_id = m.document.file_id print("FILE-ID >>>>> " + str(file_id)) text = update.effective_message.caption userId = str(user_id) date = str(upload_date) vidId = str(file_id) cap = str(text) video_owner = str(username) randomNum = common.randStr(N=10) video_code = str(userId + randomNum) image_type = str(document) userId = str(user_id) date = str(upload_date) imgId = str(file_id) cap = str(caption) cursor = db.images.find({}) for img in cursor: if img['ImageCode'] == "p1": image_code = "p2" pass elif img['ImageCode'] == "p2": image_code = "p3" pass elif img['ImageCode'] == "p3": image_code = "p4" pass elif img['ImageCode'] == "p4": image_code = "p1" pass elif img['ImageCode'] == "": image_code = "p1" if db.images.count() == 0: image_code = "p1" document = "photo" video_item = { "UserId": user_id, "ImageId": imgId, "FileType": image_type, "ImageText": cap, "ImageCode": image_code, "ImageDate": date } db.images.insert_one(video_item) video_details = emojize(" תאריך העלאה: " + str(upload_date) + "\n" + "על ידי: " + "@" + str(username) + "\n" + "קוד: " + str(video_code) + "\n----------------\n") video_details += cap if document == 'video/mp4': context.bot.send_video(chat_id, video=file_id, caption=video_details, parse_mode='HTML') user_msg = "הסרטון עודכן בהצלחה!" update.message.reply_text(user_msg) elif document == 'document': context.bot.send_document(chat_id, document=file_id, caption=video_details, parse_mode='HTML') user_msg = "הסרטון עודכן בהצלחה!" update.message.reply_text(user_msg) pass else: context.bot.send_message(chat_id, text=" משהו קרה והקובץ לא נשמר, נסו שנית.") pass if caption == "logo": res = db.logo.delete_many({}) update.message.reply_text(" תמונת לוגו התקבלה!") file_id = update.message.photo[0].file_id current_time = datetime.datetime.utcnow() context.bot.send_message(chat_id, str(upload_date)) context.bot.send_message(chat_id, file_id) context.bot.send_photo(chat_id, file_id) context.bot.send_message(chat_id, str(caption)) cursor = db.images.find({}) for img in cursor: if img['ImageCode'] == "logo": res = db.logo.delete_many({}) pass elif db.images.count() == 0: image_code = "logo" image_code = "logo" image_type = str(document) userId = str(user_id) date = str(upload_date) imgId = str(file_id) cap = str(caption) imageItem = { "UserId": user_id, "ImageId": imgId, "ImageText": cap, "FileType": image_type, "ImageCode": image_code, "ImageDate": date } db.logo.insert_one(imageItem) else: file_id = update.message.photo[0].file_id current_time = datetime.datetime.utcnow() context.bot.send_message(chat_id, str(upload_date)) context.bot.send_message(chat_id, file_id) context.bot.send_photo(chat_id, file_id) context.bot.send_message(chat_id, str(caption)) document = "" cursor = db.images.find({}) for img in cursor: if img['ImageCode'] == "p1": image_code = "p2" document = "photo" pass elif img['ImageCode'] == "p2": image_code = "p3" document = "photo" pass elif img['ImageCode'] == "p3": image_code = "p4" document = "photo" pass elif img['ImageCode'] == "p4": image_code = "p1" document = "photo" pass elif img['ImageCode'] == "": image_code = "p1" document = "photo" if db.images.count() == 0: image_code = "p1" document = "photo" m = update.message if m.video: file_id = m.video.file_id document = "video/mp4" elif m.document: if m.document.mime_type == 'video/mp4': file_id = m.document.file_id document = "document" image_type = str(document) userId = str(user_id) date = str(upload_date) imgId = str(file_id) cap = str(caption) imageItem = { "UserId": user_id, "ImageId": imgId, "FileType": image_type, "ImageText": cap, "ImageCode": image_code, "ImageDate": date } db.images.insert_one(imageItem)
def message_file_handler(update: Update, context: CallbackContext): message = update.message chat_type = update.effective_chat.type bot = context.bot if cli_args.debug and not check_admin(bot, message, analytics, ADMIN_USER_ID): return message_id = message.message_id chat_id = message.chat.id attachment = message.effective_attachment message_type = effective_message_type(message) if type(attachment) is list: if chat_type == Chat.PRIVATE: bot.send_message( chat_id, 'You need to send the image as a file to convert it to a sticker.', reply_to_message_id=message_id) return if not ensure_size_under_limit(attachment.file_size, MAX_FILESIZE_DOWNLOAD, update, context): return user = message.from_user input_file_id = attachment.file_id input_file_name = None if getattr(attachment, 'file_name', None): input_file_name = attachment.file_name elif getattr(attachment, 'title', None): input_file_name = attachment.title create_or_update_user(bot, user) analytics.track(AnalyticsType.MESSAGE, user) if chat_type == Chat.PRIVATE: bot.send_chat_action(chat_id, ChatAction.TYPING) input_file = bot.get_file(input_file_id) input_file_url = input_file.file_path probe = None try: probe = ffmpeg.probe(input_file_url) except: pass with io.BytesIO() as output_bytes: output_type = OutputType.NONE caption = None invalid_format = None if message_type == 'voice': output_type = OutputType.FILE mp3_bytes = convert(output_type, input_audio_url=input_file_url) output_bytes.write(mp3_bytes) output_bytes.name = 'voice.mp3' elif message_type == 'sticker': with io.BytesIO() as input_bytes: input_file.download(out=input_bytes) try: image = Image.open(input_bytes) with io.BytesIO() as image_bytes: image.save(image_bytes, format='PNG') output_bytes.write(image_bytes.getbuffer()) output_type = OutputType.PHOTO sticker = message['sticker'] emoji = sticker['emoji'] set_name = sticker['set_name'] caption = 'Sticker for the emoji "{}" from the set "{}"'.format( emoji, set_name) except Exception as error: logger.error('PIL error: {}'.format(error)) else: if probe: for stream in probe['streams']: codec_name = stream.get('codec_name') codec_type = stream.get('codec_type') if codec_name is not None and codec_type == VIDEO_CODED_TYPE: invalid_format = codec_name if codec_name == 'mp3': output_type = OutputType.AUDIO opus_bytes = convert(output_type, input_audio_url=input_file_url) output_bytes.write(opus_bytes) break elif codec_name == 'opus': input_file.download(out=output_bytes) output_type = OutputType.AUDIO break elif codec_name in VIDEO_CODEC_NAMES: output_type = OutputType.VIDEO mp4_bytes = convert(output_type, input_video_url=input_file_url) output_bytes.write(mp4_bytes) break else: continue if output_type == OutputType.NONE: with io.BytesIO() as input_bytes: input_file.download(out=input_bytes) try: images = convert_from_bytes(input_bytes.getbuffer()) image = images[0] with io.BytesIO() as image_bytes: image.save(image_bytes, format='PNG') output_bytes.write(image_bytes.getbuffer()) output_type = OutputType.PHOTO except Exception as error: logger.error('pdf2image error: {}'.format(error)) if output_type == OutputType.NONE: try: image = Image.open(input_bytes) with io.BytesIO() as image_bytes: image.save(image_bytes, format='WEBP') output_bytes.write(image_bytes.getbuffer()) output_type = OutputType.STICKER except Exception as error: logger.error('PIL error: {}'.format(error)) if output_type == OutputType.NONE: if chat_type == Chat.PRIVATE: if invalid_format is None: invalid_format = os.path.splitext(input_file_url)[1][1:] bot.send_message(chat_id, 'File type "{}" is not yet supported.'.format( invalid_format), reply_to_message_id=message_id) return output_bytes.seek(0) output_file_size = output_bytes.getbuffer().nbytes if caption is None and input_file_name is not None: caption = input_file_name[:MAX_CAPTION_LENGTH] if output_type == OutputType.AUDIO: if not ensure_size_under_limit( output_file_size, MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, ChatAction.UPLOAD_AUDIO) bot.send_voice(chat_id, output_bytes, caption=caption, reply_to_message_id=message_id) return elif output_type == OutputType.VIDEO: if not ensure_size_under_limit( output_file_size, MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, ChatAction.UPLOAD_VIDEO) send_video(bot, chat_id, message_id, output_bytes, attachment, caption, chat_type) return elif output_type == OutputType.PHOTO: if not ensure_size_under_limit( output_file_size, MAX_PHOTO_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_photo(chat_id, output_bytes, caption=caption, reply_to_message_id=message_id) return elif output_type == OutputType.STICKER: bot.send_sticker(chat_id, output_bytes, reply_to_message_id=message_id) return elif output_type == OutputType.FILE: if not ensure_size_under_limit( output_file_size, MAX_FILESIZE_UPLOAD, update, context, file_reference_text='Converted file'): return bot.send_chat_action(chat_id, ChatAction.UPLOAD_DOCUMENT) bot.send_document(chat_id, output_bytes, reply_to_message_id=message_id) return if chat_type == Chat.PRIVATE: bot.send_message(chat_id, 'File type is not yet supported.', reply_to_message_id=message_id)