示例#1
0
    def test_equality(self, sticker):
        a = Sticker(
            sticker.file_id,
            sticker.file_unique_id,
            self.width,
            self.height,
            self.is_animated,
            self.is_video,
        )
        b = Sticker(
            '', sticker.file_unique_id, self.width, self.height, self.is_animated, self.is_video
        )
        c = Sticker(sticker.file_id, sticker.file_unique_id, 0, 0, False, True)
        d = Sticker('', '', self.width, self.height, self.is_animated, self.is_video)
        e = PhotoSize(
            sticker.file_id, sticker.file_unique_id, self.width, self.height, self.is_animated
        )

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
示例#2
0
def get_sticker(bot, update):
    user_emoji = update.message.text
    print(user_emoji)
    logging.info('Пользователь @{} ({}) ввел: {} '.format(
        update.message.chat.username, update.message.chat.first_name,
        user_emoji))
    if "😕" in user_emoji:
        update.message.reply_sticker(
            Sticker(file_id='CAADAgADOAADX8p-CzLiVfbJsCagAg',
                    width=100,
                    height=100))
    elif "😂" in user_emoji:
        update.message.reply_sticker(
            Sticker(file_id='CAADAgADwgYAAvoLtghYZz5i3gqMNgI',
                    width=100,
                    height=100))
    elif "😊" in user_emoji:
        update.message.reply_sticker(
            Sticker(file_id='CAADAgAD2gYAAvoLtgggBeUJREiG7QI',
                    width=100,
                    height=100))
    elif "😏" in user_emoji:
        update.message.reply_sticker(
            Sticker(file_id='CAADAgADXgAD1jUSAAHMmC9kAAFQGeUC',
                    width=100,
                    height=100))
    else:
        update.message.reply_text(
            "На такой Эмодзи стикера у меня нет, извини =(")
示例#3
0
 def _get_sticker(self, data=None):
     import uuid
     from random import randint
     if data:
         data['width'] = randint(20, 200)
         data['height'] = randint(20, 200)
         return Sticker(**data)
     return Sticker(str(uuid.uuid4()), randint(20, 200), randint(20, 200))
示例#4
0
def add_card(game, card, results, can_play):
    """Add an option that represents a card"""

    if can_play:
        results.append(
            Sticker(str(card), sticker_file_id=c.STICKERS[str(card)]))
    else:
        results.append(
            Sticker(str(uuid4()),
                    sticker_file_id=c.STICKERS_GREY[str(card)],
                    input_message_content=game_info(game)))
示例#5
0
def add_call_bluff(results, game):
    """Add option to call a bluff"""
    results.append(
        Sticker("call_bluff",
                sticker_file_id=c.STICKERS['option_bluff'],
                input_message_content=InputTextMessageContent(
                    __("I'm calling your bluff!", multi=game.translate))))
    def test_de_json(self, bot, sticker):
        json_dict = {
            "file_id": self.sticker_file_id,
            "file_unique_id": self.sticker_file_unique_id,
            "width": self.width,
            "height": self.height,
            "is_animated": self.is_animated,
            "is_video": self.is_video,
            "thumb": sticker.thumb.to_dict(),
            "emoji": self.emoji,
            "file_size": self.file_size,
            "premium_animation": self.premium_animation.to_dict(),
        }
        json_sticker = Sticker.de_json(json_dict, bot)

        assert json_sticker.file_id == self.sticker_file_id
        assert json_sticker.file_unique_id == self.sticker_file_unique_id
        assert json_sticker.width == self.width
        assert json_sticker.height == self.height
        assert json_sticker.is_animated == self.is_animated
        assert json_sticker.is_video == self.is_video
        assert json_sticker.emoji == self.emoji
        assert json_sticker.file_size == self.file_size
        assert json_sticker.thumb == sticker.thumb
        assert json_sticker.premium_animation == self.premium_animation
示例#7
0
def add_gameinfo(game, results):
    """Add option to show game info"""

    results.append(
        Sticker("gameinfo",
                sticker_file_id=c.STICKERS['option_info'],
                input_message_content=game_info(game)))
示例#8
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'))
        data['entities'] = MessageEntity.de_list(data.get('entities'))
        data['forward_from'] = User.de_json(data.get('forward_from'))
        data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = Audio.de_json(data.get('audio'))
        data['document'] = Document.de_json(data.get('document'))
        data['photo'] = PhotoSize.de_list(data.get('photo'))
        data['sticker'] = Sticker.de_json(data.get('sticker'))
        data['video'] = Video.de_json(data.get('video'))
        data['voice'] = Voice.de_json(data.get('voice'))
        data['contact'] = Contact.de_json(data.get('contact'))
        data['location'] = Location.de_json(data.get('location'))
        data['venue'] = Venue.de_json(data.get('venue'))
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'))
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'))
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'))
        data['pinned_message'] = Message.de_json(data.get('pinned_message'))

        return Message(**data)
示例#9
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Message, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['date'] = from_timestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'), bot)
        data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
        data['forward_from'] = User.de_json(data.get('forward_from'), bot)
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
        data['forward_date'] = from_timestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
        data['edit_date'] = from_timestamp(data.get('edit_date'))
        data['audio'] = Audio.de_json(data.get('audio'), bot)
        data['document'] = Document.de_json(data.get('document'), bot)
        data['game'] = Game.de_json(data.get('game'), bot)
        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
        data['video'] = Video.de_json(data.get('video'), bot)
        data['voice'] = Voice.de_json(data.get('voice'), bot)
        data['video_note'] = VideoNote.de_json(data.get('video_note'), bot)
        data['contact'] = Contact.de_json(data.get('contact'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)
        data['venue'] = Venue.de_json(data.get('venue'), bot)
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'), bot)
        data['new_chat_members'] = User.de_list(data.get('new_chat_members'), bot)
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
        data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
        data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)

        return cls(bot=bot, **data)
示例#10
0
def add_card(game, card, results, can_play):
    """Add an option that represents a card"""

    if can_play:
        results.append(
            Sticker(str(card),
                    sticker_file_id=c.STICKERS[str(card)],
                    input_message_content=InputTextMessageContent(
                        "Card Played: {card}".format(card=repr(card).replace(
                            'Draw Four', '+4').replace('Draw', '+2').replace(
                                'Colorchooser', 'Color Chooser')))))
    else:
        results.append(
            Sticker(str(uuid4()),
                    sticker_file_id=c.STICKERS_GREY[str(card)],
                    input_message_content=game_info(game)))
示例#11
0
    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
示例#12
0
    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
示例#13
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'))
        data['entities'] = MessageEntity.de_list(data.get('entities'))
        data['forward_from'] = User.de_json(data.get('forward_from'))
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'))
        data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(
            data.get('reply_to_message'))
        data['audio'] = Audio.de_json(data.get('audio'))
        data['document'] = Document.de_json(data.get('document'))
        data['photo'] = PhotoSize.de_list(data.get('photo'))
        data['sticker'] = Sticker.de_json(data.get('sticker'))
        data['video'] = Video.de_json(data.get('video'))
        data['voice'] = Voice.de_json(data.get('voice'))
        data['contact'] = Contact.de_json(data.get('contact'))
        data['location'] = Location.de_json(data.get('location'))
        data['venue'] = Venue.de_json(data.get('venue'))
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'))
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'))
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'))
        data['pinned_message'] = Message.de_json(data.get('pinned_message'))

        return Message(**data)
def time_monitor(bot, job):
    now = time.localtime()
    if now.tm_min == 0 and now.tm_hour in TIME_STICKERS:
        bot.send_sticker(chat_id=config.GROUP_ID,
                         sticker=Sticker(file_id=TIME_STICKERS[now.tm_hour],
                                         width=376,
                                         height=376))
示例#15
0
def add_pass(results, game):
    """Add option to pass"""
    results.append(
        Sticker("pass",
                sticker_file_id=c.STICKERS['option_pass'],
                input_message_content=InputTextMessageContent(
                    __('Pass', multi=game.translate))))
示例#16
0
    def test_equality(self, sticker):
        a = Sticker(sticker.file_id, self.width, self.height)
        b = Sticker(sticker.file_id, self.width, self.height)
        c = Sticker(sticker.file_id, 0, 0)
        d = Sticker('', self.width, self.height)
        e = PhotoSize(sticker.file_id, self.width, self.height)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
示例#17
0
    def download_stickers_to_file(self, bot: Bot, sticker: Sticker, file_object: BufferedWriter):
        """Download Sticker as images to file_object

        Args:
            bot (:obj:`telegram.bot.Bot`): Telegram Api Bot Object.
            sticker (:obj:`telegram.sticker.Sticker`): A Sticker object
            file_object (:obj:`io.BufferedWriter`): File like object
        """
        sticker = bot.get_file(sticker.file_id)
        sticker.download(out=file_object)

        if getattr(file_object, 'save', None):
            file_object.save()
        else:
            save_file(file_object)

        image = Image.open(file_object.name)
        image.save(file_object, format='png')

        return file_object
示例#18
0
文件: bot.py 项目: fepe55/SzerdaBot
def show_stickers_de_hoy(update, context):
    stickers_de_hoy = _get_stickers_de_hoy(update.effective_chat.id)
    for sticker in stickers_de_hoy:
        # sticker_to_send = Sticker(
        #     file_id=sticker['file_id'],
        #     file_unique_id=sticker['file_unique_id'],
        #     width=sticker['width'], height=sticker['height'],
        #     is_animated=sticker['is_animated'],
        # )
        sticker_to_send = Sticker(**sticker)
        context.bot.send_sticker(update.message.chat_id, sticker_to_send)
示例#19
0
def add_draw(player, results):
    """Add option to draw"""
    n = player.game.draw_counter or 1

    results.append(
        Sticker("draw",
                sticker_file_id=c.STICKERS['option_draw'],
                input_message_content=InputTextMessageContent(
                    __('Drawing {number} card',
                       'Drawing {number} cards',
                       n,
                       multi=player.game.translate).format(number=n))))
    def _get_sticker(self, data=None):
        import uuid
        from random import randint

        if data is None:
            data = {}
        data["file_unique_id"] = data["file_id"] = str(uuid.uuid4())
        if "width" not in data:
            data["width"] = randint(20, 200)
            data["height"] = randint(20, 200)
        if "is_animated" not in data:
            data["is_animated"] = False
        return Sticker(**data)
def quiet_handler(update: Update, context: CallbackContext):
    """
    Успокоить пользователя.
    """
    # user_id = update.effective_user.id
    # text = update.effective_message.text
    #
    # if user_id == 357912833:
    #     update.effective_message.bot.send_message(chat_id=429623673, text=text)

    if context.chat_data['flag_upshut'] < 2:
        context.chat_data['flag_upshut'] += 1
    elif context.chat_data['flag_for_del_msg'] < 1:
        update.effective_message.reply_sticker(
            sticker=Sticker(                    # Стикер "Приведение (Чшшш)"
                file_id='CAACAgIAAxkBAAIEa17LHgIb22R-EgkdalwzI327QeVAAAK-AAMw1J0RtKcIkYQmscoZBA',
                file_unique_id='AgADvgADMNSdEQ',
                width=512,
                height=512,
                is_animated=True
            )
        )
        context.chat_data['flag_for_del_msg'] += 1
        context.chat_data['flag_upshut'] = 0
    elif context.chat_data['flag_for_del_msg'] == 1:
        update.effective_message.reply_sticker(
            sticker=Sticker(                    # Стикер "Приведение (Лопает)"
                file_id='CAACAgIAAxkBAAIHbl7Zja1kbyzuuk-pggdbRiFPRHFiAAK8AAMw1J0Rd5meEIvSc6IaBA',
                file_unique_id='AgADvAADMNSdEQ',
                width=512,
                height=512,
                is_animated=True
            )
        )
        context.chat_data['flag_for_del_msg'] += 1
        context.chat_data['flag_upshut'] = 3
    else:
        update.effective_message.delete()
示例#22
0
    def test_sticker(self):
        sticker = Sticker("idyouknow", 30, 30)
        u = self.mg.get_message(sticker=sticker)
        self.assertEqual(sticker.file_id, u.message.sticker.file_id)

        cap = "sticker file"
        u = self.mg.get_message(sticker=sticker, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(sticker=True)
        self.assertIsInstance(u.message.sticker, Sticker)

        with self.assertRaisesRegexp(BadMessageException,
                                     r"telegram\.Sticker"):
            self.mg.get_message(sticker="sticker")
示例#23
0
    def test_de_json(self, bot, sticker):
        json_dict = {
            'file_id': sticker.file_id,
            'width': self.width,
            'height': self.height,
            'thumb': sticker.thumb.to_dict(),
            'emoji': self.emoji,
            'file_size': self.file_size
        }
        json_sticker = Sticker.de_json(json_dict, bot)

        assert json_sticker.file_id == sticker.file_id
        assert json_sticker.width == self.width
        assert json_sticker.height == self.height
        assert json_sticker.emoji == self.emoji
        assert json_sticker.file_size == self.file_size
示例#24
0
    def de_json(data):
        """
        Args:
            data (str):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        if 'first_name' in data.get('chat', ''):
            data['chat'] = User.de_json(data.get('chat'))
        elif 'title' in data.get('chat', ''):
            data['chat'] = GroupChat.de_json(data.get('chat'))
        data['forward_from'] = \
            User.de_json(data.get('forward_from'))
        data['forward_date'] = \
            Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = \
            Audio.de_json(data.get('audio'))
        data['document'] = \
            Document.de_json(data.get('document'))
        data['photo'] = \
            PhotoSize.de_list(data.get('photo'))
        data['sticker'] = \
            Sticker.de_json(data.get('sticker'))
        data['video'] = \
            Video.de_json(data.get('video'))
        data['voice'] = \
            Voice.de_json(data.get('voice'))
        data['contact'] = \
            Contact.de_json(data.get('contact'))
        data['location'] = \
            Location.de_json(data.get('location'))
        data['new_chat_participant'] = \
            User.de_json(data.get('new_chat_participant'))
        data['left_chat_participant'] = \
            User.de_json(data.get('left_chat_participant'))
        data['new_chat_photo'] = \
            PhotoSize.de_list(data.get('new_chat_photo'))

        return Message(**data)
示例#25
0
    def de_json(data):
        """
        Args:
            data (str):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        if 'first_name' in data.get('chat', ''):
            data['chat'] = User.de_json(data.get('chat'))
        elif 'title' in data.get('chat', ''):
            data['chat'] = GroupChat.de_json(data.get('chat'))
        data['forward_from'] = \
            User.de_json(data.get('forward_from'))
        data['forward_date'] = \
            Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = \
            Audio.de_json(data.get('audio'))
        data['document'] = \
            Document.de_json(data.get('document'))
        data['photo'] = \
            PhotoSize.de_list(data.get('photo'))
        data['sticker'] = \
            Sticker.de_json(data.get('sticker'))
        data['video'] = \
            Video.de_json(data.get('video'))
        data['voice'] = \
            Voice.de_json(data.get('voice'))
        data['contact'] = \
            Contact.de_json(data.get('contact'))
        data['location'] = \
            Location.de_json(data.get('location'))
        data['new_chat_participant'] = \
            User.de_json(data.get('new_chat_participant'))
        data['left_chat_participant'] = \
            User.de_json(data.get('left_chat_participant'))
        data['new_chat_photo'] = \
            PhotoSize.de_list(data.get('new_chat_photo'))

        return Message(**data)
    def test_de_json(self, bot, sticker):
        json_dict = {
            'file_id': 'not a file id',
            'width': self.width,
            'height': self.height,
            'thumb': sticker.thumb.to_dict(),
            'emoji': self.emoji,
            'file_size': self.file_size
        }
        json_sticker = Sticker.de_json(json_dict, bot)

        assert json_sticker.file_id == 'not a file id'
        assert json_sticker.width == self.width
        assert json_sticker.height == self.height
        assert json_sticker.emoji == self.emoji
        assert json_sticker.file_size == self.file_size
        assert json_sticker.thumb == sticker.thumb
示例#27
0
文件: bot.py 项目: fepe55/SzerdaBot
def _easter_egg(update, context):
    # PUG_RECEIVED_FILE_ID = 'CAACAgIAAxkBAAICQF8SWXrp9vpWQiv4HjjuzwdOv51CAAJ5AwAC7sShChuQueMKcwYNGgQ'  # noqa
    PUG_RECEIVED_UNIQUE_ID = 'AgADeQMAAu7EoQo'

    # PUG_TO_SEND
    file_id = 'CAACAgIAAxkBAAICP18SWNY-NLC_96rFAemzZ0s2nLCVAAIEAQAC9HsZAAGAEeRAK8ac-xoE'  # noqa
    file_unique_id = 'AgADBAEAAvR7GQAB'
    width = 440
    height = 512
    STICKER_TO_SEND = Sticker(
        file_id=file_id,
        file_unique_id=file_unique_id,
        width=width,
        height=height,
        is_animated=False,
    )

    if update.message.sticker.file_unique_id == PUG_RECEIVED_UNIQUE_ID:
        context.bot.send_sticker(update.message.chat_id, STICKER_TO_SEND)
示例#28
0
    def test_equality(self, photo):
        a = PhotoSize(photo.file_id, photo.file_unique_id, self.width, self.height)
        b = PhotoSize('', photo.file_unique_id, self.width, self.height)
        c = PhotoSize(photo.file_id, photo.file_unique_id, 0, 0)
        d = PhotoSize('', '', self.width, self.height)
        e = Sticker(photo.file_id, photo.file_unique_id, self.width, self.height, False)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
示例#29
0
    def test_de_json(self, bot, sticker):
        json_dict = {
            'file_id': self.sticker_file_id,
            'file_unique_id': self.sticker_file_unique_id,
            'width': self.width,
            'height': self.height,
            'is_animated': self.is_animated,
            'is_video': self.is_video,
            'thumb': sticker.thumb.to_dict(),
            'emoji': self.emoji,
            'file_size': self.file_size,
        }
        json_sticker = Sticker.de_json(json_dict, bot)

        assert json_sticker.file_id == self.sticker_file_id
        assert json_sticker.file_unique_id == self.sticker_file_unique_id
        assert json_sticker.width == self.width
        assert json_sticker.height == self.height
        assert json_sticker.is_animated == self.is_animated
        assert json_sticker.is_video == self.is_video
        assert json_sticker.emoji == self.emoji
        assert json_sticker.file_size == self.file_size
        assert json_sticker.thumb == sticker.thumb
示例#30
0
def Verification(bot, update):
        text = update.message.text
        if not validate.login[2]:
                if not validate.login[0] and not validate.login[1]:
                        #Valida la lista y el correo mediante Expresiones Regulares(emailverification)
                        if not validate.login[0] and emailVerification(text):
                                validate.login[0] = True
                                validate.login[1] = True
                                credentials.email = text
                                bot.send_message(
                                        chat_id=update.message.chat_id,
                                        #setea el pasword ahora en text
                                        text='Introduce your password:'******'Email invalid!\nIntroduce your email address:'
                                )
                #Tras validar email, chequea la clave con inbox.authenticator
                elif validate.login[0] and validate.login[1]:
                        credentials.password = text
                        bot.send_message(chat_id=update.message.chat_id,text='Loading, please wait....')
                        auth = inbox.Authenticator(credentials.email,credentials.password)
                        #Si auth da ok: imprime el sticker de login correcto, y muestra el menu principal (INBOX, ENVIAR, LOGOUT)
                        if auth == 'ok':
                                validate.login[2] = True
                                keyboard = [[InlineKeyboardButton("Inbox", callback_data='4'),
                                InlineKeyboardButton("Send a email", callback_data='5'),InlineKeyboardButton("Logout", callback_data='7')]]
                                reply_markup = InlineKeyboardMarkup(keyboard)
                                newsticker = Sticker(file_id= 'CAADAgAD8wIAApzW5wrgLgRxhQ_BAgI', width= 512, height= 512)
                                bot.send_sticker(chat_id=update.message.chat_id, sticker= newsticker)
                                bot.send_message(chat_id=update.message.chat_id, text='Your login was successful')
                                update.message.reply_text('Select an option:',reply_markup=reply_markup)

                        else:
                        #Sino reinicia la lista de validacion y credenciales
                                validate.login[0] = False
                                validate.login[1] = False
                                credentials.email = ''
                                credentials.password = ''
                                newsticker = Sticker(file_id= 'CAADAgADCAMAApzW5wqTpbtQDP42agI', width= 512, height= 512)
                                bot.send_sticker(chat_id=update.message.chat_id, sticker= newsticker)
                                bot.send_message(chat_id=update.message.chat_id, text='Error, the force is not strong enough in you')
                                bot.send_message(chat_id=update.message.chat_id,text='Got midi-chlorians? Email or password incorrect!')
                                bot.send_message(chat_id=update.message.chat_id,text='Try again!')
                                bot.send_message(chat_id=update.message.chat_id,text='Introduce your email address:')
        elif validate.login[2]:
                contain = update.message.text.find(',') 
                emails = ''
                if contain != -1:
                        emails = update.message.text.split(',')
                else:
                       emails = update.message.text


                """ if validate.sendImail[0] and not validate.sendImail[1] and not emailVerification(update.message.text):
                        bot.send_message(
                                chat_id=update.message.chat_id,
                                text='Email invalid'
                        )
                        bot.send_message(
                                chat_id=update.message.chat_id,
                                text='From:'
                        ) 
                        Comentamos esto porque no hace falta poner el from de nuevo si ya iniciaste sesion con dicho correo
                        """
                
                if validate.sendImail[0] and validate.sendImail[1] and not validate.sendImail[2] and contain != -1:
                        validation = True
                        for i in range(0,len(emails)):
                                if not emailVerification(emails[i]):
                                        bot.send_message(
                                                chat_id=update.message.chat_id,
                                                text='Email invalid'
                                        )
                                        bot.send_message(
                                                chat_id=update.message.chat_id,
                                                text='To:'
                                        )
                                        validation = False
                                
                        if validation and validate.sendImail[0] and validate.sendImail[1] and not validate.sendImail[2] and not validate.sendImail[3] and not validate.sendImail[4]:
                                validate.sendImail[2] = True
                                data.To = update.message.text
                                bot.send_message(
                                        chat_id=update.message.chat_id,
                                        text='Subject:'
                                )
                                
                elif validate.sendImail[0] and validate.sendImail[1] and not validate.sendImail[2] and not emailVerification(update.message.text):
                        
                        bot.send_message(
                                chat_id=update.message.chat_id,
                                text='Email invalid'
                        )
                        bot.send_message(
                                chat_id=update.message.chat_id,
                                text='To:'
                        )
                else:
                        if validate.sendImail[0] and not validate.sendImail[1] and not validate.sendImail[2] and not validate.sendImail[3] and not validate.sendImail[4]:
                                validate.sendImail[1] = True
                                data.From = update.message.text
                                bot.send_message(
                                        chat_id=update.message.chat_id,
                                        text='To:'
                                )
                        elif validate.sendImail[0] and validate.sendImail[1] and not validate.sendImail[2] and not validate.sendImail[3] and not validate.sendImail[4]:
                                validate.sendImail[2] = True
                                data.To = emails
                                bot.send_message(
                                        chat_id=update.message.chat_id,
                                        text='Subject:'
                                )
                        elif validate.sendImail[0] and validate.sendImail[1] and validate.sendImail[2] and not validate.sendImail[3] and not validate.sendImail[4]:
                                validate.sendImail[3] = True
                                data.Subject = update.message.text
                                bot.send_message(
                                        chat_id=update.message.chat_id,
                                        text='Body:'
                                )
                        elif validate.sendImail[0] and validate.sendImail[1] and validate.sendImail[2] and validate.sendImail[3] and not validate.sendImail[4]:
                                data.Body = update.message.text
                                keyboard = [[InlineKeyboardButton("YES", callback_data='9'),InlineKeyboardButton("NO", callback_data='10')]]
                                reply_markup = InlineKeyboardMarkup(keyboard)
                                bot.send_message(chat_id=update.message.chat_id, text= 'Do you want to send any file ?',
                                        reply_markup=reply_markup)
示例#31
0
def button(bot, update):
        query = update.callback_query
        keyboard = [[InlineKeyboardButton("Start again", callback_data='3')]]
        reply_markup = InlineKeyboardMarkup(keyboard)
    
        if query.data == '0':
                #Query del menu principal
                index.min = 0
                index.max= 10
                validate.sendImail = [False,False,False,False,False]
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)

                keyboard = [[InlineKeyboardButton("Inbox", callback_data='4'),
                                InlineKeyboardButton("Send a email", callback_data='5'),InlineKeyboardButton("Logout", callback_data='7')]]
                reply_markup = InlineKeyboardMarkup(keyboard)
                bot.send_message(chat_id=query.message.chat_id,text='Select an option:',
                                reply_markup=reply_markup)
        #Qyery del boton login
        if query.data == '1':
                #bot.send_photo(chat_id=query.message.chat_id, photo=open('./src/stickers/notWorking.png', 'rb'),caption='Out of service now!',reply_markup=reply_markup)
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)

                bot.send_message(
                        chat_id=query.message.chat_id,
                        text='Introduce your email address:'
                )

        elif query.data == '3':
                #Query al reiniciar el bot (Start Again) 
                validate.login = [False,False,False]
                validate.sendImail = [False,False,False,False,False]
                credentials.email = ''
                credentials.password = ''
                hour = int(time.strftime("%H"))
                text = ''
                if hour >= 0 and hour <= 11:
                        text="Good Morning!"

                elif hour >= 12 and hour <= 18:
                        text="Good Afternoon!"

                elif hour >= 17 and hour <= 23:
                        text="Good Evening!"

                keyboard = [[InlineKeyboardButton("Login", callback_data='1'),InlineKeyboardButton("Close", callback_data='8')]]
                reply_markup = InlineKeyboardMarkup(keyboard)
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
                bot.send_message(chat_id=query.message.chat_id, text= text+'\n\n Select an option:',
                                reply_markup=reply_markup)

        elif query.data == '4':
                #Query del imbox para mostrar mas correos o ir al Query del menu principal
                keyboard = [[InlineKeyboardButton("Read more", callback_data='4'),InlineKeyboardButton("Main menu", callback_data='0')]]
                reply_markup = InlineKeyboardMarkup(keyboard)
                
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
                bot.send_message(chat_id=query.message.chat_id,text='Searching emails, please wait....')
                inboxlist = inbox.OpenInbox(index.min,index.max)
                index.min = index.min+10
                index.max= index.max+10
                #print(inboxlist)
                
                for info_email in inboxlist:
                         bot.send_message(chat_id=query.message.chat_id,text=info_email)

                bot.send_message(chat_id=query.message.chat_id,text='Select an option:',
                              reply_markup=reply_markup)
        elif query.data == '5':
                #Query de redactar un correo
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
                validate.sendImail[0] = True
                validate.sendImail[1] = True
                data.From = credentials.email
                bot.send_message(
                        chat_id=query.message.chat_id,
                        text='To:'
                )
        elif query.data == '6':
                #Query que manda el correo y muestra el menu principal de nuevo
                validate.sendImail = [False,False,False,False,False]
                keyboard = [[InlineKeyboardButton("Inbox", callback_data='4'),
                        InlineKeyboardButton("Send a email", callback_data='5'),
                        InlineKeyboardButton("Logout", callback_data='7')]]
                reply_markup = InlineKeyboardMarkup(keyboard)
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)  
                bot.send_message(chat_id=query.message.chat_id,text='Sending email, please wait....')
                result = ''
                if data.file_url == '' and data.file_name == '':
                        result = send.Send(credentials.email,credentials.password,data.From,data.To,data.Subject,data.Body)
                else:
                        result = sendattch.Send(credentials.email,credentials.password,data.From,data.To,data.Subject,data.Body,data.file_url,data.file_name)

                if result == 'ok':
                        data.Body = ''
                        data.From = ''
                        data.To = ''
                        data.Subject = ''
                        newsticker = Sticker(file_id= 'CAADAgADAgMAApzW5woU5Cm1Ey_jtAI', width= 512, height= 512)
                        bot.send_sticker(chat_id=query.message.chat_id, sticker= newsticker)
                        bot.send_message(chat_id=query.message.chat_id,text='The email has been sent....')
                        bot.send_message(chat_id=query.message.chat_id,text='Select an option:',
                              reply_markup=reply_markup) 
                else:
                        data.Body = ''
                        data.From = ''
                        data.To = ''
                        data.Subject = ''
                        newsticker = Sticker(file_id= 'CAADAgADCAMAApzW5wqTpbtQDP42agI', width= 512, height= 512)
                        bot.send_sticker(chat_id=update.message.chat_id, sticker= newsticker)
                        bot.send_message(chat_id=query.message.chat_id,text='Has been an error, try again....')
                        bot.send_message(chat_id=query.message.chat_id,text='Select an option:',
                              reply_markup=reply_markup)                  
        elif query.data == '7':
                #Query de cerrar sesion
                validate.login = [False,False,False]
                validate.sendImail = [False,False,False,False,False]
                credentials.email = ''
                credentials.password = ''
                index.min = 0
                index.max= 10
                inbox.Logout()
                newsticker = Sticker(file_id= 'CAADAgAD9QIAApzW5woDP3qDEC4ObwI', width= 512, height= 512)
                bot.send_sticker(chat_id=query.message.chat_id, sticker= newsticker)
                bot.send_message(chat_id=query.message.chat_id,text='Bye!',reply_markup=reply_markup)
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
        elif query.data == '8':
                #Query de cerrar bot
                validate.login = [False,False,False]
                validate.sendImail = [False,False,False,False,False]
                credentials.email = ''
                credentials.password = ''
                index.min = 0
                index.max= 10
                newsticker = Sticker(file_id= 'CAADAgAD9QIAApzW5woDP3qDEC4ObwI', width= 512, height= 512)
                bot.send_sticker(chat_id=query.message.chat_id, sticker= newsticker)
                bot.send_message(chat_id=query.message.chat_id,text='Bye!\nRemember... I am your father!!',reply_markup=reply_markup)
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
        elif query.data == '9':
                #Query de agregar adjuntable
                validate.sendImail[4] = True
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
                bot.send_message(chat_id=query.message.chat_id,text='Add your file') 
        elif query.data == '10':
                #Query de no adjuntar archivo al correo, da opcion de enviar o volver al menu principal
                bot.deleteMessage(chat_id=query.message.chat_id, message_id=query.message.message_id)
                keyboard = [[InlineKeyboardButton("Send", callback_data='6'),InlineKeyboardButton("Main menu", callback_data='0')]]
                reply_markup = InlineKeyboardMarkup(keyboard)
                bot.send_message(chat_id=query.message.chat_id, text= 'Select an option:',
                                        reply_markup=reply_markup)
示例#32
0
    def de_json(data):
        if 'from' in data:  # from is a reserved word, use from_user instead.
            from telegram import User
            from_user = User.de_json(data['from'])
        else:
            from_user = None

        if 'date' in data:
            date = datetime.fromtimestamp(data['date'])
        else:
            date = None

        if 'chat' in data:
            if 'first_name' in data['chat']:
                from telegram import User
                chat = User.de_json(data['chat'])
            if 'title' in data['chat']:
                from telegram import GroupChat
                chat = GroupChat.de_json(data['chat'])
        else:
            chat = None

        if 'forward_from' in data:
            from telegram import User
            forward_from = User.de_json(data['forward_from'])
        else:
            forward_from = None

        if 'forward_date' in data:
            forward_date = datetime.fromtimestamp(data['forward_date'])
        else:
            forward_date = None

        if 'reply_to_message' in data:
            reply_to_message = Message.de_json(data['reply_to_message'])
        else:
            reply_to_message = None

        if 'audio' in data:
            from telegram import Audio
            audio = Audio.de_json(data['audio'])
        else:
            audio = None

        if 'document' in data:
            from telegram import Document
            document = Document.de_json(data['document'])
        else:
            document = None

        if 'photo' in data:
            from telegram import PhotoSize
            photo = [PhotoSize.de_json(x) for x in data['photo']]
        else:
            photo = None

        if 'sticker' in data:
            from telegram import Sticker
            sticker = Sticker.de_json(data['sticker'])
        else:
            sticker = None

        if 'video' in data:
            from telegram import Video
            video = Video.de_json(data['video'])
        else:
            video = None

        if 'voice' in data:
            from telegram import Voice
            voice = Voice.de_json(data['voice'])
        else:
            voice = None

        if 'contact' in data:
            from telegram import Contact
            contact = Contact.de_json(data['contact'])
        else:
            contact = None

        if 'location' in data:
            from telegram import Location
            location = Location.de_json(data['location'])
        else:
            location = None

        if 'new_chat_participant' in data:
            from telegram import User
            new_chat_participant = User.de_json(data['new_chat_participant'])
        else:
            new_chat_participant = None

        if 'left_chat_participant' in data:
            from telegram import User
            left_chat_participant = User.de_json(data['left_chat_participant'])
        else:
            left_chat_participant = None

        if 'new_chat_photo' in data:
            from telegram import PhotoSize
            new_chat_photo = \
                [PhotoSize.de_json(x) for x in data['new_chat_photo']]
        else:
            new_chat_photo = None

        return Message(message_id=data.get('message_id', None),
                       from_user=from_user,
                       date=date,
                       chat=chat,
                       forward_from=forward_from,
                       forward_date=forward_date,
                       reply_to_message=reply_to_message,
                       text=data.get('text', ''),
                       audio=audio,
                       document=document,
                       photo=photo,
                       sticker=sticker,
                       video=video,
                       voice=voice,
                       caption=data.get('caption', ''),
                       contact=contact,
                       location=location,
                       new_chat_participant=new_chat_participant,
                       left_chat_participant=left_chat_participant,
                       new_chat_title=data.get('new_chat_title', None),
                       new_chat_photo=new_chat_photo,
                       delete_chat_photo=data.get('delete_chat_photo', None),
                       group_chat_created=data.get('group_chat_created', None))
 {
     'game':
     Game(
         'my_game',
         'just my game',
         [
             PhotoSize('game_photo_id', 'unique_id', 30, 30),
         ],
     )
 },
 {
     'photo': [PhotoSize('photo_id', 'unique_id', 50, 50)],
     'caption': 'photo_file'
 },
 {
     'sticker': Sticker('sticker_id', 'unique_id', 50, 50, True)
 },
 {
     'video': Video('video_id', 'unique_id', 12, 12, 12),
     'caption': 'video_file'
 },
 {
     'voice': Voice('voice_id', 'unique_id', 5)
 },
 {
     'video_note': VideoNote('video_note_id', 'unique_id', 20, 12)
 },
 {
     'new_chat_members': [User(55, 'new_user', False)]
 },
 {
示例#34
0
class TestStickerSet:
    title = 'Test stickers'
    is_animated = True
    contains_masks = False
    stickers = [Sticker('file_id', 'file_un_id', 512, 512, True)]
    name = 'NOTAREALNAME'

    def test_de_json(self, bot, sticker):
        name = f'test_by_{bot.username}'
        json_dict = {
            'name': name,
            'title': self.title,
            'is_animated': self.is_animated,
            'contains_masks': self.contains_masks,
            'stickers': [x.to_dict() for x in self.stickers],
            'thumb': sticker.thumb.to_dict(),
        }
        sticker_set = StickerSet.de_json(json_dict, bot)

        assert sticker_set.name == name
        assert sticker_set.title == self.title
        assert sticker_set.is_animated == self.is_animated
        assert sticker_set.contains_masks == self.contains_masks
        assert sticker_set.stickers == self.stickers
        assert sticker_set.thumb == sticker.thumb

    @flaky(3, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_1_png(self, bot, chat_id, sticker_file):
        with open('tests/data/telegram_sticker.png', 'rb') as f:
            file = bot.upload_sticker_file(95205500, f)
        assert file
        assert bot.add_sticker_to_set(chat_id,
                                      f'test_by_{bot.username}',
                                      png_sticker=file.file_id,
                                      emojis='😄')
        # Also test with file input and mask
        assert bot.add_sticker_to_set(
            chat_id,
            f'test_by_{bot.username}',
            png_sticker=sticker_file,
            emojis='😄',
            mask_position=MaskPosition(MaskPosition.EYES, -1, 1, 2),
        )

    @flaky(3, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_1_tgs(self, bot, chat_id):
        assert bot.add_sticker_to_set(
            chat_id,
            f'animated_test_by_{bot.username}',
            tgs_sticker=open('tests/data/telegram_animated_sticker.tgs', 'rb'),
            emojis='😄',
        )

    def test_sticker_set_to_dict(self, sticker_set):
        sticker_set_dict = sticker_set.to_dict()

        assert isinstance(sticker_set_dict, dict)
        assert sticker_set_dict['name'] == sticker_set.name
        assert sticker_set_dict['title'] == sticker_set.title
        assert sticker_set_dict['is_animated'] == sticker_set.is_animated
        assert sticker_set_dict['contains_masks'] == sticker_set.contains_masks
        assert sticker_set_dict['stickers'][0] == sticker_set.stickers[
            0].to_dict()

    @flaky(3, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_2_png(self, bot, sticker_set):
        file_id = sticker_set.stickers[0].file_id
        assert bot.set_sticker_position_in_set(file_id, 1)

    @flaky(3, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_2_tgs(self, bot, animated_sticker_set):
        file_id = animated_sticker_set.stickers[0].file_id
        assert bot.set_sticker_position_in_set(file_id, 1)

    @flaky(10, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_3_png(self, bot, chat_id, sticker_set_thumb_file):
        sleep(1)
        assert bot.set_sticker_set_thumb(f'test_by_{bot.username}', chat_id,
                                         sticker_set_thumb_file)

    @flaky(10, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_3_tgs(self, bot, chat_id, animated_sticker_file,
                               animated_sticker_set):
        sleep(1)
        assert bot.set_sticker_set_thumb(f'animated_test_by_{bot.username}',
                                         chat_id, animated_sticker_file)
        file_id = animated_sticker_set.stickers[-1].file_id
        # also test with file input and mask
        assert bot.set_sticker_set_thumb(f'animated_test_by_{bot.username}',
                                         chat_id, file_id)

    @flaky(10, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_4_png(self, bot, sticker_set):
        sleep(1)
        file_id = sticker_set.stickers[-1].file_id
        assert bot.delete_sticker_from_set(file_id)

    @flaky(10, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_4_tgs(self, bot, animated_sticker_set):
        sleep(1)
        file_id = animated_sticker_set.stickers[-1].file_id
        assert bot.delete_sticker_from_set(file_id)

    def test_upload_sticker_file_local_files(self, monkeypatch, bot, chat_id):
        # For just test that the correct paths are passed as we have no local bot API set up
        test_flag = False
        expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri()
        file = 'tests/data/telegram.jpg'

        def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = data.get('png_sticker') == expected

        monkeypatch.setattr(bot, '_post', make_assertion)
        bot.upload_sticker_file(chat_id, file)
        assert test_flag

    def test_create_new_sticker_set_local_files(self, monkeypatch, bot,
                                                chat_id):
        # For just test that the correct paths are passed as we have no local bot API set up
        test_flag = False
        expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri()
        file = 'tests/data/telegram.jpg'

        def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = data.get('png_sticker') == expected and data.get(
                'tgs_sticker') == expected

        monkeypatch.setattr(bot, '_post', make_assertion)
        bot.create_new_sticker_set(chat_id,
                                   'name',
                                   'title',
                                   'emoji',
                                   png_sticker=file,
                                   tgs_sticker=file)
        assert test_flag

    def test_add_sticker_to_set_local_files(self, monkeypatch, bot, chat_id):
        # For just test that the correct paths are passed as we have no local bot API set up
        test_flag = False
        expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri()
        file = 'tests/data/telegram.jpg'

        def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = data.get('png_sticker') == expected and data.get(
                'tgs_sticker') == expected

        monkeypatch.setattr(bot, '_post', make_assertion)
        bot.add_sticker_to_set(chat_id,
                               'name',
                               'emoji',
                               png_sticker=file,
                               tgs_sticker=file)
        assert test_flag

    def test_set_sticker_set_thumb_local_files(self, monkeypatch, bot,
                                               chat_id):
        # For just test that the correct paths are passed as we have no local bot API set up
        test_flag = False
        expected = (Path.cwd() / 'tests/data/telegram.jpg/').as_uri()
        file = 'tests/data/telegram.jpg'

        def make_assertion(_, data, *args, **kwargs):
            nonlocal test_flag
            test_flag = data.get('thumb') == expected

        monkeypatch.setattr(bot, '_post', make_assertion)
        bot.set_sticker_set_thumb('name', chat_id, thumb=file)
        assert test_flag

    def test_get_file_instance_method(self, monkeypatch, sticker):
        def make_assertion(*_, **kwargs):
            return kwargs['file_id'] == sticker.file_id

        assert check_shortcut_signature(Sticker.get_file, Bot.get_file,
                                        ['file_id'], [])
        assert check_shortcut_call(sticker.get_file, sticker.bot, 'get_file')
        assert check_defaults_handling(sticker.get_file, sticker.bot)

        monkeypatch.setattr(sticker.bot, 'get_file', make_assertion)
        assert sticker.get_file()

    def test_equality(self):
        a = StickerSet(self.name, self.title, self.is_animated,
                       self.contains_masks, self.stickers)
        b = StickerSet(self.name, self.title, self.is_animated,
                       self.contains_masks, self.stickers)
        c = StickerSet(self.name, None, None, None, None)
        d = StickerSet('blah', self.title, self.is_animated,
                       self.contains_masks, self.stickers)
        e = Audio(self.name, '', 0, None, None)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)