Exemple #1
0
    def send_gallery(self, dict_of_dicts_of_pics, text):
        self.send_text(text)
        long_sleep()
        cnt = 0
        for k, dict_of_pics in dict_of_dicts_of_pics.items():
            list_of_items_in_one_group = list()

            for item in sorted(dict_of_pics.items(), key=lambda item: item[0]):
                if item[1]['type'] == 'pic':
                    list_of_items_in_one_group.append(
                        telegram.InputMediaPhoto(item[1]['url']))
                elif item[1]['type'] == 'video':
                    list_of_items_in_one_group.append(
                        telegram.InputMediaVideo(item[1]['url']))
                else:
                    logging.error('Unkown item in gallery.')
                    return SupplyResult.SKIP_FOR_NOW

            try:
                self.telegram_bot.send_media_group(
                    chat_id=self.t_channel,
                    media=list_of_items_in_one_group,
                    timeout=66)
                logging.info('Successful gallery sent.')
            except Exception as e:
                logging.error('Gallery sent failed.')
            cnt += 1
            long_sleep(cnt + 1)
        return SupplyResult.SUCCESSFULLY
Exemple #2
0
def save_in_telegram(twitter_msg, context):
    """
    Saves a tweet and video in Telegram (with a archive.is link)
    :param twitter_msg: Twitter Status Object
    :param context: Telegram bot context
    :return: nothing
    """
    tweet_url = "https://www.twitter.com/{}/status/{}".format(
        twitter_msg.user.screen_name, twitter_msg.id)
    logging.info("Saving tweet {}".format(tweet_url))
    if twitter_msg.media is not None:
        saved_url = archive.save_in_archive(tweet_url)
        config.save_config()
        location = tweets.get_geo(twitter_msg)
        caption = "{} {}".format(saved_url, location)
        msg = None
        if saved_url is not None:
            # Individual file
            if len(twitter_msg.media) == 1:
                m = twitter_msg.media[0]
                if m.type == "photo":
                    msg = context.bot.send_photo(config.config["telegram"]["chatid"],
                                                 m.media_url_https,
                                                 disable_notification=True,
                                                 caption=caption)
                elif m.type == "video":
                    best_variant = tweets.get_best_variant(m.video_info["variants"])
                    if best_variant is not None:
                        msg = context.bot.send_video(config.config["telegram"]["chatid"],
                                                     best_variant,
                                                     disable_notification=True,
                                                     caption=caption)

            elif len(twitter_msg.media) > 1:
                mediaArr = []
                for m in twitter_msg.media:
                    if m.type == "photo":
                        mediaArr.append(telegram.InputMediaPhoto(media=m.media_url_https,
                                                                 caption=saved_url))
                    elif m.type == "video":
                        best_variant = tweets.get_best_variant(
                            m.video_info["variants"])
                        if best_variant is not None:
                            mediaArr.append(telegram.InputMediaVideo(media=best_variant,
                                                                     caption=saved_url))
                resps = context.bot.send_media_group(config.config["telegram"]["chatid"],
                                                     mediaArr,
                                                     disable_notification=True)
                if len(resps) > 0:
                    msg = resps[0]
            config.config["cached"][str(twitter_msg.id)] = {
                "archive_url": saved_url,
                "telegram_url": msg.link
            }
            config.save_config()
        else:
            logging.info("error saving tweet {}")
        return msg
Exemple #3
0
def urlsForAlbum(urls):
    video_output = []
    photo_output = []
    for url in urls:
        if "mp4" in url or "gif" in url:
            video_output.append(
                telegram.InputMediaVideo(media=url['url'],
                                         caption=url['caption']))
        else:
            photo_output.append(
                telegram.InputMediaPhoto(media=url['url'],
                                         caption=url['caption']))
    return photo_output, video_output
Exemple #4
0
 def __update_message(self,
                      tg_transport,
                      user,
                      response,
                      message_id,
                      current_command,
                      from_command=None):
     for m in response.messages:
         if m.type == MessageType.TEXT:
             if m.quoted_incoming_message is not None:
                 reply_to_message_id = m.quoted_incoming_message.id
             else:
                 reply_to_message_id = None
             tg_transport.editMessageText(
                 chat_id=user.chat_id,
                 message_id=message_id,
                 text=m.payload,
                 reply_to_message_id=reply_to_message_id,
                 parse_mode=telegram.ParseMode.HTML)
         elif m.type == MessageType.VIDEO:
             try:
                 tg_transport.edit_message_media(
                     chat_id=user.chat_id,
                     message_id=message_id,
                     media=telegram.InputMediaVideo(m.payload),
                 )
             except Exception:
                 tg_transport.editMessageText(
                     chat_id=user.chat_id,
                     message_id=message_id,
                     text=m.payload,
                     parse_mode=telegram.ParseMode.HTML)
         elif m.type == MessageType.KEYBOARD:
             self.__send_keyboard(tg_transport,
                                  user,
                                  m.payload,
                                  existing_keyboard=message_id,
                                  current_command=current_command,
                                  from_command=from_command,
                                  without_history=m.payload.without_history)
         elif m.type == MessageType.ANSWER:
             tg_transport.answer_callback_query(user.callback_id, m.payload)
         else:
             self.send_unhandled_message(user)
Exemple #5
0
def sendstuff(sender, chat):
    last_file = subprocess.check_output(
        "ls -t description/", shell=True).decode('unicode_escape').split('\n')
    if (len(last_file) <= 1):
        print("no files")
        return
    laststr = last_file[len(last_file) - 2]
    description_file = open("description/" + laststr, "r")
    desc = description_file.read().split('\n')
    description_file.close()
    if ((desc[0] != "photo") & (desc[0] != "text") & (desc[0] != "doc") &
        (desc[0] != "video")):
        bot.send_message(chat_id="@goglike",
                         text="something is wrong with " + laststr)
        subprocess.call(["rm", "-v", "description/" + laststr])
        sendstuff(sender, chat)
        return
    updater = Updater(token=sender)
    bot = updater.bot
    if (len(desc) <= 3):
        if (desc[0] == 'text'):
            caption_file = open("text/" + laststr, "r")
            caption = caption_file.read()
            caption_file.close()
            bot.send_message(chat_id=chat, text=caption)
        if ((desc[0] == 'photo') & (desc[1] != 'cap')):
            bot.send_photo(chat_id=chat, photo=desc[2])
        if ((desc[0] == 'photo') & (desc[1] == 'cap')):
            caption_file = open("text/" + laststr, "r")
            caption = caption_file.read()
            caption_file.close()
            bot.send_photo(chat_id=chat, photo=desc[2], caption=caption)
        if ((desc[0] == 'doc') & (desc[1] != 'cap')):
            bot.send_document(chat_id=chat, document=desc[2])
        if ((desc[0] == 'doc') & (desc[1] == 'cap')):
            caption_file = open("text/" + laststr, "r")
            caption = caption_file.read()
            caption_file.close()
            bot.send_document(chat_id=chat, document=desc[2], caption=caption)
        if ((desc[0] == 'video') & (desc[1] != 'cap')):
            bot.send_video(chat_id=chat, video=desc[2])
        if ((desc[0] == 'video') & (desc[1] == 'cap')):
            caption_file = open("text/" + laststr, "r")
            caption = caption_file.read()
            caption_file.close()
            bot.send_video(chat_id=chat, video=desc[2], caption=caption)
        subprocess.call(["rm", "-v", "description/" + laststr])
    elif (len(desc) == 4):
        numlist = []
        desclist = []
        while (len(desc) == 4):
            numlist.append(laststr)
            desclist.append(desc)

            laststr = str(int(laststr) + 1)
            temppath = Path("description/" + laststr)
            if temppath.is_file():
                description_file = open("description/" + laststr, "r")
                desc = description_file.read().split('\n')
                description_file.close()
            else:
                break

        print(numlist, desclist)
        inputmedia = []
        for i in range(len(numlist)):
            desc = desclist[i]
            if ((desc[0] == 'photo') & (desc[1] != 'cap')):
                inputmedia.append(tel.InputMediaPhoto(desc[2]))
            if ((desc[0] == 'photo') & (desc[1] == 'cap')):
                caption_file = open("text/" + numlist[i], "r")
                caption = caption_file.read()
                caption_file.close()
                inputmedia.append(tel.InputMediaPhoto(desc[2],
                                                      caption=caption))
            if ((desc[0] == 'doc') & (desc[1] != 'cap')):
                inputmedia.append(tel.InputMediaDocument(desc[2]))
            if ((desc[0] == 'doc') & (desc[1] == 'cap')):
                caption_file = open("text/" + numlist[i], "r")
                caption = caption_file.read()
                caption_file.close()
                inputmedia.append(
                    tel.InputMediaDocument(desc[2], caption=caption))
            if ((desc[0] == 'video') & (desc[1] != 'cap')):
                inputmedia.append(tel.InputMediaVideo(desc[2]))
            if ((desc[0] == 'video') & (desc[1] == 'cap')):
                caption_file = open("text/" + numlist[i], "r")
                caption = caption_file.read()
                caption_file.close()
                inputmedia.append(tel.InputMediaVideo(desc[2],
                                                      caption=caption))
        print(len(inputmedia))
        bot.send_media_group(chat_id=chat, media=inputmedia)
        for i in numlist:
            subprocess.call(["rm", "-v", "description/" + i])
Exemple #6
0
    def send_to_ch(self, channel):
        message = db.get_last_msg(channel_name=channel.name)
        dir_ = out = None
        try:
            # media_group
            if isinstance(message, list):
                chat_id = channel.name
                media = []
                new_message = []
                for msg in message:
                    txt = editor.id_remove(text=msg.txt, channel=channel)
                    if msg.kind == 'photo':
                        media.append(
                            telegram.InputMediaPhoto(media=msg.file_id,
                                                     caption=txt))
                    elif msg.kind == 'video':
                        media.append(
                            telegram.InputMediaVideo(media=msg.file_id,
                                                     caption=txt))

                    msg.sent = True
                    msg.ch_a = True
                    new_message.append(msg)

                self.updater.bot.send_media_group(chat_id=chat_id,
                                                  media=media,
                                                  timeout=time_out)
                for msg in new_message:
                    db.update(msg)
                logging.info('media_group sent {}'.format(message.__str__()))

            # regular
            elif not message.ch_a:
                txt = editor.id_remove(text=message.txt, channel=channel)
                parse_mode = 'HTML' if message.other == 'url' else None

                if message.kind == 'photo':
                    dir_ = "image/{}.jpg".format(channel.name)
                    out = "image/{}_out.jpg".format(channel.name)
                    if channel.plan >= 1:
                        try:
                            self.updater.bot.getFile(
                                message.file_id).download(dir_)
                            txt = editor.image_watermark(photo=dir_,
                                                         out=out,
                                                         caption=message.txt,
                                                         channel=channel)
                            self.updater.bot.send_photo(
                                chat_id=message.to_channel,
                                photo=open(out, 'rb'),
                                caption=txt,
                                timeout=time_out)
                        except Exception:
                            txt = editor.id_remove(text=message.txt,
                                                   channel=channel)
                            self.updater.bot.send_photo(
                                chat_id=message.to_channel,
                                photo=message.file_id,
                                caption=txt)
                    else:
                        txt = editor.id_remove(message.txt, channel)
                        self.updater.bot.send_photo(chat_id=message.to_channel,
                                                    photo=message.file_id,
                                                    caption=txt)

                elif message.kind == 'video':
                    form = message.mime
                    dir_ = "vid/{}.{}".format(channel.name, form)
                    out = "vid/{}_out.mp4".format(channel.name)

                    if message.size <= limit_size and channel.plan >= 3:
                        self.updater.bot.getFile(message.file_id).download(
                            dir_, timeout=20)
                        try:
                            txt = editor.vid_watermark(vid=dir_,
                                                       out=out,
                                                       kind=message.kind,
                                                       caption=message.txt,
                                                       channel=channel)

                            self.updater.bot.send_video(
                                chat_id=message.to_channel,
                                video=open(out, 'rb'),
                                caption=txt,
                                timeout=time_out)
                        except Exception:
                            self.updater.bot.send_video(
                                chat_id=message.to_channel,
                                video=message.file_id,
                                caption=txt)
                    else:
                        txt = editor.id_remove(text=message.txt,
                                               channel=channel)
                        self.updater.bot.send_video(chat_id=message.to_channel,
                                                    video=message.file_id,
                                                    caption=txt)

                elif message.kind == 'animation':
                    form = message.mime
                    dir_ = "gif/{}.{}".format(channel.name, form)
                    out = "gif/{}_out.mp4".format(channel.name)

                    if message.size <= limit_size and channel.plan >= 2:
                        try:
                            self.updater.bot.getFile(message.file_id).download(
                                dir_, timeout=20)
                            txt = editor.vid_watermark(vid=dir_,
                                                       out=out,
                                                       kind=message.kind,
                                                       caption=message.txt,
                                                       channel=channel)

                            self.updater.bot.send_animation(
                                chat_id=message.to_channel,
                                animation=open(out, 'rb'),
                                caption=txt,
                                timeout=time_out)
                        except Exception as _:
                            self.updater.bot.send_animation(
                                chat_id=message.to_channel,
                                animation=message.file_id,
                                caption=txt)
                    else:
                        txt = editor.id_remove(text=message.txt,
                                               channel=channel)
                        self.updater.bot.send_animation(
                            chat_id=message.to_channel,
                            animation=message.file_id,
                            caption=txt)

                elif message.kind == 'text':
                    self.updater.bot.send_message(chat_id=message.to_channel,
                                                  text=txt,
                                                  parse_mode=parse_mode)

                elif message.kind == 'audio':
                    self.updater.bot.send_audio(chat_id=message.to_channel,
                                                audio=message.file_id,
                                                caption=txt)

                elif message.kind == 'document':
                    self.updater.bot.send_document(chat_id=message.to_channel,
                                                   document=message.file_id,
                                                   caption=txt)

                elif message.kind == 'v_note':
                    self.updater.bot.send_video_note(
                        chat_id=message.to_channel, video_note=message.file_id)

                elif message.kind == 'voice':
                    self.updater.bot.send_voice(chat_id=message.to_channel,
                                                voice=message.file_id,
                                                caption=txt)

                elif message.kind == 'sticker':
                    self.updater.bot.send_sticker(chat_id=message.to_channel,
                                                  sticker=message.file_id,
                                                  caption=txt)

                try:
                    if dir_ or out:
                        _ = [os.remove(i) for i in [dir_, out]]
                except Exception:
                    pass

                logging.debug('send_to_ch {}'.format(message.__str__()))
                message.sent = True
                message.ch_a = True
                db.update(message)

        except IndexError:
            pass
        except AttributeError:
            pass
        except Exception as E:
            if isinstance(message, db.Message):
                message.sent = True
                message.ch_a = True
                db.update(message)
                logging.error('send_to_ch attempt {} Error: {}'.format(
                    message.__str__(), E))
            else:
                logging.error(
                    'send_to_ch attempt {} Error: not a message'.format(
                        message.__str__()))