コード例 #1
0
async def send_welcome(message: types.Message):
    # So... At first I want to send something like this:
    await message.reply("Do you want to see many pussies? Are you ready?")

    # Wait a little...
    await asyncio.sleep(3)

    # Good bots should send chat actions...
    await types.ChatActions.upload_photo()

    # Create media group
    media = types.MediaGroup()

    # Attach local file
    media.attach_photo(types.InputFile('data/cat.png'), 'Cat!')
    # More local files and more cats!
    media.attach_photo(types.InputFile('data/cats.jpg'), 'More cats!')

    # You can also use URL's
    # For example: get random puss:
    #media.attach_photo('https://avatars.mds.yandex.net/get-zen_gallery/4001064/pub_605cd86ed15daa7344cf4ae7_605cd927d15daa7344cfe3a3/scale_1200', 'Image')

    # And you can also use file ID:
    # media.attach_photo('<file_id>', 'cat-cat-cat.')

    # Done! Send media group
    # await message.reply_media_group(media=media)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(bot.send_message(CHANNEL_ID, media))
コード例 #2
0
async def process_styles_command(message: types.Message):
    args = message.get_args()
    styles = list(interface.examples_styles_images())
    n_styles = len(styles)
    if args == "":
        return await message.reply(
            'Формат команды: "/styles n", где n от 0 до {}'.format(n_styles -
                                                                   1),
            reply=False)
    if args == "all" and False:
        await types.ChatActions.upload_photo()
        media = types.MediaGroup()
        for st, im in styles:
            media.attach_photo(types.InputFile(st), 'Стиль')
            media.attach_photo(types.InputFile(im), 'Результат')
        return await message.reply_media_group(media=media, reply=False)

    if not is_int(args):
        return await message.reply(
            'Формат команды: "/styles n", где n от 0 до {}'.format(n_styles -
                                                                   1),
            reply=False)

    s = int(args)
    if s < 0 or s >= n_styles:
        return await message.reply(
            'Номер стиля может быть только от от 0 до {}'.format(n_styles - 1),
            reply=False)
    await types.ChatActions.upload_photo()
    media = types.MediaGroup()
    media.attach_photo(types.InputFile(interface.example_content()), 'Контент')
    media.attach_photo(types.InputFile(styles[s][0]), 'Стиль')
    media.attach_photo(types.InputFile(styles[s][1]), 'Результат')
    await message.reply_media_group(media=media, reply=False)
コード例 #3
0
async def send_welcome(message: types.Message):
    # So... At first I want to send something like this:
    await message.reply("Do you want to see many pussies? Are you ready?")

    # And wait few seconds...
    await asyncio.sleep(1)

    # Good bots should send chat actions. Or not.
    await types.ChatActions.upload_photo()

    # Create media group
    media = types.MediaGroup()

    # Attach local file
    media.attach_photo(types.InputFile('data/cat.jpg'), 'Cat!')
    # More local files and more cats!
    media.attach_photo(types.InputFile('data/cats.jpg'), 'More cats!')

    # You can also use URL's
    # For example: get random puss:
    media.attach_photo('http://lorempixel.com/400/200/cats/', 'Random cat.')

    # And you can also use file ID:
    # media.attach_photo('<file_id>', 'cat-cat-cat.')

    # Done! Send media group
    await message.reply_media_group(media=media)
コード例 #4
0
async def upload_track(bot,
                       path,
                       thumb_path,
                       title,
                       performer,
                       duration=None,
                       tries=0):
    if tries > 3:
        shutil.rmtree(path.rsplit('/', 1)[0])
        raise RuntimeError("can't upload track")
    try:
        msg = await bot.send_audio(
            chat_id=-1001246220493,
            audio=types.InputFile(path),
            thumb=types.InputFile(thumb_path),
            title=title,
            performer=performer,
            duration=duration,
        )
    except exceptions.RetryAfter as e:
        print(f"flood control exceeded, sleeping for {e.timeout + 10} seconds")
        await sleep(e.timeout + 10)
        return await upload_track(bot, path, title, performer, duration,
                                  tries + 1)
    except exceptions.TelegramAPIError:
        await sleep(5)
        return await upload_track(bot, path, title, performer, duration,
                                  tries + 1)
    return msg
コード例 #5
0
async def readme_handler(message: types.Message, state: FSMContext):
    user_data = await state.get_data()
    await message.answer(
        'Я могу обработать фото таким образом, '
        'чтобы стилистически оно стало похоже на другое изображение (стиль).',
        reply_markup=ReplyKeyboardRemove())
    await types.ChatActions.upload_photo()
    flower_id = 4
    if flower_id in examples[0]:
        media = types.MediaGroup()
        media.attach_photo(
            types.InputFile(examples[0][flower_id][ImageTypes.CONTENT]),
            caption='Например, в качестве фото можно использовать цветы.')

        media.attach_photo(
            types.InputFile(examples[0][flower_id][ImageTypes.STYLE]),
            caption='А в качестве стиля акварельный рисунок цветов.')
        media.attach_photo(
            types.InputFile(examples[0][flower_id][ImageTypes.RESULT]),
            caption='В результате получатся цветы с исходного фото, '
            'но как буд-то нарисованные акварелью.')
        await message.answer_media_group(media)
    await message.answer(
        'Обычно в качестве стиля используют '
        'либо картинку с содержанием похожим на исходное фото, но оформленным иначе, '
        'либо красивую текстуру.\n\n'
        'Подробную информацию о моей реализации смотрите на '
        f'{md.hlink("github", "https://github.com/ChumankinYuriy/heroku_chust_bot")}.',
        reply_markup=init_main_keyboard(user_data),
        disable_web_page_preview=True,
        parse_mode=types.ParseMode.HTML)
コード例 #6
0
async def cancel_payment(call: CallbackQuery, state: FSMContext):
    data = await state.get_data()
    payment: PaymentForQiwi = data.get("payment")
    try:
        payment.check_payment()
    except NoPaymentFound:
        await call.message.answer("Не найден платеж!")
        return
    except NotEnoughMoney:
        await call.message.answer("Не хватает средств!")
        return
    else:
        await call.message.answer("Все успешно оплачено!")
        rand_item = randint(1, 2)
        if rand_item == 1:
            await call.message.answer_document(
                types.InputFile("data/Rostov-na-donu.png"),
                caption="Вот ваша секретная покупка!")
        else:
            await call.message.answer_document(
                types.InputFile("data/Rostov-na-donu_1.png"),
                caption="Вот ваша секретная покупка!")
        await state.set_state("choose a product")
    await call.message.delete_reply_markup()
    await state.finish()
コード例 #7
0
async def show_what_you_can(message: Message):
    # первое сообщение пользователю:
    await bot.send_message(chat_id=message.from_user.id,
                           text="Вот, что я могу:")

    # Create media group
    media_content, media_style, media_finish = types.MediaGroup(
    ), types.MediaGroup(), types.MediaGroup()
    media_h2z, media_z2h = types.MediaGroup(), types.MediaGroup()
    media_content.attach_photo(types.InputFile(r"image_for_bot/karabash.jpg"))
    media_style.attach_photo(types.InputFile(r"image_for_bot/shanghai.jpg"))
    media_finish.attach_photo(types.InputFile(r"image_for_bot/result_nst.jpg"))
    media_h2z.attach_photo(types.InputFile(r"image_for_bot/horse2zebra.jpg"))
    media_z2h.attach_photo(types.InputFile(r"image_for_bot/zebra2horse.jpg"))

    # Wait a little...
    await asyncio.sleep(1)
    # отправляем картинку-основу
    await bot.send_message(
        chat_id=message.from_user.id,
        text=
        "Я умею переносить стиль одной картинки на другую. Приведу простой пример"
        "\nВот картинка-основа \nОжидайте...")
    # для того, чтобы ползунок вверху писал: "Отправляет фото...>>>"
    await types.ChatActions.upload_photo()
    await bot.send_media_group(chat_id=message.from_user.id,
                               media=media_content)

    # отправляем картинку-стиль
    await asyncio.sleep(4)
    await bot.send_message(chat_id=message.from_user.id,
                           text="Вот картинка-стиль \nОжидайте...")
    await types.ChatActions.upload_photo()
    await bot.send_media_group(chat_id=message.from_user.id, media=media_style)

    # отправляем картинку-результат
    await asyncio.sleep(2)
    await bot.send_message(chat_id=message.from_user.id,
                           text="А вот то, что мы можем получить \n")
    await types.ChatActions.upload_photo()
    await bot.send_media_group(chat_id=message.from_user.id,
                               media=media_finish)

    # отправляем преобразование лошадь-зебра
    await asyncio.sleep(4)
    await bot.send_message(chat_id=message.from_user.id,
                           text="Также умею превращать лошадей в зебр...")
    await types.ChatActions.upload_photo()
    await bot.send_media_group(chat_id=message.from_user.id, media=media_h2z)

    # отправляем преобразование зебра-лошадь
    await asyncio.sleep(4)
    await bot.send_message(chat_id=message.from_user.id,
                           text="... и зебр в лошадей...")
    await types.ChatActions.upload_photo()
    await bot.send_media_group(chat_id=message.from_user.id, media=media_z2h)

    await asyncio.sleep(4)
    await bot.send_message(chat_id=message.from_user.id, text=text_instruction)
コード例 #8
0
async def message_for_all(msg: types.Message):
    # получаем имена колонок
    get_column_names = cur.execute("SELECT * FROM game_team_3 LIMIT 1")
    col_name = [i[0] for i in get_column_names.description]

    cur.execute(
        """SELECT team_name, {}, {}, {}, win_point, wpoint_duel FROM game_team_3 
                    ORDER BY win_point DESC, wpoint_duel DESC, sum_point DESC, sum_wpoint DESC, sum_time ASC;"""
        .format(col_name[8], col_name[9], col_name[10]))
    res_tab = cur.fetchall()
    rows = [1, 2, 3]
    cols = [
        'Команда', col_name[8], col_name[9], col_name[10], 'Победные очки',
        'Разница в счёте'
    ]
    colors = [[("Linen" if c in [0, 4] else "white") for c in range(len(cols))]
              for r in range(len(rows))]
    fig = plt.figure(figsize=(len(cols), len(rows) * 0.25), dpi=120)
    ax = plt.subplot()
    ax.set_axis_off()
    table_state = ax.table(cellText=res_tab,
                           rowLabels=rows,
                           colLabels=cols,
                           cellLoc='center',
                           loc='center',
                           rowLoc='center',
                           cellColours=colors,
                           rowColours=["Wheat"] * len(rows),
                           colColours=["Wheat"] * len(cols))
    table_state.auto_set_font_size(False)
    table_state.set_fontsize(7)
    plt.tight_layout(pad=0.2)
    plt.savefig('table_result.jpg')
    for i in all_players:
        await bot.send_photo(i, types.InputFile('table_result.jpg'))
    await bot.send_photo(id_chat, types.InputFile('table_result.jpg'))
    cur.execute(
        "SELECT team_name FROM game_team_3 ORDER BY win_point DESC, wpoint_duel DESC, sum_point DESC, sum_wpoint DESC, sum_time ASC "
    )
    res = cur.fetchall()
    cur.execute(
        "SELECT team_name, sum_time FROM game_team_1 ORDER BY sum_time ASC LIMIT 1"
    )
    speedy = cur.fetchone()
    speedy_name, speedy_time = speedy[0], speedy[1]
    mes = emojize(
        ':trophy:Внимание!!!:trophy:\n Итоги игры\n'
        ':Santa_Claus:Новогодний:evergreen_tree:Онлайн:evergreen_tree:Квиз:Santa_Claus::\n\n'
        ':1st_place_medal:Первое место - :party_popper:команда "{}":party_popper:\n'
        ':2nd_place_medal:Второе место - :confetti_ball:команда "{}":confetti_ball:\n'
        ':3rd_place_medal:Третье место - :balloon:команда "{}":balloon:\n\nP.S.\n'
        ':high_voltage:В номинации "Самый быстрый" побежает:\n:racing_car:команда "{}":racing_car:\n'
        'На 35 вопросов команда потратила всего лишь {} мин. {} сек., это в среднем по {} сек. на вопрос!'
        .format(res[0][0], res[1][0], res[2][0], speedy_name,
                str(int(speedy_time // 60)), str(int(speedy_time % 60)),
                str(int(speedy_time // 35))))
    await send_for_list(all_players, mes, 'text', False, False)
コード例 #9
0
ファイル: choice.py プロジェクト: kankeinai/Python_study
def anime_media_gen(result_1, result_2):
    media = types.MediaGroup()
    media.attach_photo(
        types.InputFile(save_image(result_1[0][1], result_1[0][3])),
        result_1[0][1])
    media.attach_photo(
        types.InputFile(save_image(result_2[0][1], result_2[0][3])),
        result_2[0][1])
    return media
コード例 #10
0
async def websocket_conn(session, ws_url):
    async with session.ws_connect(ws_url) as ws:
        logger.info(f"Client connected to {ws_url}")

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                if msg.data == 'close cmd':
                    await ws.close()
                    break
                else:
                    await ws.send_str(msg.data)
            elif msg.type in (aiohttp.WSMsgType.CLOSED,
                              aiohttp.WSMsgType.ERROR):
                break
            logger.info(f"Message received: {msg.data}")
            if msg.data != 'Done!!':
                try:
                    logger.info(f'msg.data!=Done###{msg.data}###')
                    params = json.loads(msg.data)
                    message_id = params["message_id"]
                    predit_video = params["predit_video"]
                    chat_id = params["chat_id"]
                    cam = params["cam"]
                    cam_video = params["cam_video"]
                    logger.info(
                        f'message_id:{message_id}, predit_video:{predit_video}'
                    )
                except Exception as e:
                    logger.info(e)

            else:
                t = time.time()
                logger.info(
                    f"detected during {t - ws_post[types.User.get_current().id]['start_time']:.2f} seconds."
                )
                try:
                    await bot.send_message(
                        chat_id,
                        f"detected during {t - ws_post[types.User.get_current().id]['start_time']:.2f} seconds.",
                        reply_to_message_id=message_id)
                    await bot.send_document(chat_id,
                                            types.InputFile(predit_video),
                                            reply_to_message_id=message_id)
                    if cam:
                        try:
                            await bot.send_document(
                                chat_id,
                                types.InputFile(cam_video),
                                reply_to_message_id=message_id)
                        except Exception as e:
                            logger.error(f'cam video: {e}')
                    await ws.close()
                    ws_post.pop(types.User.get_current().id)

                except Exception as e:
                    logger.error(e)
コード例 #11
0
def create_media(paths: Tuple[str, str, str, str]) -> types.MediaGroup:
    media = types.MediaGroup()

    media.attach_photo(types.InputFile(paths[3]), caption='Average histogram')
    media.attach_photo(types.InputFile(paths[0]),
                       caption='R channel histogram')
    media.attach_photo(types.InputFile(paths[1]),
                       caption='B channel histogram')
    media.attach_photo(types.InputFile(paths[2]),
                       caption='G channel  histogram')
    return media
コード例 #12
0
async def end_session(message: types.Message):
    """
    This handler will be called when user sends /example command
    """
    # send result to the user:in
    await types.ChatActions.upload_photo()
    media = types.MediaGroup()
    media.attach_photo(types.InputFile('example_content_img.jpg'),
                       'Content Image')
    media.attach_photo(types.InputFile('example_style_img.jpg'), 'Style Image')
    media.attach_photo(types.InputFile('example_output_img.jpg'),
                       'Output Image')
    await message.answer(messages['example'])
    await message.answer_media_group(media=media)
コード例 #13
0
ファイル: photo_utils.py プロジェクト: PacketCat/cumzoner
async def fix_size(pictures):
    resulting_list = []
    for picture in pictures:
        if not isinstance(picture, types.InputFile):
            print('Жопа в говне size', picture)
            continue
        try:

            if picture.get_file().closed:
                if isinstance(picture.get_file(), types.input_file._WebPipe):
                    fileo = types.InputFile.from_url(
                        picture.get_file().url).get_file()
                    print(1, fileo)
                else:
                    fileo = open(picture.get_file().name, 'rb')
                print(fileo, 2)
            else:
                fileo = picture.get_file()
            if isinstance(fileo, types.input_file._WebPipe):
                fileo = io.BytesIO(await (fileo.read()))
            fileo.seek(0)
            img_obj = Image.open(fileo)
        except UnidentifiedImageError:
            resulting_list.append(open(picture.get_file().name, 'rb'))
            continue
        ext = picture.filename.split('.')[-1]
        length = io.BytesIO()
        img_obj.save(length, ext)
        length = length.tell()
        if length < 1024**2 * 10:
            resulting_list.append(open(picture.get_file().name, 'rb'))
        else:
            res = io.BytesIO()
            img_obj.reduce(1 - (1024**2 * 10 / length)).save(res,
                                                             ext,
                                                             optimize=True)
            print(res.tell() / 1024**2)
            res.seek(0)
            resulting_list.append(res)
            if len(resulting_list) == 1:
                return types.InputFile(resulting_list[0])
            elif len(resulting_list) > 1:
                return types.MediaGroup([
                    types.InputMedia(types.InputFile(x))
                    for x in resulting_list
                ])
            else:
                print('achko')
            return
コード例 #14
0
ファイル: cart_handlers.py プロジェクト: sn1ch/tlbaku
async def get_prev(call: types.CallbackQuery, state: FSMContext):
    await bot.answer_callback_query(call.id)
    try:
        async with state.proxy() as data:
            if data['page'] > 1:
                data['page'] -= 1
                product_id = list(data['products'].keys())[data['page'] - 1]
                values = list(data['products'].values())[data['page'] - 1]
                product = await Botbakuadmin_product.filter(id=product_id)
                totals_sum = await total_sum(data['products'])
                cb_page_text = f'{data["page"]}/{len(data["products"])}'
                await types.ChatActions.upload_photo()
                photo = types.InputFile(os.path.join(BASE_DIR, product[0].img))
                media = types.InputMediaPhoto(
                    media=photo,
                    caption=f'<b>{product[0].name}</b>',
                    parse_mode='HTML')
                await call.message.edit_media(media=media,
                                              reply_markup=get_cart_kb(
                                                  cb_page_text, values,
                                                  totals_sum))
            else:
                pass
    except KeyError:
        await call.answer(text='OPS. Похоже корзина пуста')
コード例 #15
0
async def send_act(message: types.Message, state: FSMContext):
    user = Datafunc.get_user(message.from_user.id)
    if (user.is_payed) == False and ((user.id in ADMINS_ID) == False):
        await message.answer(TEXTS["pay_please"])  
        return

    data = await state.get_data()

    if ('dict_user_pictures' in data.keys()) == False: #Проверка, что хранилище создано
        await state.update_data(dict_user_pictures={})
        data = await state.get_data()
    
    if (str(user.id) in data['dict_user_pictures'].keys()) == False: #Проверка, что ID пользователя, который написал нет в хранилище
        data['dict_user_pictures'][f'{user.id}'] = {'truth' : [], 'actions' : []}
        await state.update_data(dict_user_pictures=data['dict_user_pictures'])

    acts = [pic.id for pic in Datafunc.get_acts()] #Генератор листов. Создаем лист только из ID полученных картинок
    sends_acts = list(set(acts) - set(data['dict_user_pictures'][f'{user.id}']['actions']))

    if (len(sends_acts) == 0): #Обнуляем лист, если кончились картинки
        sends_acts = acts
        data['dict_user_pictures'][f'{user.id}']['actions'].clear()
        await state.update_data(dict_user_pictures=data['dict_user_pictures'])

    randomik = random.randint(0, len(sends_acts)-1) #Отправляем случайную картинку, из тех, что не было
    pic = Datafunc.get_pic_act(sends_acts[randomik])
    await message.answer_photo(types.InputFile(pic.filename))

    data['dict_user_pictures'][f'{user.id}']['actions'].append(sends_acts[randomik]) # Обновляем список отправленных картинок
    await state.update_data(dict_user_pictures=data['dict_user_pictures'])
コード例 #16
0
ファイル: poster_creation.py プロジェクト: Lamroy95/mapoc-bot
async def send_city_map(c: types.CallbackQuery, button: kbd.Button, manager: DialogManager):
    city_name = manager.context.data("city")
    city_img_path = FILES_PATH / "img" / (city_name + ".png")
    await c.message.answer_photo(
        types.InputFile(city_img_path),
        caption=f"Save this image, crop the area that you need and {markdown.hbold('send cropped image back')}"
    )
コード例 #17
0
ファイル: poster_creation.py プロジェクト: Lamroy95/mapoc-bot
async def area_image_handler(m: types.Message, dialog: Dialog, manager: DialogManager):
    city_select: kbd.Select = manager.dialog().find("city_select")
    city_name = city_select.get_checked(manager)

    if not m.photo:
        geojson_path = get_city_gjs_path(city_name)
        manager.context.set_data("geojson", geojson_path)
        await m.reply("There's no photo in your message.\nSkipping.")
        await dialog.next(manager)
        return

    area_img = BytesIO()
    await m.photo[-1].download(area_img, seek=True)

    try:
        geojson_path, selected_image_bytes = await run_blocking(area_to_geojson, city_name, area_img)
        manager.context.set_data("is_area_specified", True)
        await m.reply_photo(types.InputFile(selected_image_bytes), caption="Defined area")
    except ValueError as e:
        logger.exception(e)
        geojson_path = get_city_gjs_path(city_name)
        manager.context.set_data("is_area_specified", False)
        await m.reply("Can't define area, error occured. Using full map")

    manager.context.set_data("geojson", geojson_path)
    await dialog.next(manager)
コード例 #18
0
ファイル: edit.py プロジェクト: gibbsnich/bot_na_rayone
async def edit_house(message: types.Message, state: FSMContext):
    poi = (await state.get_data())['poi']
    houses = await db.get_houses()
    houses.sort(key=lambda h: poi.location.distance(h.location))
    houses = houses[:3]

    # Prepare the map
    map_file = get_map([h.location for h in houses], ref=poi.location)
    # Prepare the keyboard
    kbd = types.InlineKeyboardMarkup(row_width=1)
    for i, house in enumerate(houses, 1):
        prefix = '✅ ' if house == poi.house else ''
        kbd.add(
            types.InlineKeyboardButton(
                f'{prefix} {i} {house.name}',
                callback_data=HOUSE_CB.new(hid=house.key)))
    kbd.add(
        types.InlineKeyboardButton(tr(('editor', 'cancel')),
                                   callback_data='cancel_attr'))

    # Finally send the reply
    await delete_msg(message, state)
    if map_file:
        await message.answer_photo(types.InputFile(map_file.name),
                                   caption=tr(('editor', 'house')),
                                   reply_markup=kbd)
        map_file.close()
    else:
        await message.answer(tr(('editor', 'house')), reply_markup=kbd)
コード例 #19
0
 async def patched_func(*args, **kwargs):
     new_args = list(args)
     try:
         new_args[1] = types.InputFile(args[1]) if os.path.exists(args[1]) else args[1]
     except TypeError:  # file argument already InputFile type
         pass
     return await initial_method(*new_args, **kwargs)
コード例 #20
0
ファイル: error.py プロジェクト: NotFoundError/SophieBot
async def report_error(event, telethon=False):
    if telethon is True:
        msg = event
        chat_id = msg.chat_id
        lib = 'Telethon'
    else:
        msg = event.message
        chat_id = msg.chat.id
        lib = 'Aiogram'

    date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    logger.error("Error: " + date)
    logger.error("Lib: " + lib)

    if telethon is True:
        logger.error(traceback.format_exc())

    if DEBUG_MODE is True:
        await msg.reply(str(sys.exc_info()[1]))
        return

    new = {'error': str(sys.exc_info()[1]), 'date': datetime.datetime.now()}
    mongodb.errors.insert_one(new)

    text = "<b>Sorry, I encountered a error!</b>\n"
    link = "<a href=\"https://t.me/YanaBotGroup\">Sophie support chat</a>"
    text += f"If you wanna you can report it - just forward this file to {link}.\n"
    text += "I won't log anything except the fact of error and date\n"

    ftext = "Sophie error log file."
    ftext += "\n______________________\n"
    ftext += "\nNotice:\nThis file uploaded ONLY here, we logged only fact of error and date, "
    ftext += "we respect your privacy, you may not report this error if you've "
    ftext += "any confidential data here, noone will see your data\n\n"
    ftext += "\nDate: " + date
    ftext += "\nLib: " + lib
    ftext += "\nGroup ID: " + str(chat_id)
    ftext += "\nSender ID: " + str(msg.from_user.id if lib ==
                                   "Aiogram" else msg.from_id)
    ftext += "\n\nRaw update text:\n"
    ftext += str(event)
    ftext += "\n\nFormatted update text:\n"
    ftext += str(ujson.dumps(msg, indent=2))
    ftext += "\n\nTraceback info:\n"
    ftext += str(traceback.format_exc())
    ftext += "\n\nError text:\n"
    ftext += str(sys.exc_info()[1])

    command = "git log --pretty=format:\"%an: %s\" -5"
    ftext += "\n\n\nLast 5 commits:\n"
    ftext += await term(command)

    await bot.send_document(chat_id,
                            types.InputFile(io.StringIO(ftext),
                                            filename="Error.txt"),
                            caption=text,
                            reply_to_message_id=msg.message_id
                            if lib == "Aiogram" else msg.message.id)

    return
コード例 #21
0
async def get_logs(message: types.Message):
    check_id(message.from_user)
    logger.info(f"{message.from_user.username} do getlog command")
    if message.from_user.id == ADMIN_ID:
        try:
            int(message.text[9:])
        except ValueError:
            await message.chat.do(types.ChatActions.UPLOAD_DOCUMENT)
            await message.reply_document(types.InputFile(f"logs/current.log"),
                                         caption="The logs file",
                                         reply_markup=key)
        else:
            await message.chat.do(types.ChatActions.TYPING)
            logs = (open(f"logs/current.log",
                         "r").readlines())[-int(message.text[9:]):]
            log = str()
            for i in logs:
                log += i
            msg = markdown.text(markdown.italic("logs:"),
                                markdown.code(log),
                                sep="\n")
            try:
                await message.reply(msg,
                                    parse_mode=ParseMode.MARKDOWN,
                                    reply_markup=key)
            except MessageIsTooLong:
                await message.reply(markdown.bold("Too much logs ! ❌"),
                                    reply_markup=key)
コード例 #22
0
async def state_go(message: types.Message):
    state = dp.current_state(user=message.from_user.id)

    if len(message.photo) == 0:
        if is_int(message.text):
            s = int(message.text)
            styles = interface.style_images()
            n_styles = len(styles)
            if s < 0 or s >= n_styles:
                return await message.reply(
                    'Номер стиля может быть только от 0 до {}.'.format(
                        n_styles - 1),
                    reply=False)
            dstyle = 'data/{}_style.jpg'.format(message.from_user.id)
            shutil.copy(styles[s], dstyle)

            await types.ChatActions.upload_photo()
            media = types.MediaGroup()
            media.attach_photo(types.InputFile(dstyle),
                               'Вы выбрали такой стиль.')
            await message.reply_media_group(media=media, reply=False)
        else:
            return await message.reply(
                'Вы не загрузили стилевую картинку... Загрузите, пожалуйста.',
                reply=False)
    else:
        await message.photo[-1].download('data/{}_style.jpg'.format(
            message.from_user.id))
    await state.set_state(AppStates.STATE_LOAD_CONTENT[0])
    await message.reply('Загрузи контентную картинку.', reply=False)
コード例 #23
0
async def state_style(message: types.Message):
    state = dp.current_state(user=message.from_user.id)

    if len(message.photo) == 0:
        return await message.reply(
            'Вы не загрузили контентную картинку... Загрузите, пожалуйста.',
            reply=False)

    path_content = 'data/{}_content.jpg'.format(message.from_user.id)
    path_style = 'data/{}_style.jpg'.format(message.from_user.id)
    path_output = 'data/{}_output.jpg'.format(message.from_user.id)

    await message.photo[-1].download(path_content)
    await do_style(path_style, path_content, path_output)

    await types.ChatActions.upload_photo()
    media = types.MediaGroup()
    media.attach_photo(types.InputFile(path_output), 'Вот результат!')

    await message.reply_media_group(media=media, reply=False)
    await state.reset_state()
    await message.reply("Набери /go или /gan, чтобы начать снова.",
                        reply=False)

    await gccollect()
コード例 #24
0
async def send_db_to_admin():
    path_and_name = "data/main.db"

    date_and_time = time.ctime(os.path.getctime(path_and_name))

    await bot.send_document(chat_id=ADMINS[0], document=types.InputFile(path_and_name),
                            caption=f"Время создания:\n{date_and_time}")
コード例 #25
0
async def tutorial_1(message: types.Message):
    if isinstance(message, types.CallbackQuery):
        response = await render_template(message.from_user.id, "tutorial_part_1")
        await tutorial_callback_query(
            message,
            response,
            media=os.path.join(config.BASE_DIR, "data/i17obot-1.mp4"),
            keyboards=[("Próximo >>", "tutorial_2")],
        )
        return

    await types.ChatActions.upload_video()

    keyboard_markup = types.InlineKeyboardMarkup()
    keyboard_markup.row(
        types.InlineKeyboardButton("Próximo >>", callback_data="tutorial_2"),
    )

    response = await render_template(message.from_user.id, "tutorial_part_1")

    await bot.send_animation(
        chat_id=message.chat.id,
        animation=types.InputFile(os.path.join(config.BASE_DIR, "data/i17obot-2.mp4")),
        caption=response,
        parse_mode="markdown",
        reply_markup=keyboard_markup,
    )
コード例 #26
0
async def calc_stat(num_list):
    point_list = []
    for i in num_list.split(','):
        point_list.append('point_' + i)
    point_str = ', '.join(point_list)
    cur.execute("""SELECT team_name, {}, sum_point, sum_wpoint 
            FROM game_team_1 ORDER BY sum_point DESC, sum_wpoint DESC, sum_time ASC;"""
                .format(point_str))
    res = cur.fetchall()
    rows = range(1, len(res) + 1)
    cols = ['name'] + point_list + ['sum_point', 'sum_wpoint']
    colors = [[("Linen" if c == 0 or c == len(cols) - 1 or c == len(cols) - 2
                else "white") for c in range(len(cols))]
              for r in range(len(rows))]
    fig = plt.figure(figsize=(len(cols) * 0.8, len(rows) * 0.24), dpi=120)
    ax = plt.subplot()
    ax.set_axis_off()
    ax.table(cellText=res,
             rowLabels=rows,
             colLabels=cols,
             cellLoc='center',
             loc='center',
             rowLoc='center',
             cellColours=colors,
             rowColours=["Wheat"] * len(rows),
             colColours=["Wheat"] * len(cols))
    plt.tight_layout(pad=0.2)
    plt.savefig('table_stat.jpg')
    for i in players:
        await bot.send_photo(i, types.InputFile('table_stat.jpg'))
コード例 #27
0
async def screenshot(message: types.Message):
    if message.text.startswith('http://') or message.text.startswith(
            'https://'):
        await bot.send_message(chat_id=message.chat.id,
                               text="Wait a second...")

        url = message.text
        picture_path = "image.png"
        try:
            driver.get(url)
        except:
            return SendMessage(chat_id=message.chat.id, text="Incorrect link")

        window_size = driver.get_window_size()
        width = driver.execute_script(
            'return document.body.parentNode.scrollWidth')
        height = driver.execute_script(
            'return document.body.parentNode.scrollHeight')
        driver.set_window_size(width, height)

        await message.reply(text="taking a website screenshot...")

        driver.find_element_by_tag_name('body').screenshot(picture_path)
        driver.set_window_size(window_size['width'], window_size['height'])

        await message.reply(text="Done")
        return SendDocument(chat_id=message.chat.id,
                            document=types.InputFile(picture_path),
                            caption=url)
    return SendMessage(chat_id=message.chat.id, text="Incorrect link")
コード例 #28
0
async def show_styles_handler(message: types.Message, state: FSMContext):
    user_data = await state.get_data()
    await types.ChatActions.upload_photo()
    media = types.MediaGroup()
    # Флаг указывающий, следует ли расставить картинки стилей в определённом здесь порядке.
    CUSTOM_ORDER = True
    if CUSTOM_ORDER:

        def attach(indexes):
            for idx in indexes:
                media.attach_photo(types.InputFile(
                    default_styles[idx]['file']),
                                   caption=default_styles[idx]['name'])

        attach([2, 3])
        await message.answer_media_group(media)
        media = types.MediaGroup()
        attach([13, 4, 1, 7, 8, 10, 12, 9, 11])
        await message.answer_media_group(media)
    else:
        counter = 0
        for style_id, style in default_styles.items():
            # 9 картинок красиво собираются в квадрат.
            if counter == 9:
                await message.answer_media_group(media)
                media = types.MediaGroup()
                counter = 0
            media.attach_photo(types.InputFile(style['file']),
                               caption=style['name'])
            counter += 1
        await message.answer_media_group(media)
    await message.answer(
        'Это только список стандартных стилей. '
        'Перед обработкой вы можете выбрать в качестве стиля любое понравившееся изображение в вашем телефоне.',
        reply_markup=init_main_keyboard(user_data))
コード例 #29
0
async def fbanned_list(message, strings, status, chat_id, chat_title, fed,
                       *args, **kwargs):
    fbanned = mongodb.fbanned_users.find({'fed_id': fed['fed_id']})
    if not fbanned or fbanned.count() == 0:
        await message.reply(
            strings['no_fbanned_in_fed'].format(fed_name=fed['fed_name']))
        return
    text = strings['fbanned_list_header'].format(fed_name=fed['fed_name'],
                                                 fed_id=fed['fed_id'])
    for user_id in fbanned:
        user_id = user_id['user']
        user = mongodb.user_list.find_one({'user_id': user_id})
        fbanned = mongodb.fbanned_users.find_one({
            'fed_id': fed['fed_id'],
            'user_id': user_id
        })
        if user:
            text += f"\n {user['first_name']} "
            if 'last_name' in user and user['last_name']:
                text += user['last_name']
            text += f" ({user_id})"
        else:
            text += f'\n ({user_id})'
        if fbanned and 'reason' in fbanned:
            text += ': ' + fbanned['reason']
    await message.answer_document(types.InputFile(io.StringIO(text),
                                                  filename="fbanned_list.txt"),
                                  strings['fbanned_list_header'].format(
                                      fed_name=fed['fed_name'],
                                      fed_id=fed['fed_id']),
                                  reply=message.message_id)
コード例 #30
0
async def message_handler(message: types.Message, state: FSMContext):
    lang = language(message.chat.id)
    await state.finish()
    code = message.text
    if not os.path.exists(f'export/text/{code}.txt'):
        await message.answer(lang['warning_chat_not_exist'])
        return
    try:
        await bot.send_document(message.chat.id,
                                types.InputFile(f'export/text/{code}.txt', f'{code} text messages.txt'))
    except FileNotFoundError:
        await message.answer(lang['warning_chat_has_not_text'])
    await sleep(.05)
    try:
        with open(f'export/media/{code}.txt', 'r') as f:
            data = f.readlines()
        for file in data:
            filetype, fileid = file[:-1].split('/')
            try:
                if filetype == 'photo':
                    await bot.send_photo(message.chat.id, fileid)
                elif filetype == 'video':
                    await bot.send_video(message.chat.id, fileid)
                elif filetype == 'document':
                    await bot.send_document(message.chat.id, fileid)
            except Exception as e:
                await message.answer(str(e))
            await sleep(.05)
    except FileNotFoundError:
        await message.answer(lang['warning_chat_has_not_media'])