Пример #1
0
def fact(message):
    session = session_manager.active_chat_session(message.chat.id)
    current_session = user_session_manager.get_players(session)[-1]
    if not session or not current_session:
        return

    text, img = None, None
    if message.content_type == 'text':
        text = ' '.join(message.text.split(maxsplit=1)[1:]).strip() or ''
    elif message.caption and '/fact' in message.caption:
        text = message.caption.replace('/fact ', '') or ''

        file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
        img = images.client.upload_from_url(
            'https://api.telegram.org/file/bot{0}/{1}'.format(
                tg_token, file_info.file_path),
            config={
                'album': session.album
            },
            anon=False).get('link')
    else:
        return

    sender = user_manager.get(message.from_user.id)

    if sender == current_session.user and (text or img):
        google_docs.add_data(document_id=session.document,
                             owner=sender.get_name(),
                             text=text.strip(),
                             image=img)
        bot.reply_to(message, session.hashtag())
Пример #2
0
def process_get_file(message, chosen_session):
    user_session = user_session_manager.get(chosen_session)
    if message.document:
        file_info = bot.get_file(message.document.file_id)
    else:
        return

    try:
        file = requests.get(f'https://api.telegram.org/file/bot{tg_token}/{file_info.file_path}', proxies=tg_proxy)
        if not 200 <= int(file.status_code) <= 299:
            raise Exception(f'Cant download save-game. Status code: {file.status_code}')
    except Exception as e:
        error(e)
        bot.reply_to(message, 'Something went wrong!')
        return

    file_name = user_session.game_name()
    with open(file_name, 'wb') as f:
        f.write(file.content)
    save_id = google_drive.upload_file(file_name, file_name, user_session.session.folder)
    os.remove(file_name)

    user_session_manager.write_save(save_id, user_session)

    old, new = user_session_manager.step(user_session.session)
    bot.reply_to(message, 'Your turn came to the end!')
    if new:
        bot.send_message(new.user, f'Your turn!\nDownload the save: {google_drive.get_link(save_id)}')
    else:
        bot.send_message(old.session.chat, f'The round of game is end. Last save: {google_drive.get_link(save_id)}')
Пример #3
0
def video_handler(update, context):
    video = update.message.video
    video_id = video.file_id

    video_meta = bot.get_file(video_id)

    video_meta.download("out.avi")
    video_capture = VideoCapture("out.avi")
    frames = model.inference(video_capture)
    bot.send_video(chat_id=update.message.chat.id, video=frames)
Пример #4
0
def echo(bot, update):
     #my_id = 504335145
    try:
      # print(update)
      user_id = update['message']['chat']['id']
      user_name = update['message']['chat']['first_name'] 

      file_id = bot.get_file(update['message']['photo'][2]['file_id'])
      url =file_id["file_path"]
      r = requests.post("http://shayan2020.ir/Api/Telegram/UploadData.php", data={'url': url,'filename':str(user_id)+'_'+str(user_name)})
      if(r.text =="ok"):
          bot.send_message(chat_id=update.message.chat_id, text="با تشکر از شما برای اضافه کردن عکسی دیگر دگمه /start را مجددا تایپ نمایید")
      else:
          print(r.text)
          bot.send_message(chat_id=update.message.chat_id, text="خطا لطفا مجددا تلاش نمایید")
    except:
        print(update)
        bot.send_message(chat_id=update.message.chat_id, text="لطفا فقط عکس اضافه کنید")
Пример #5
0
def send_prediction_on_photo(bot: Bot, update):
    # Нам нужно получить две картинки, чтобы произвести перенос стиля, но каждая картинка приходит в
    # отдельном апдейте, поэтому в простейшем случае мы будем сохранять id первой картинки в память,
    # чтобы, когда уже придет вторая, мы могли загрузить в память уже сами картинки и обработать их.
    chat_id = update.message.chat_id
    if chat_id not in first_image_file:
        bot.send_message(
            chat_id,
            'Крутяк! Исходная картинка есть, теперь отправляй картинку со стилем'
        )

    # получаем информацию о картинке
    image_info = update.message.photo[-1]
    image_file = bot.get_file(image_info)

    if chat_id in first_image_file:

        # первая картинка, которая к нам пришла станет content image, а вторая style image
        content_image_stream = BytesIO()
        first_image_file[chat_id].download(out=content_image_stream)
        del first_image_file[chat_id]

        style_image_stream = BytesIO()
        image_file.download(out=style_image_stream)
        bot.send_message(
            chat_id,
            'Стиль получен! Пошёл работать.\nМожешь выпить пока чайку, потому что я считаю на cpu('
        )

        output = model.transfer_style(model.open_image(content_image_stream),
                                      model.open_image(style_image_stream))

        # теперь отправим назад фото
        output_stream = BytesIO()
        output.save(output_stream, format='PNG')
        output_stream.seek(0)

        bot.send_message(chat_id, 'TADAAAM!')
        bot.send_photo(chat_id, photo=output_stream)
        print("Sent Photo to user")
    else:
        first_image_file[chat_id] = image_file
Пример #6
0
def photo_handler(update: Update, context: CallbackContext):
    photo = update.message.photo[-1]
    photo_id = photo.file_id
    photo_meta = bot.get_file(photo_id)
    photo_meta.download('image.jpg')

    fen = photo_to_fen('./image.jpg')

    context.user_data["fen"] = fen

    fen_parts = [None] * 6
    fen_parts[0] = fen[:-1]
    board = Board(fen_parts)
    boardGrid = board.board
    boardImg = DrawImage(boardGrid, 'png', './', 'result')
    boardImg.create()
    boardImg.to_image()

    stockfish_engine.set_fen_position(fen)

    chat_id = update.message.chat.id
    bot.send_photo(chat_id,
                   photo=open('result.png', 'rb'),
                   caption="Here is detected chessboard configuration")