Пример #1
0
def cmd(api, message, owner_id, uploader: VkUpload):
    attach = message.get('attachments')
    reply = message.get('reply_message')
    if len(attach) == 0 and reply is None:
        api.messages.send(
            peer_id=message['peer_id'],
            random_id=0,
            message=
            f"{config.prefixes['error']} Необходимо прикрепить аудиозапись или ответить на сообщение с аудиозаписью.",
            reply_to=message['id'])
        return

    try:
        if reply is not None:
            _type = reply['attachments'][0]['type']
            if reply['attachments'][0].get('audio') is not None:
                audio = reply['attachments'][0]['audio']['url']
            else:
                raise Exception()
        else:
            audio = attach[0]['audio']['url']
    except:
        api.messages.send(
            peer_id=message['peer_id'],
            random_id=0,
            message=
            f"{config.prefixes['error']} Необходимо прикрепить аудиозапись или ответить на сообщение с аудиозаписью.",
            reply_to=message['id'])
        return

    filename = "files/" + os.path.basename(audio).split('?')[0]
    if len(filename.split('.')) < 2: filename += ".mp3"

    r = requests.get(audio)
    with open(filename, 'wb') as f:
        f.write(r.content)

    if os.path.isfile('files/new_audio.wav'): os.remove('files/new_audio.wav')
    os.system(
        f"ffmpeg -i {filename} -acodec pcm_s32le -ar 44100 -ac 1 -b:a 256k files/new_audio.wav"
    )

    uploaded = uploader.audio_message('files/new_audio.wav',
                                      message['peer_id'])['audio_message']
    attach = f"audio_message{uploaded['owner_id']}_{uploaded['id']}"

    os.remove(filename)
    os.remove("files/new_audio.wav")

    api.messages.send(
        peer_id=message['peer_id'],
        random_id=0,
        attachment=attach,
        reply_to=None if message['from_id'] == owner_id else message['id'])
    return
Пример #2
0
 def __send_message(self, peer_id, msg, file=""):
     try:
         upload = VkUpload(self.bot.vk)
         audio = upload.audio_message(
             file, peer_id=peer_id,
             group_id=self.bot.group_id)['audio_message']
     finally:
         os.remove(file)
     self.bot.send_message(
         peer_id,
         msg,
         attachment=f"audio_message{audio['owner_id']}_{audio['id']}")
Пример #3
0
def send_message(uid,
                 chat_id,
                 msg=None,
                 photo=None,
                 documents=None,
                 audio=None,
                 voice=None,
                 video=None,
                 sticker=None):
    try:
        session = get_session(uid)
        api = get_api(uid)
    except IndexError:
        return 0

    # Generate message id like in vk api
    msg_id = randint(1, 9223372036854775700)
    try:
        vchat_id = execute(
            f"select vchat_id from chats where chat_id = {chat_id}")[0][0]
        # if chat is conference
        if vchat_id is None:
            vchat_id = execute(
                f"select peer_id from chats where chat_id = {chat_id}")[0][0]
    except IndexError:
        # If telegram group not binded to vk chat stream
        return

    attachments = []
    if photo or documents or audio or voice or video or sticker:
        if photo:
            attach = photo
        elif documents:
            attach = documents
        elif audio:
            attach = audio
        elif voice:
            attach = voice
        elif video:
            attach = video
        elif sticker:
            attach = sticker
        else:
            attach = None

        uploader = VkUpload(session)
        attach_file = attach.get_file().download()
        if sticker:
            new_name = attach_file.split('.')[0] + '.png'
            try:
                im = Image.open(attach_file).convert("RGBA")
                im.save(new_name, "png")
            except UnidentifiedImageError:
                # Animated sticker
                return
            attach_file = new_name
        attach_file = open(attach_file, 'rb')
        file_name = attach_file.name

        if photo:
            upload_response = uploader.photo_messages(photos=attach_file,
                                                      peer_id=vchat_id)
            for file in upload_response:
                attachments.append(f"photo{file['owner_id']}_{file['id']}")

        if audio:
            _msg = "VK doesn't allow to upload music."
            if msg is None:
                msg = _msg
            else:
                msg += "\n" + _msg

        if voice:
            upload_response = uploader.audio_message(audio=attach_file,
                                                     peer_id=vchat_id)
            audio = upload_response['audio_message']
            attachments.append(
                f"audio_message{audio['owner_id']}_{audio['id']}")

        if documents:
            upload_response = uploader.document_message(attach_file,
                                                        peer_id=vchat_id)
            doc = upload_response['doc']
            attachments.append(f"doc{doc['owner_id']}_{doc['id']}")

        if video:
            video = uploader.video(attach_file, is_private=True)
            attachments.append(f"video{video['owner_id']}_{video['video_id']}")

        if sticker:
            upload_response = uploader.graffiti(attach_file, peer_id=vchat_id)
            graffiti = upload_response['graffiti']
            attachments.append(f"doc{graffiti['owner_id']}_{graffiti['id']}")

        attach_file.close()
        remove(file_name)

        attachments = ','.join(attachments)

    if msg is not None:
        api.messages.send(random_id=msg_id,
                          message=msg,
                          peer_id=vchat_id,
                          attachment=attachments)
    else:
        api.messages.send(random_id=msg_id,
                          peer_id=vchat_id,
                          attachment=attachments)

    api.account.setOffline()