コード例 #1
0
ファイル: app.py プロジェクト: v1rus96/trialkidsinfo-bot
def test_chosen(chosen_inline_result):
    kID, action = chosen_inline_result.query.split()
    order = chosen_inline_result.result_id
    find = MessageModel.get_one(args={'kID': str(kID)}, filters={'_id': 0})
    if find:
        chat_id = find['chat_id']
        message_id = find['message_id']
    if action == 'estimate':
        MessageModel.update_message(args={'kID': str(kID)}, set_query={
                                    "$set": {'estimation': chosen_inline_result.result_id}})
        bot.edit_message_media(media=types.InputMediaPhoto(generateImage(kID=kID)),
                               chat_id=chat_id,
                               message_id=message_id)
    elif action == 'assign':
        MessageModel.update_message(args={'kID': str(kID)}, set_query={
                                    "$set": {'assignedTo': chosen_inline_result.result_id}})
        bot.edit_message_media(media=types.InputMediaPhoto(generateImage(kID=kID)),
                               chat_id=chat_id,
                               message_id=message_id,
                               reply_markup=mainKeyboard(kID))
    elif action == 'family':
        MessageModel.update_message(args={'kID': str(kID)}, set_query={
                                    "$set": {'family': chosen_inline_result.result_id}})
        bot.edit_message_media(media=types.InputMediaPhoto(generateImage(kID=kID)),
                               chat_id=chat_id,
                               message_id=message_id)
    elif action == 'order':
        session1 = isNowInTimePeriod(time(9, 45), time(11, 45))
        session2 = isNowInTimePeriod(time(11, 45), time(13, 45))
        session3 = isNowInTimePeriod(time(13, 45), time(16, 45))
        session4 = isNowInTimePeriod(time(16, 45), time(5, 45))
        if session1:
            session = 1
        elif session2:
            session = 2
        elif session3:
            session = 3
        elif session4:
            session = 4
        date = str(datetime.now().date())
        find2 = MessageModel.get_one(args={'order': int(
            order), 'session': session, 'date': date}, filters={'_id': 0})
        if find2:
            message_idOrder = find2['message_id']
            print(message_idOrder)
            kIDOrder = find2['kID']
            print(kIDOrder)
            orderCurrent = find['order']
            MessageModel.update_message(args={'kID': str(kID)}, set_query={"$set": {
                                        'order': int(chosen_inline_result.result_id), 'message_id': message_idOrder}})
            bot.edit_message_media(media=types.InputMediaPhoto(generateImage(kID=kID)),
                                   chat_id=chat_id,
                                   message_id=message_idOrder)
            MessageModel.update_message(args={'kID': str(kIDOrder)}, set_query={
                                        "$set": {'order': int(orderCurrent), 'message_id': message_id}})
            bot.edit_message_media(media=types.InputMediaPhoto(generateImage(kID=kIDOrder)),
                                   chat_id=chat_id,
                                   message_id=message_id)
        else:
            print("Didnt work")
コード例 #2
0
ファイル: cs_bot.py プロジェクト: ShchipskiiYura/CS_bot
def send_array(message):
    try:
        new = mine()
        post1 = new[0]
        picture1 = new[1]
        # print(new)
        # print(post1, picture1)
        # chat_id = "@metrogoldenma"
        if len(picture1) > 10:
            n = 10
        else:
            n = len(picture1)
        try:
            caption = post1
            try:
                media = [
                    types.InputMediaPhoto(picture1[0],
                                          caption=post1,
                                          parse_mode='markdown')
                ]
            except:
                media = [types.InputMediaPhoto(picture1[0])]

            for photo_id in range(1, n):
                media.append(types.InputMediaPhoto(picture1[photo_id]))
            bot.send_media_group(message.chat.id, media, parse_mode='markdown')
        except:
            try:
                bot.send_photo(message.chat.id,
                               picture1[0],
                               caption=post1,
                               parse_mode='markdown')
            except:
                try:
                    med = []
                    for id in picture1:
                        med.append(types.InputMediaPhoto(id))
                    bot.send_media_group(message.chat.id,
                                         med,
                                         parse_mode='markdown')
                    bot.send_message(message.chat.id,
                                     text=post1,
                                     parse_mode='markdown')
                except:
                    try:
                        bot.send_photo(message.chat.id,
                                       picture1[0],
                                       parse_mode='markdown')
                        bot.send_message(message.chat.id,
                                         text=post1,
                                         parse_mode='markdown')
                    except:
                        bot.send_photo(message.chat.id,
                                       picture1[0],
                                       parse_mode='markdown')
    except:
        news = "Прошу вибачення за неполадки.\nЧіп і Дейл уже спішать на допомогу.\nЮхххххххххххххххххххххуууууууууууууууууууу"
        bot.send_message(message.chat.id, text=news)
コード例 #3
0
 def test_send_media_group(self):
     tb = telebot.TeleBot(TOKEN)
     img1 = 'https://i.imgur.com/CjXjcnU.png'
     img2 = 'https://i.imgur.com/CjXjcnU.png'
     medias = [types.InputMediaPhoto(img1, "View"), types.InputMediaPhoto(img2, "Dog")]
     result = tb.send_media_group(CHAT_ID, medias)
     assert len(result) == 2
     assert result[0].media_group_id is not None
     assert result[0].media_group_id == result[1].media_group_id
コード例 #4
0
 def test_send_media_group_formatting_caption(self):
     tb = telebot.TeleBot(TOKEN)
     img1 = 'https://i.imgur.com/CjXjcnU.png'
     img2 = 'https://i.imgur.com/CjXjcnU.png'
     medias = [types.InputMediaPhoto(img1, "*View*", parse_mode='Markdown'),
               types.InputMediaPhoto(img2, "_Dog_", parse_mode='Markdown')]
     result = tb.send_media_group(CHAT_ID, medias)
     assert len(result) == 2
     assert result[0].media_group_id is not None
     assert result[0].caption_entities[0].type == 'bold'
     assert result[1].caption_entities[0].type == 'italic'
コード例 #5
0
def send_chords(message):
    """Отправка изображения аккорда"""
    if len(message.text) < 10:
        cap, chord_files_id = chords_db.get_files_id(message.text.lower())
        if chord_files_id is None:
            bot.send_message(message.chat.id, string_values.update)
            chord = parser.Images_chord(message.text)
            caption, chord_urls = chord.get_Url()
            if len(caption) > 0:
                ids = []
                chord_urls = split_array_of_ten(chord_urls)
                for url_box in chord_urls:
                    if len(url_box) > 1:
                        images = []
                        print(url_box)
                        for chord_url in url_box:
                            images.append(types.InputMediaPhoto(chord_url))
                        try:
                            messages_file = bot.send_media_group(message.chat.id, images)
                        except Exception:
                            messages_file = []
                            bot.send_message(message.chat.id, string_values.message_exception)
                            for admin in config.ADMINS:
                                bot.send_message(admin,
                                                 string_values.message_exception_loading_media_to_admin + '\nАккорд: ' + message.text)
                        for message_file in messages_file:
                            ids.append(message_file.photo[0].file_id)
                    else:
                        img = requests.get(url_box[0])
                        file = bot.send_photo(message.chat.id, img.content)
                        ids.append(file.photo[0].file_id)
                if len(ids) > 0:
                    chords_db.set_files_id(message.text.lower(), ids, caption)
            else:
                keyboard = types.InlineKeyboardMarkup()
                keyboard.add(types.InlineKeyboardButton(text=string_values.to_offer,
                                                        callback_data='^$' + str(
                                                            message.from_user.first_name) + '$' + str(
                                                            message.chat.id) + '$' + str(message.text)))
                bot.send_message(message.chat.id, string_values.text_inline_button, reply_markup=keyboard)
        else:
            chord_files_id = split_array_of_ten(chord_files_id)
            for chord_files_box in chord_files_id:
                if len(chord_files_box) > 1:
                    images = []
                    for chord_file_id in chord_files_box:
                        images.append(types.InputMediaPhoto(chord_file_id))
                    bot.send_media_group(message.chat.id, images)
                else:
                    bot.send_photo(message.chat.id, chord_files_box[0])
    else:
        bot.send_message(message.chat.id, string_values.not_exist)
コード例 #6
0
ファイル: test_telebot.py プロジェクト: Gralex80/PyTbot
    def test_edit_message_media(self):
        file_data = open('../examples/detailed_example/kitten.jpg', 'rb')
        file_data_2 = open('../examples/detailed_example/rooster.jpg', 'rb')
        tb = telebot.TeleBot(TOKEN)
        msg = tb.send_photo(CHAT_ID, file_data)
        new_msg = tb.edit_message_media(chat_id=CHAT_ID, message_id=msg.message_id,
                                        media=types.InputMediaPhoto(file_data_2, caption='Test editMessageMedia 0'))
        assert type(new_msg) != bool

        new_msg = tb.edit_message_media(chat_id=CHAT_ID, message_id=msg.message_id,
                                        media=types.InputMediaPhoto(msg.photo[0].file_id, caption='Test editMessageMedia'))
        assert type(new_msg) != bool
        assert new_msg.caption == 'Test editMessageMedia'
コード例 #7
0
def ph(message):
    bot.send_message(
        message.chat.id,
        'Сразу все твое расписание, что бы не ебаться с кнопками! ❤\n\nP. S. Не знаю зачем вся эта фигня с кнопкапи, но походу мой создатель хотел просто поиграться с этим и разобраться, имхо.\nА вдруг кому и полезно будет :D'
    )

    bot.send_media_group(message.chat.id, [
        types.InputMediaPhoto('https://imbt.ga/poczWS7NoH'),
        types.InputMediaPhoto('https://imbt.ga/XwNIcnAZaj'),
        types.InputMediaPhoto('https://imbt.ga/FOINQmsDi4'),
        types.InputMediaPhoto('https://imbt.ga/Rl2RWFYTb9'),
        types.InputMediaPhoto('https://imbt.ga/mozMd3KsP0')
    ])
コード例 #8
0
def edit_media(call):
    new_id = random.randint(1, 5)
    new_file = 'pics/{}.jpg'.format(new_id)
    bot.edit_message_media(media=types.InputMediaPhoto(open(new_file, 'rb')),
                           chat_id=call.message.chat.id,
                           message_id=call.message.message_id,
                           reply_markup=get_keyboard())
コード例 #9
0
 def post(self):
     text = self.text
     photo = {types.InputMediaPhoto(file) for file in self.album}
     if photo:
         bot_handlers.send_media_group(config.channel_id, photo)
     bot_handlers.send_message(config.channel_id, text)
     bot_handlers.send_message(config.admin_id, 'Объявление опубликовано!')
コード例 #10
0
ファイル: handlers.py プロジェクト: petrov-aa/soedini_bot
def send_combined_image(session: Session):
    photos = session.photo_set.all()
    images = list()
    for photo in photos:
        image_content = image_cache.get_image(str(photo.id))
        if image_content is None:
            photo_file_info = bot.get_file(photo.telegram_file_id)
            image_content = bot.download_file(photo_file_info.file_path)
            image_cache.store_image(str(photo.id), image_content)
        image_bytes = io.BytesIO(image_content)
        image = PIL.Image.open(image_bytes)
        images.append(image)
    combined_image = process.get_combined_image(images, session.mode)
    combined_image_bytes_stream = BytesIO()
    combined_image.save(combined_image_bytes_stream, format=PHOTO_PIL_FORMAT)
    combined_image_bytes_stream.flush()
    combined_image_bytes_stream.seek(0)
    bot_backend.update_session_query_token(session)
    if session.control_telegram_message_id is not None:
        message = bot.edit_message_media(
            tg.InputMediaPhoto(combined_image_bytes_stream.getvalue()),
            session.chat.telegram_id,
            session.control_telegram_message_id,
            reply_markup=get_control_markup(session, len(photos)))
    else:
        message = bot.send_photo(session.chat.telegram_id,
                                 combined_image_bytes_stream.getvalue(),
                                 reply_markup=get_control_markup(
                                     session, len(photos)))
    bot_backend.set_session_telegram_message_id(
        session, message.message_id, datetime.fromtimestamp(message.date))
    bot_backend.set_session_combined_photo_file_id(session,
                                                   message.photo[-1].file_id)
コード例 #11
0
def prods(call):
    bot.delete_message(call.message.chat.id, call.message.message_id)
    id = call.data.split('_')[-1]
    bot.last_update_id
    r = requests.get(url + f'product/?category={id}&limit=3')
    for prod in r.json()['results']:
        prod_id = prod['id']
        name = prod['name']
        price = prod['price']
        # images = prod['images']
        images = 'https://im0-tub-ru.yandex.net/i?id=b6a2cf0ee7b2aafd66d4e996bab05433&n=13'

        keyboard = types.InlineKeyboardMarkup()
        key_1 = types.InlineKeyboardButton(text='Добавить',
                                           callback_data=f'add_{prod_id}')
        key_2 = types.InlineKeyboardButton(text='Заказать в 1 клик',
                                           callback_data=f'add_{prod_id}')
        keyboard.add(key_1, key_2)
        img = [types.InputMediaPhoto(images, caption=name) for img in range(3)]
        # img = [types.InputMediaPhoto(img['image'], caption='test')
        #        for img in images]
        bot.send_media_group(call.message.chat.id, img)
        bot.send_message(call.message.chat.id,
                         f'''{name}
{price}р.''',
                         reply_markup=keyboard)
コード例 #12
0
def watch_wishlist_inline(chosen_inline_result):
    """
    inline-метод, позволяющий публиковать в чате игры из своего вишлиста
    :param chosen_inline_result: пустая строка
    """
    print('общий инлайнер')
    try:
        with session_scope() as session:
            wishes = Wish.get_all(user_id=chosen_inline_result.from_user.id,
                                  session=session)
            games = [
                Game.get(id=wish.game_id, session=session) for wish in wishes
            ]

            bot.answer_inline_query(
                inline_query_id=chosen_inline_result.id,
                results=[
                    types.InlineQueryResultPhoto(
                        id=game.id,
                        title=game.name,
                        photo_url=game.poster_url,
                        thumb_url=game.poster_url,
                        caption=str(game),
                        parse_mode='MARKDOWN',
                        input_message_content=types.InputMediaPhoto(
                            caption=str(game),
                            parse_mode='MARKDOWN',
                            media=get_image_bytes(game.poster_url)),
                    ) for i, game in enumerate(
                        sorted(games, key=lambda x: x.name))
                ],
                switch_pm_text='Добавить игр?',
                switch_pm_parameter='start')
    except Exception as e:
        print(e)
def change_inline_picture(call):

    #photo2 = open(f'./pic/{models_pic_dict[current_model_n]}', 'rb')
    photo2 = open(f'./foo.png', 'rb')
    #bot.send_photo(call.message.chat.id, 'AgACAgIAAxkDAAIBzV97Xk23sGQOKNiXf6h4pN9lhi4OAAKCsDEbb8fRS4rRMe0-0_1Wc7NFmC4AAwEAAwIAA20AA7FTAQABGwQ')
    bot.edit_message_media(chat_id=call.message.chat.id,
                           message_id=photo_obj.message_id,
                           media=types.InputMediaPhoto(photo2))
コード例 #14
0
def navigation_handler(call):
    requested_id = int(call.data)
    photo_url = get_photo_url(requested_id)
    keyboard = get_keyboard(requested_id)
    bot.edit_message_media(media=types.InputMediaPhoto(photo_url),
                           chat_id=call.message.chat.id,
                           message_id=call.message.message_id,
                           reply_markup=keyboard)
コード例 #15
0
ファイル: bot_sender.py プロジェクト: fizteh95/prod_vk_bot
    def broadcaster(self, posts: list) -> int:
        """

        """
        for post in posts:
            if (not post.photo) and post.text:
                self.bot.send_message(self.tg_channel, post.text)
                sleep(.05)

            if (len(post.photo) > 1) and (len(post.photo) <= 10):

                medias = []

                if post.text:
                    medias.append(types.InputMediaPhoto(post.photo[0], post.text))
                else:
                    medias.append(types.InputMediaPhoto(post.photo[0]))

                for i in range(1, len(post.photo)):
                    medias.append(types.InputMediaPhoto(post.photo[i]))

                try:
                    self.bot.send_media_group(self.tg_channel, medias)
                except Exception as e:
                    print(e)
                sleep(.05)  
                sleep(.05)

            if len(post.photo) == 1:
                if post.text:
                    self.bot.send_photo(self.tg_channel, post.photo[0],
                                        caption=post.text)
                else:
                    self.bot.send_photo(self.tg_channel, post.photo[0])
                sleep(.05)

            # try:
            #     if post.audio:
            #         for audio in post.audio:
            #             self.bot.send_audio(self.tg_channel, audio.get('url'))
            #             sleep(.05)
            # except Exception as e:
            #     print(e)

        return True
コード例 #16
0
def edit_media(call):
    global Init
    Init=5
    markup = types.InlineKeyboardMarkup()
    markup = Fc.controlMarkup(0, Init, fileContent)
    markup.add(types.InlineKeyboardButton(text="Atualizar",callback_data='atualizar'),types.InlineKeyboardButton(text="Próximo", callback_data='next'))

    bot.edit_message_media(media=types.InputMediaPhoto(open("Files/BD-N1.png", 'rb')), chat_id=call.message.chat.id,
                           message_id=call.message.message_id, reply_markup=markup)
コード例 #17
0
ファイル: bot.py プロジェクト: bubaleh1337/vktgbot
    def sendPhotosPost():
        try:
            photo_list = []
            for urlPhoto in photo_url_list:
                photo_list.append(
                    types.InputMediaPhoto(
                        urllib.request.urlopen(urlPhoto).read()))

            if len(textOfPost) <= 1024 and len(textOfPost) > 0:
                photo_list[0].caption = textOfPost
                photo_list[0].parse_mode = "HTML"
            elif len(textOfPost) > 1024:
                if len(textOfPost) <= 4096:
                    bot.send_message(config.tgChannel,
                                     textOfPost,
                                     parse_mode="HTML")
                else:
                    if repost[0] == "post":
                        bot.send_message(
                            config.tgChannel,
                            f"{textOfPost[:4090]} (...)",
                            parse_mode="HTML",
                        )
                        bot.send_message(
                            config.tgChannel,
                            f"(...) {textOfPost[4090:]}",
                            parse_mode="HTML",
                        )
                    elif repost[0] == "repost":
                        bot.send_message(
                            config.tgChannel,
                            f"{textOfPost[:4086]}</i> (...)",
                            parse_mode="HTML",
                            disable_web_page_preview=True,
                        )
                        bot.send_message(
                            config.tgChannel,
                            f"(...) <i>{textOfPost[4086:]}",
                            parse_mode="HTML",
                            disable_web_page_preview=True,
                        )
            bot.send_media_group(config.tgChannel, photo_list)
            addLog("i", f"[id:{postid}] Text post with photos sent")
        except Exception as ex:
            if type(ex).__name__ == "ConnectionError":
                addLog(
                    "w",
                    f"[id:{postid}] {type(ex).__name__} went wrong in sendPosts() --> sendPhotosPost(): {str(ex)}",
                )
                addLog("i",
                       f"[id:{postid}] Bot trying to resend message to user")
                time.sleep(3)
                sendPhotosPost()
            addLog(
                "e",
                f"[id:{postid}] Something [{type(ex).__name__}] went wrong in sendPosts() --> sendPhotosPost(): {str(ex)}",
            )
コード例 #18
0
 def test_send_media_group_local_files(self):
     photo = open('../examples/detailed_example/kitten.jpg', 'rb')
     video = open('./test_data/test_video.mp4', 'rb')
     tb = telebot.TeleBot(TOKEN)
     medias = [types.InputMediaPhoto(photo, "View"),
               types.InputMediaVideo(video)]
     result = tb.send_media_group(CHAT_ID, medias)
     assert len(result) == 2
     assert result[0].media_group_id is not None
     assert result[1].media_group_id is not None
コード例 #19
0
def process_image(message):
    
    try:
        # Prepares a photo on the Telegram API server and downloads it from there
        pic = bot.get_file(os.getenv(str(message.chat.id) + 'user_pic_id'))
        download_url = telegram_download_link + pic.file_path  
        downloaded = requests.get(download_url)
    
        # Sends the downloaded picture to our API server
        request_url = api_dummy_url if os.getenv(str(message.chat.id) + 'DUMMY') else api_url
        files = {"file": (pic.file_path.split('/')[1], downloaded.content, 'image/jpeg')}
        data = {"nsimilar": message.text, "rmfirst": os.getenv(str(message.chat.id) + 'painting_recomm') == '1'}
        
        # Resetting the bot to the waiting mode
        os.environ[str(message.chat.id) + 'user_pic_id'] = ''
        os.environ[str(message.chat.id) + 'painting_recomm'] = ''
        
        api_response = requests.post(request_url, files=files, data=data).json()
        
        if api_response:
            # Processes a response received from our API server    
            # API stricture: {img_url, html_url, author, title, created, museum}  
            returned_photos = []
            
            for response_item in api_response:
                pic_received = requests.get(response_item['img_url']).content
        
                # If picture is larger then 10 Mb, resize it before sending
                while (len(pic_received) > 10000000):
                    pic_received = resize_pic(pic_received)
                
                reply = f'<i>Title:</i> <a href="{response_item["html_url"]}">{response_item["title"]}</a>\n<i>Author:</i> {response_item["author"]}\n' + \
                        f"<i>Created:</i> {response_item['created']}\n<i>Museum:</i> {response_item['museum']}\n\n"
                    
                if len(api_response) == 1:    
                    # Sends painting and description to the chat
                    bot.send_photo(message.chat.id, pic_received, caption=reply, parse_mode = 'HTML')
                else:
                    # Or adds them to send later
                    returned_photos.append(types.InputMediaPhoto(pic_received, caption=reply, parse_mode='HTML'))
            
            # Sends group of photos
            if returned_photos:
                bot.send_media_group(message.chat.id, returned_photos)
                    
        else:
            bot.send_message(message.chat.id, "I was not able to find similar paintings 😭")
        
        time.sleep(2)
        bot.send_message(message.chat.id, "Now you can send me a 📷 or enter your ❤️🖼️ again")
                        
    except BaseException as e:
        print(e)
        bot.send_message(message.chat.id, 'Oops! Something crashed in the middle 🚑🤖... ')
        bot.send_message(message.chat.id, 'Please try again or use another photo 🤷🤷‍♂️')
コード例 #20
0
def callback_query(call):
    bot.answer_callback_query(call.id, "Доставляю")
    logger.info('uid is {}, name is {} '.format(call.message.chat.id,
                                                call.data))
    try:
        try:
            all_data = sql.get_values(call.data, str(call.message.chat.id))
            logger.info(all_data)
            if len(all_data['photos']) > 2:
                try:
                    bot.send_media_group(call.message.chat.id,
                                         (types.InputMediaPhoto(i)
                                          for i in all_data['photos']))
                except Exception as e:
                    '''maybe make some regular for Bad Request or find another way'''
                    chunks_ = chunks(all_data['photos'], 10)
                    for chunk in chunks_:
                        bot.send_media_group(call.message.chat.id,
                                             (types.InputMediaPhoto(i)
                                              for i in chunk))
            else:
                for i in all_data['photos']:
                    bot.send_photo(call.message.chat.id, i)
            if len(all_data['videos']) > 0:
                bot.send_media_group(call.message.chat.id,
                                     (types.InputMediaVideo(i)
                                      for i in all_data['videos']))
            if len(all_data['gifs']) > 0:
                bot.send_media_group(call.message.chat.id,
                                     (types.InputMediaDocument(i)
                                      for i in all_data['gifs']))
            if len(all_data['doc_images']) > 0:
                for doc in all_data['doc_images']:
                    bot.send_document(call.message.chat.id, doc)
            sql.session_add((call.message.chat.id, call.message.date))

        except FileNotFoundError:
            bot.send_message(call.message.chat.id, 'No data')

    except Exception as e:
        logger.error(e)
        bot.send_message(call.message.chat.id, 'Что-то пошло не так')
コード例 #21
0
def call_exec_true(call):
    bot.answer_callback_query(callback_query_id=call.id)
    bot.delete_message(chat_id=call.message.chat.id, message_id=mymsg.message_id)
    bot.delete_message(chat_id=call.message.chat.id, message_id=myexcel.message_id)
    bot.delete_message(chat_id=call.message.chat.id, message_id=myphoto.message_id)

    markup = Fc.SrControl(0, execute)
    bot.answer_callback_query(callback_query_id=call.id)
    bot.edit_message_media(media=types.InputMediaPhoto(open("Files/SRimage.png", 'rb'), caption=caption),
                           chat_id=call.message.chat.id,
                           message_id=call.message.message_id, reply_markup=markup)
コード例 #22
0
def compare(message):
    with open("userbase.json", "r", encoding="UTF-8") as database:
        data = json.loads(database.read())
        try:
            couple_list = data[str(message.from_user.id)]
            del couple_list
        except KeyError:
            personalise(message)
            compare(message)
            return 0
        int1 = random.randint(0, amount - 1)
        int2 = random.randint(0, amount - 1)
        if int1 == int2:
            if int2 == amount - 1:
                int2 = 0
            else:
                int2 += 1
        int1_prev = int1
        int2_prev = int2
        int1, int2 = check(data, message.from_user.id, int1, int1_prev, int2, int2_prev)
        if int1 is None:
            achievement = open("photos/achievement.jpg", "rb")
            bot.send_message(message.chat.id, "[ошибка] Вы оценили всех. Серьезно, всех!")
            bot.send_photo(message.chat.id, achievement, caption="Лови ачивку :Р")
            return 0
        data[str(message.from_user.id)][str(int1)].append(int2)
        data[str(message.from_user.id)][str(int1)].sort()  # мб лучше sorted([...])
        data[str(message.from_user.id)][str(int2)].append(int1)
        data[str(message.from_user.id)][str(int2)].sort()  # ________^
        write_database(data, "userbase.json")
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        item1 = types.KeyboardButton("1")
        item2 = types.KeyboardButton("2")
        markup.add(item1, item2)
        ph1 = open("photos/" + str(int1) + ".jpg", "rb")
        ph2 = open("photos/" + str(int2) + ".jpg", "rb")
        photos = [types.InputMediaPhoto(ph1),
                  types.InputMediaPhoto(ph2)]
        bot.send_media_group(message.chat.id, photos)
        sent = bot.send_message(message.chat.id, "Какую ты считаешь более привлекательной?", reply_markup=markup)
        bot.register_next_step_handler(sent, choose, [int1, int2])
コード例 #23
0
def back_cat_handling(call):
    print(call.data)
    keyboard = keyboards.category_keyboard(data_instance.categories)
    caption = 'Choose the category'
    try:
        bot.edit_message_media(media=types.InputMediaPhoto(main_photo,
                                                           caption=caption),
                               chat_id=call.from_user.id,
                               message_id=call.message.message_id,
                               reply_markup=keyboard)
    except Exception:
        pass
コード例 #24
0
def product_handling(call):
    print(call.data)
    product = data_instance.get_product_details(call.data)
    key = keyboards.prod_description_keyboard(product)
    caption = f"{product['name']}\nUnit - {product['unit']}\nPrice - {product['price']}"
    try:
        bot.edit_message_media(media=types.InputMediaPhoto(product['image'],
                                                           caption=caption),
                               chat_id=call.from_user.id,
                               message_id=call.message.message_id,
                               reply_markup=key)
    except Exception:
        pass
コード例 #25
0
def category_handler(call):
    print(call.data)
    prods = data_instance.get_prods_in_given_category(call.data)
    key = keyboards.prods_by_category(prods)
    caption = call.data.upper()
    try:
        bot.edit_message_media(media=types.InputMediaPhoto(main_photo,
                                                           caption=caption),
                               chat_id=call.from_user.id,
                               message_id=call.message.message_id,
                               reply_markup=key)
    except Exception:
        pass
コード例 #26
0
ファイル: cs_bot.py プロジェクト: ShchipskiiYura/CS_bot
def send(photo, post):
    if len(photo) > 10:
        n = 10
    else:
        n = len(photo)
    try:
        caption = post
        try:
            media = [
                types.InputMediaPhoto(photo[0],
                                      caption=post,
                                      parse_mode='markdown')
            ]
        except:
            media = [types.InputMediaPhoto(photo[0])]

        for photo_id in range(1, n):
            media.append(types.InputMediaPhoto(photo[photo_id]))
        bot.send_media_group(chat_id, media, parse_mode='markdown')
    except:
        try:
            bot.send_photo(chat_id,
                           photo[0],
                           caption=post,
                           parse_mode='markdown')
        except:
            try:
                med = []
                for id in photo:
                    med.append(types.InputMediaPhoto(id))
                bot.send_media_group(chat_id, med)
                bot.send_message(chat_id, text=post, parse_mode='markdown')
            except:
                try:
                    bot.send_photo(chat_id, photo[0])
                    bot.send_message(chat_id, text=post, parse_mode='markdown')
                except:
                    bot.send_photo(chat_id, photo[0])
コード例 #27
0
ファイル: bot.py プロジェクト: saikokm/YouTube-Bot
def mainCha_subscribed(object_, printMsg: bool):
    if str(type(object_)) == "<class 'telebot.types.CallbackQuery'>":
        obType = 'call'
        message_id = object_.message.id
        chat_id = object_.message.chat.id
    else:
        obType = 'message'
        chat_id = object_.chat.id
        message_id = object_.id
    user_id = object_.from_user.id
    status = bot.get_chat_member(mainCha, user_id).status
    if status != 'left':
        return True
    else:
        if printMsg:
            if obType == 'call' and object_.message.photo != None:
                bot.edit_message_media(
                    chat_id=chat_id,
                    message_id=message_id,
                    media=types.InputMediaPhoto(
                        object_.message.photo[0].file_id),
                    reply_markup=types.InlineKeyboardMarkup().add(
                        types.InlineKeyboardButton(
                            text=
                            f'⭕️ يجب الاشتراك بقناة البوت لاستعماله {object_.from_user.first_name}',
                            url=
                            f"https://telegram.me/{bot.get_chat(mainCha).username}"
                        )))
            else:
                if obType == 'call':
                    bot.delete_message(chat_id=chat_id, message_id=message_id)
                else:
                    pass
                bot.send_message(
                    chat_id=chat_id,
                    reply_to_message_id=None
                    if obType == 'call' else message_id,
                    text=mainChaSubscribMsg(
                        user_id=user_id,
                        first_name=object_.from_user.first_name),
                    parse_mode='HTML',
                    reply_markup=types.InlineKeyboardMarkup().add(
                        types.InlineKeyboardButton(
                            text='𝕔𝕙𝕒.',
                            url=
                            f"https://telegram.me/{bot.get_chat(mainCha).username}"
                        )))
        else:
            pass
    return False
コード例 #28
0
def call_session(call):
    id_ = call.message.chat.id
    msg_id = call.message.json['message_id']
    user = User(id_)
    msg = Message(user.state_movie)
    msg.session(int(call.data) - 1)
    keyboard = Markup()
    keyboard.back()
    bot.edit_message_media(chat_id=id_,
                           message_id=msg_id,
                           media=types.InputMediaPhoto(msg.image,
                                                       caption=msg.text,
                                                       parse_mode='HTML'),
                           reply_markup=keyboard.keyboard)
コード例 #29
0
def call_body_cinema(call):
    id_ = call.message.chat.id
    msg_id = call.message.json['message_id']
    user = User(id_)
    msg = Message(user.state_movie)
    msg.cinemas()
    keyboard = Markup()
    keyboard.cinemas(msg.total_cinemas)
    bot.edit_message_media(chat_id=id_,
                           message_id=msg_id,
                           media=types.InputMediaPhoto(msg.image,
                                                       caption=msg.text,
                                                       parse_mode='HTML'),
                           reply_markup=keyboard.keyboard)
コード例 #30
0
ファイル: ads.py プロジェクト: Pyoss/moscowadvert
 def post(self):
     media_array = []
     for file in self.album:
         media_array.append(types.InputMediaPhoto(file))
     if media_array:
         if len(self.text) < 999:
             media_array[0].caption = self.text
             bot_handlers.send_media_group(config.channel_id, media_array)
         else:
             bot_handlers.send_media_group(config.channel_id, media_array)
             bot_handlers.send_message(config.channel_id, self.text)
     else:
         bot_handlers.send_message(config.channel_id, self.text)
     bot_handlers.send_message(config.admin_id, 'Объявление опубликовано!')