Beispiel #1
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(
            "На такой Эмодзи стикера у меня нет, извини =(")
Beispiel #2
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)
Beispiel #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))
Beispiel #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)))
Beispiel #5
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)))
Beispiel #6
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
Beispiel #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)))
Beispiel #8
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
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))
Beispiel #10
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))))
Beispiel #11
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))))
Beispiel #12
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)
Beispiel #13
0
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)
Beispiel #14
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()
Beispiel #17
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")
Beispiel #18
0
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)
Beispiel #19
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)
Beispiel #20
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)
Beispiel #21
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)
Beispiel #22
0
class TestStickerSet:
    title = 'Test stickers'
    is_animated = True
    is_video = True
    contains_masks = False
    stickers = [Sticker('file_id', 'file_un_id', 512, 512, True, 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,
            'is_video': self.is_video,
            '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.is_video == self.is_video
        assert sticker_set.contains_masks == self.contains_masks
        assert sticker_set.stickers == self.stickers
        assert sticker_set.thumb == sticker.thumb

    def test_create_sticker_set(
        self, bot, chat_id, sticker_file, animated_sticker_file, video_sticker_file
    ):
        """Creates the sticker set (if needed) which is required for tests. Make sure that this
        test comes before the tests that actually use the sticker sets!
        """
        test_by = f"test_by_{bot.username}"
        for sticker_set in [test_by, f'animated_{test_by}', f'video_{test_by}']:
            try:
                bot.get_sticker_set(sticker_set)
            except BadRequest as e:
                if not e.message == "Stickerset_invalid":
                    raise e

                if sticker_set.startswith(test_by):
                    s = bot.create_new_sticker_set(
                        chat_id,
                        name=sticker_set,
                        title="Sticker Test",
                        png_sticker=sticker_file,
                        emojis='😄',
                    )
                    assert s
                elif sticker_set.startswith("animated"):
                    a = bot.create_new_sticker_set(
                        chat_id,
                        name=sticker_set,
                        title="Animated Test",
                        tgs_sticker=animated_sticker_file,
                        emojis='😄',
                    )
                    assert a
                elif sticker_set.startswith("video"):
                    v = bot.create_new_sticker_set(
                        chat_id,
                        name=sticker_set,
                        title="Video Test",
                        webm_sticker=video_sticker_file,
                        emojis='🤔',
                    )
                    assert v

    @flaky(3, 1)
    def test_bot_methods_1_png(self, bot, chat_id, sticker_file):
        with open('tests/data/telegram_sticker.png', 'rb') as f:
            # chat_id was hardcoded as 95205500 but it stopped working for some reason
            file = bot.upload_sticker_file(chat_id, 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)
    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='😄',
        )

    @flaky(3, 1)
    def test_bot_methods_1_webm(self, bot, chat_id):
        with open('tests/data/telegram_video_sticker.webm', 'rb') as f:
            assert bot.add_sticker_to_set(
                chat_id, f'video_test_by_{bot.username}', webm_sticker=f, 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['is_video'] == sticker_set.is_video
        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)
    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)
    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(3, 1)
    def test_bot_methods_2_webm(self, bot, video_sticker_set):
        file_id = video_sticker_set.stickers[0].file_id
        assert bot.set_sticker_position_in_set(file_id, 1)

    @flaky(10, 1)
    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)
    def test_bot_methods_3_tgs(self, bot, chat_id, animated_sticker_file, animated_sticker_set):
        sleep(1)
        animated_test = f'animated_test_by_{bot.username}'
        assert bot.set_sticker_set_thumb(animated_test, 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(animated_test, chat_id, file_id)

    # TODO: Try the below by creating a custom .webm and not by downloading another pack's thumb
    @pytest.mark.skip(
        "Skipped for now since Telegram throws a 'File is too big' error "
        "regardless of the .webm file size."
    )
    def test_bot_methods_3_webm(self, bot, chat_id, video_sticker_file, video_sticker_set):
        pass

    @flaky(10, 1)
    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)
    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)

    @flaky(10, 1)
    def test_bot_methods_4_webm(self, bot, video_sticker_set):
        sleep(1)
        file_id = video_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
        monkeypatch.delattr(bot, '_post')

    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
                and data.get('webm_sticker') == expected
            )

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

    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
        monkeypatch.delattr(bot, '_post')

    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
        monkeypatch.delattr(bot, '_post')

    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,
            self.is_video,
        )
        b = StickerSet(
            self.name,
            self.title,
            self.is_animated,
            self.contains_masks,
            self.stickers,
            self.is_video,
        )
        c = StickerSet(self.name, None, None, None, None, None)
        d = StickerSet(
            'blah', self.title, self.is_animated, self.contains_masks, self.stickers, self.is_video
        )
        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)
Beispiel #23
0
def start(bot, update):
    update.message.reply_text("Привет! Пришли мне слово или текст до 15 тыс. "
                              "символов на русском или английском и "
                              "я переведу его для тебя! You're welcome!")
    sticker = Sticker(file_id='CAADAgAD8wcAAhhC7gj21R3ZVhUQAwI', height=512, width=512)
    bot.send_sticker(chat_id=update.message.chat_id, sticker=sticker)
Beispiel #24
0
def read_file(update, context):
    if update.message.reply_to_message:
        if update.message.reply_to_message.animation:
            file_id = str(update.message.reply_to_message.animation.file_id)
            unique_id = str(
                update.message.reply_to_message.animation.file_unique_id)
            width = str(update.message.reply_to_message.animation.width)
            height = str(update.message.reply_to_message.animation.height)
            duration = str(update.message.reply_to_message.animation.duration)
            # context.bot.send_message(update.effective_user.id,text=f"file_id = '{file_id}', \nfile_unique_id = '{unique_id}', \nwidth = {width}, \nheight = {height}, \nduration = {duration}")
            animation = Animation(file_id, unique_id, width, height, duration)
            update.message.reply_animation(
                animation,
                caption=
                f"This is an animation. \n\n\nfile_id = '{file_id}', \n\nfile_unique_id = '{unique_id}', \n\nwidth = {width}, \n\nheight = {height}, \n\nduration = {duration}"
            )
        if update.message.reply_to_message.photo:
            file_id = str(update.message.reply_to_message.photo[2]['file_id'])
            unique_id = str(
                update.message.reply_to_message.photo[2]['file_unique_id'])
            width = str(update.message.reply_to_message.photo[2]['width'])
            height = str(update.message.reply_to_message.photo[2]['height'])
            file_size = str(
                update.message.reply_to_message.photo[2]['file_size'])
            photo = PhotoSize(file_id, unique_id, width, height, file_size)
            update.message.reply_photo(
                photo,
                caption=
                f"This is a photo. \n\n\nfile_id = '{file_id}', \n\nfile_unique_id = '{unique_id}', \n\nwidth = {width},\n\nheight = {height},\n\nfile_size = {file_size}\n\n"
            )
        if update.message.reply_to_message.voice:
            file_id = str(update.message.reply_to_message.voice.file_id)
            unique_id = str(
                update.message.reply_to_message.voice.file_unique_id)
            duration = str(update.message.reply_to_message.voice.duration)
            mime_type = str(update.message.reply_to_message.voice.mime_type)
            file_size = str(update.message.reply_to_message.voice.file_size)
            voice = Voice(file_id, unique_id, duration, mime_type, file_size)
            update.message.reply_voice(
                voice,
                caption=
                f"This is a voice message. \n\n\nfile_id = '{file_id}', \n\nfile_unique_id = '{unique_id}', \n\nduration = {duration},\n\nmime_type = {mime_type},\n\nfile_size = {file_size}\n\n"
            )
        if update.message.reply_to_message.audio:
            file_id = str(update.message.reply_to_message.audio.file_id)
            unique_id = str(
                update.message.reply_to_message.audio.file_unique_id)
            duration = str(update.message.reply_to_message.audio.duration)
            performer = str(update.message.reply_to_message.audio.performer)
            title = str(update.message.reply_to_message.audio.title)
            mime_type = str(update.message.reply_to_message.audio.mime_type)
            file_size = str(update.message.reply_to_message.audio.file_size)
            audio = Audio(file_id, unique_id, duration, performer, title,
                          mime_type, file_size)
            update.message.reply_audio(
                audio,
                caption=
                f"This is an audio. \n\n\nfile_id = '{file_id}', \n\nfile_unique_id = '{unique_id}', \n\nduration = {duration},\n\nperformer = {performer} \n\ntitle = {title}, \n\nmime_type = {mime_type},\n\nfile_size = {file_size}"
            )
        if update.message.reply_to_message.document:
            file_id = str(update.message.reply_to_message.document.file_id)
            unique_id = str(
                update.message.reply_to_message.document.file_unique_id)
            document = Document(file_id, unique_id)
            update.message.reply_document(
                document,
                caption=
                f"This is a document. \n\n\nfile_id = '{file_id}',\n\nfile_unique_id = '{unique_id}'"
            )
        if update.message.reply_to_message.video:
            file_id = str(update.message.reply_to_message.video.file_id)
            unique_id = str(
                update.message.reply_to_message.video.file_unique_id)
            width = str(update.message.reply_to_message.video.width)
            height = str(update.message.reply_to_message.video.height)
            duration = str(update.message.reply_to_message.video.duration)
            video = Video(file_id, unique_id, width, height, duration)
            update.message.reply_video(
                video,
                caption=
                f"This is a video. \n\n\nfile_id = '{file_id}',\n\nfile_unique_id = '{unique_id}', \n\nwidth = {width}, \n\nheight = {height},\n\nduration = {duration}"
            )
        if update.message.reply_to_message.sticker:
            file_id = str(update.message.reply_to_message.sticker.file_id)
            unique_id = str(
                update.message.reply_to_message.sticker.file_unique_id)
            width = str(update.message.reply_to_message.sticker.width)
            height = str(update.message.reply_to_message.sticker.height)
            is_animated = str(
                update.message.reply_to_message.sticker.is_animated)
            sticker = Sticker(file_id, unique_id, width, height, is_animated)
            update.message.reply_sticker(sticker, caption='')
            context.bot.send_message(
                update.effective_chat.id,
                text=
                f"This is a sticker. \n\n\nfile_id = '{file_id}',\n\nfile_unique_id = '{unique_id}', \n\nwidth = {width}, \n\nheight = {height},\n\nis_animated = {is_animated}"
            )
        if update.message.reply_to_message.game:
            title = str(update.message.reply_to_message.game.title)
            description = str(update.message.reply_to_message.game.description)
            photo = str(update.message.reply_to_message.game.photo)
            text = str(update.message.reply_to_message.game.text)
            text_entities = str(
                update.message.reply_to_message.game.text_entities)
            animation = str(update.message.reply_to_message.game.animation)
            game = Game(title, description, photo, text, text_entities,
                        animation)
            update.message.reply_game(
                game,
                caption=
                f'This is a game.\n\n\ntitle = {title}, \n\ndescription = {description}, \n\nphoto = {photo}, \n\ntext = {text}, \n\ntext_entities = {text_entities}, \n\nanimation = {animation}'
            )
        if update.message.reply_to_message.video_note:
            file_id = str(update.message.reply_to_message.video_note.file_id)
            unique_id = str(
                update.message.reply_to_message.video_note.file_unique_id)
            length = str(update.message.reply_to_message.video_note.length)
            duration = str(update.message.reply_to_message.video_note.duration)
            videoNote = VideoNote(file_id, unique_id, length, duration)
            update.message.reply_video_note(videoNote, caption='')
            context.bot.send_message(
                update.effective_chat.id,
                text=
                f"This is a video message.\n\n\nfile_id = '{file_id}',\n\nfile_unique_id = '{unique_id}',\n\nlength = {length}, \n\nduration = {duration}"
            )
        if update.message.reply_to_message.text:
            ttext = str(update.message.reply_to_message.text)
            update.message.reply_text(f'{ttext}\n\nThis is a text.')
    else:
        u = str(update)
        u = dumps(eval(u), indent=2)
        update.message.reply_text(u)
 {
     '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)]
 },
 {
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)
Beispiel #27
0
class TestStickerSet(object):
    title = 'Test stickers'
    is_animated = True
    contains_masks = False
    stickers = [Sticker('file_id', 512, 512, True)]
    name = 'NOTAREALNAME'

    def test_de_json(self, bot):
        name = 'test_by_{0}'.format(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]
        }
        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

    @flaky(3, 1)
    @pytest.mark.timeout(10)
    def test_bot_methods_1(self, bot, chat_id):
        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,
                                      'test_by_{0}'.format(bot.username),
                                      file.file_id, '😄')

    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(self, bot, sticker_set):
        file_id = 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(self, bot, sticker_set):
        sleep(1)
        file_id = sticker_set.stickers[-1].file_id
        assert bot.delete_sticker_from_set(file_id)

    def test_get_file_instance_method(self, monkeypatch, sticker):
        def test(*args, **kwargs):
            return args[1] == sticker.file_id

        monkeypatch.setattr('telegram.Bot.get_file', test)
        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)
Beispiel #28
0
 }, {
     'document': Document('document_id'),
     'caption': 'document_file'
 }, {
     'animation': Animation('animation_id', 30, 30, 1),
     'caption': 'animation_file'
 }, {
     'game':
     Game('my_game', 'just my game', [
         PhotoSize('game_photo_id', 30, 30),
     ])
 }, {
     'photo': [PhotoSize('photo_id', 50, 50)],
     'caption': 'photo_file'
 }, {
     'sticker': Sticker('sticker_id', 50, 50)
 }, {
     'video': Video('video_id', 12, 12, 12),
     'caption': 'video_file'
 }, {
     'voice': Voice('voice_id', 5)
 }, {
     'video_note': VideoNote('video_note_id', 20, 12)
 }, {
     'new_chat_members': [User(55, 'new_user', False)]
 }, {
     'contact': Contact('phone_numner', 'contact_name')
 }, {
     'location': Location(-23.691288, 46.788279)
 }, {
     'venue':
Beispiel #29
0
class TestStickerSet(object):
    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 = 'test_by_{}'.format(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,
                                      'test_by_{}'.format(bot.username),
                                      png_sticker=file.file_id,
                                      emojis='😄')
        # Also test with file input and mask
        assert bot.add_sticker_to_set(chat_id,
                                      'test_by_{}'.format(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,
            'animated_test_by_{}'.format(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('test_by_{}'.format(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(
            'animated_test_by_{}'.format(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(
            'animated_test_by_{}'.format(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_get_file_instance_method(self, monkeypatch, sticker):
        def test(*args, **kwargs):
            return args[1] == sticker.file_id

        monkeypatch.setattr('telegram.Bot.get_file', test)
        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)
Beispiel #30
0
 }, {
     'document': Document('document_id'),
     'caption': 'document_file'
 }, {
     'animation': Animation('animation_id', 30, 30, 1),
     'caption': 'animation_file'
 }, {
     'game':
     Game('my_game', 'just my game', [
         PhotoSize('game_photo_id', 30, 30),
     ])
 }, {
     'photo': [PhotoSize('photo_id', 50, 50)],
     'caption': 'photo_file'
 }, {
     'sticker': Sticker('sticker_id', 50, 50, True)
 }, {
     'video': Video('video_id', 12, 12, 12),
     'caption': 'video_file'
 }, {
     'voice': Voice('voice_id', 5)
 }, {
     'video_note': VideoNote('video_note_id', 20, 12)
 }, {
     'new_chat_members': [User(55, 'new_user', False)]
 }, {
     'contact': Contact('phone_numner', 'contact_name')
 }, {
     'location': Location(-23.691288, 46.788279)
 }, {
     'venue':