Esempio n. 1
0
    def state(self, update, content):
        try:
            admin = update.message.chat_id

            if not content.args:
                channel = db.find("channel", admin=admin)
            else:
                name = content.args[0]
                channel = db.find("channel", admin=admin, name=name)

            if isinstance(channel, db.Channel):
                text = strings.status(channel,
                                      util.remain(channel=channel),
                                      button=False)
                self.updater.bot.send_message(
                    chat_id=admin,
                    text=text,
                    reply_to_message_id=update.message.message_id)
                logging.info("state : {}".format(channel.name))

            elif isinstance(channel, list):
                self.updater.bot.send_message(
                    chat_id=admin,
                    text=
                    "شما صاحب چندین نسخه از بات هستید لطفا نام کانال خود را نیز وارد کنید"
                    "مثال:\n"
                    "/state @channel",
                    reply_to_message_id=update.message.message_id)

        except Exception as E:
            logging.error("state : {}".format(E))
Esempio n. 2
0
def set_logo(update, content):
    try:
        if update.callback_query:
            um = update.callback_query
            comm, name = um.data.split(';')
            chat_id = um.message.chat_id
            channel = db.find('channel', admin=chat_id, name=name)
            editor.logo_by_name(channel)
            channel.logo = False

            text, keyboard = strings.set_logo_ok(channel=channel)
            content.bot.send_photo(chat_id=chat_id,
                                   reply_to_message_id=um.message.message_id,
                                   photo=open('info.png', 'rb'),
                                   caption=text,
                                   reply_markup=keyboard)
            return set_pos

        elif update.message.sticker:
            print(update.message.sticker)
        elif update.message.document:
            um = update.message
            chat_id = um.chat_id
            file_id = um.document.file_id
            mime = um.document.mime_type
            size = um.document.file_size
            name = um.caption if um.caption else None
            if name:
                res = db.find('channel', admin=chat_id, name=name)
            else:
                res = db.find('channel', admin=chat_id)
            if isinstance(res, db.Channel) and mime.startswith(
                    'image') and size < (8 * 1025 * 1024):
                channel = res
                content.bot.get_file(file_id=file_id).download(
                    'logo/{}.png'.format(channel.name))
                channel.logo = True
                db.update(channel)

                text, keyboard = strings.set_logo_ok(channel=channel)
                content.bot.send_photo(chat_id=chat_id,
                                       reply_to_message_id=um.message_id,
                                       photo=open('info.png', 'rb'),
                                       caption=text,
                                       reply_markup=keyboard)
                return set_pos

            elif isinstance(res, list):
                content.bot.send_message(chat_id=chat_id,
                                         reply_to_message_id=um.message_id,
                                         text=strings.set_logo_fail)
                return set_logo
            else:
                content.bot.send_message(chat_id=chat_id,
                                         reply_to_message_id=um.message_id,
                                         text=strings.set_logo_else)
                return set_logo
    except Exception as E:
        logging.error("set_logo {}".format(E))
Esempio n. 3
0
def status(update, content):
    try:
        um = update.message
        admin = um.from_user.id
        channels = db.find('channel', admin=admin)
        if channels:
            if isinstance(channels, db.Channel):
                channel = channels
                chat_id = um.chat_id
                message_id = um.message_id

                text, keyboard = strings.status(
                    channel=channel, remain=util.remain(channel=channel))
                content.bot.send_message(chat_id=chat_id,
                                         text=text,
                                         reply_to_message_id=message_id,
                                         reply_markup=keyboard)
                return select

            elif isinstance(channels, list):
                keyboard = InlineKeyboardMarkup(
                    [[Inline(i.name, callback_data="_;{}".format(i.name))]
                     for i in channels])
                content.bot.send_message(
                    chat_id=admin,
                    text=
                    "شما صاحب چندین کانال هستید\nمایل به مشاهده تنظیمات کدام یک هستید؟",
                    reply_markup=keyboard)
                return setting

    except Exception as E:
        logging.error("status {}".format(E))
Esempio n. 4
0
def data_param(adata):
    adata['client_id'] = common.client_id
    adata['grant_type'] = common.grant_type
    adata['client_secret'] = common.client_secret
    adata['timestamp'] = str(int(time.time()))
    access_token = db.find()
    if access_token == 'empty':
        adata['access_token'] = access_token
Esempio n. 5
0
def auth():
    access_token = db.find()
    if access_token == 'empty':
        return redirect(
            'https://mai.pinduoduo.com/h5-login.html?response_type=code&client_id=86b52cf3146d42dfb4ca0ff994006db0&redirect_uri=http://boss-vip.utools.club/access_token&&state=1212&view=h5'
        )
    else:
        return render_template('index.html', auth_title='已授权')
Esempio n. 6
0
    def task(self, content):
        try:
            now = JalaliDatetime().now()
            channels = db.find('channel')

            if now.minute == 0:
                content.bot.send_message(chat_id=cna,
                                         text=str(psutil.virtual_memory()[2]))

            for channel in channels:
                if util.time_is_in(now=now, channel=channel):
                    self.send_to_ch(channel=channel)
                if now.hour == now.minute == 0:
                    self.add_member(channel=channel)

        except Exception as E:
            logging.error('Task {}'.format(E))
Esempio n. 7
0
    def send_info(self, update, content):
        try:
            um = update.message
            if isinstance(um.new_chat_members, list):
                chat_member = um.new_chat_members[0]
                channel = db.find('channel', group_id=um.chat_id)

                if chat_member.id == content.bot.id:
                    if um.chat.type == 'supergroup' and isinstance(
                            channel, db.Channel):
                        content.bot.send_message(chat_id=um.chat_id,
                                                 text=strings.congrats)
                    else:
                        content.bot.send_message(chat_id=um.chat_id,
                                                 text=um.chat_id)
                        content.bot.leave_chat(um.chat_id)
        except Exception as E:
            logging.error("send_info: {}".format(E))
Esempio n. 8
0
def set_pos(update, content):
    try:
        um = update.callback_query
        admin = um.message.chat_id
        data = um.data
        pos, name = data.split(';')
        channel = db.find("channel", admin=admin, name=name)
        channel.pos = int(pos)
        db.update(channel)
        content.bot.send_message(chat_id=admin,
                                 reply_to_message_id=um.message.message_id,
                                 text="تغییرات اعمال شد",
                                 reply_markup=InlineKeyboardMarkup([[
                                     Inline('وضعیت',
                                            callback_data='{};{}'.format(
                                                admin, name))
                                 ]]))
        return setting
    except Exception as E:
        logging.error("set_pos {}".format(E))
Esempio n. 9
0
def done(update, content):
    try:
        if update.callback_query:
            um = update.callback_query
            data = um.data
            part1, channel_name = data.split(';')
            chat_id = um.message.chat_id
            message_id = um.message.message_id

            channel = db.find('channel', name=channel_name)

            if part1 == '_':
                pass
            elif part1.endswith('b'):
                bed = part1[:-1]
                channel.bed = int(bed)
                db.update(channel)
            elif part1.endswith('w'):
                wake = part1[:-1]
                channel.wake = int(wake)
                db.update(channel)
            elif part1.endswith("r") or part1.endswith("f"):
                interval = part1
                channel.interval = interval
                db.update(channel)
            elif part1 == "off":
                channel.bed = -1
                channel.wake = -1
                db.update(channel)

            text, keyboard = strings.status(
                channel=channel, remain=util.remain(channel=channel))
            content.bot.edit_message_text(chat_id=chat_id,
                                          message_id=message_id,
                                          text=text,
                                          reply_markup=keyboard)
            return select

    except Exception as E:
        logging.error("done {}".format(E))
Esempio n. 10
0
def select(update, content):
    try:
        um = update.callback_query
        data = um.data
        data = data.split(';')
        chat_id = um.message.chat_id
        message_id = um.message.message_id
        if data[0] == 'interval':
            keyboard = [[
                Inline('01M', callback_data='01m;{}'.format(data[1]))
            ]]
            for i in range(5, 60, 5):
                keyboard.append([
                    Inline("{}M".format(str(i).zfill(2)),
                           callback_data="{}m;{}".format(
                               str(i).zfill(2), data[1]))
                ])
            for i in range(1, 25):
                keyboard.append([
                    Inline("{}H".format(str(i).zfill(2)),
                           callback_data='{}h;{}'.format(
                               str(i).zfill(2), data[1]))
                ])
            keyboard = np.array(keyboard).reshape((-1, 6)).tolist()
            keyboard.append([
                Inline('بازگشت به منوی تنظیمات',
                       callback_data='setting;{}'.format(data[1]))
            ])
            content.bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text="گام اول:\n"
                "زمانبدی مورد نظر خود را انتخاب کنید\n تنها درصورتی که مایل "
                "به تغییر دقایق به صورت دلخواه هستید "
                "برای مثال:\n"
                "13m -> برابر با هر 13 دقیقه\n"
                "از این روش استفاده کنید:\n"
                "/delay 13m @name-e-channel"
                "\n اگر دچار مشکلی شده اید از ما کمک بگیرید\n"
                "@Cna74",
                reply_markup=InlineKeyboardMarkup(keyboard))
            return step2
        elif data[0] == 'wake':
            keyboard = []
            for i in range(0, 24):
                keyboard.append([
                    Inline('{}:00'.format(str(i).zfill(2)),
                           callback_data="{}w;{}".format(
                               str(i).zfill(2), data[1]))
                ])
            keyboard = np.array(keyboard).reshape((6, -1)).tolist()
            keyboard.append(
                [Inline('off', callback_data="offw;{}".format(data[1]))])
            keyboard.append([
                Inline('بازگشت به منوی تنظیمات',
                       callback_data='setting;{}'.format(data[1]))
            ])
            content.bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text="بات از چه ساعتی شروع به کار کند؟",
                reply_markup=InlineKeyboardMarkup(keyboard))
            return done
        elif data[0] == 'bed':
            keyboard = []
            for i in range(0, 24):
                keyboard.append([
                    Inline('{}:00'.format(str(i).zfill(2)),
                           callback_data="{}b;{}".format(
                               str(i).zfill(2), data[1]))
                ])
            keyboard = np.array(keyboard).reshape((6, -1)).tolist()
            keyboard.append(
                [Inline('off', callback_data="offw;{}".format(data[1]))])
            keyboard.append([
                Inline('بازگشت به منوی تنظیمات',
                       callback_data='setting;{}'.format(data[1]))
            ])
            content.bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text="بات در چه ساعتی خاموش شود؟",
                reply_markup=InlineKeyboardMarkup(keyboard))
            return done
        elif data[0] == 'graph':
            content.bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text="نمودار در چه بازه زمانی باشد؟",
                reply_markup=InlineKeyboardMarkup([[
                    Inline('یک هفته', callback_data="1w;{}".format(data[1])),
                    Inline('یک ماه', callback_data="1m;{}".format(data[1])),
                    Inline('یک سال', callback_data="1y;{}".format(data[1]))
                ]]))
            return graph
        elif data[0] == 'logo':
            content.bot.edit_message_text(
                chat_id=chat_id,
                message_id=message_id,
                text=
                "یک عکس با فرمت png بدون پس زمینه برام بفرست در ابعاد مربع\n"
                "اگر نمیتونی یا بلد نیستی اینکار رو بکنی"
                " میتونم از اسم کانال به عنوان لوگو استفاده کنم",
                reply_markup=InlineKeyboardMarkup([[
                    Inline('استفاده از نام کانال',
                           callback_data="name;{}".format(data[1]))
                ]]))
            return set_logo
        elif data[0] == 'up':
            channel = db.find('channel', name=data[1])
            content.bot.edit_message_text(chat_id=chat_id,
                                          message_id=message_id,
                                          text=strings.status_upgrade(channel))
            return ConversationHandler.END
    except Exception as E:
        logging.error("select {}".format(E))
Esempio n. 11
0
def set_interval(update, content):
    try:
        um = update.message
        admin = um.from_user
        if content.args:
            if len(content.args) == 2:
                interval = content.args[0]
                ch_name = content.args[1]
                channel = db.find('channel', name=ch_name, admin=admin.id)
                if channel:
                    if interval.endswith('m') and interval[:-1].isdigit():
                        interval = int(interval[:-1])
                        if 1 < interval <= 30:
                            content.bot.send_message(
                                chat_id=um.chat_id,
                                reply_to_message_id=um.message_id,
                                text="گام دوم:\n"
                                "1️⃣ پیام ها هر {0} دقیقه ارسال شوند."
                                " برای مثال بصورت 01:{0}, "
                                "01:{1} و ...\n"
                                "2️⃣ پیام ها وقتی دقیقه شمار برابر {0} است"
                                " ارسال شوند برای مثال "
                                "01:{0}, 02:{0}, 03:{0} و ...\n"
                                "کدام یک مورد پسند شماست؟\n"
                                "از ما کمک بگیرید:\n"
                                "@s_for_cna".format(
                                    str(interval).zfill(2),
                                    str(interval * 2).zfill(2)),
                                reply_markup=InlineKeyboardMarkup(
                                    [[
                                        Inline('حالت  1️⃣',
                                               callback_data='{}mr;{}'.format(
                                                   interval, ch_name)),
                                        Inline('حالت  2️⃣',
                                               callback_data='{}mf;{}'.format(
                                                   interval, ch_name))
                                    ],
                                     [
                                         Inline('لغو، بازگشت',
                                                callback_data='_;{}'.format(
                                                    ch_name))
                                     ]]))
                        else:
                            content.bot.send_message(
                                chat_id=um.chat_id,
                                reply_to_message_id=um.message_id,
                                text="گام دوم:\n"
                                "پیام ها در ساعاتی مانند 01:{0}, 02:{0} ارسال میشوند\n"
                                "از ما کمک بگیرید:\n"
                                "@s_for_cna".format(str(interval).zfill(2)),
                                reply_markup=InlineKeyboardMarkup(
                                    [[
                                        Inline('تایید',
                                               callback_data='{}mr;{}'.format(
                                                   interval, ch_name))
                                    ],
                                     [
                                         Inline('لغو، بازگشت',
                                                callback_data='_;{}'.format(
                                                    ch_name))
                                     ]]))
                        return done

    except Exception as E:
        logging.error("set_interval: {}".format(E))
Esempio n. 12
0
def graph(update, content):
    try:
        if update.callback_query:
            um = update.callback_query
            admin = um.message.chat_id
            data = um.data
            domain, ch_name = data.split(';')
            save_in = "plot/{}.png".format(ch_name)

            d = {'1w': 7, '1m': 31, '1y': 365}
            domain = d.get(domain)
            now = JalaliDatetime().now().to_date()
            from_ = now - timedelta(days=domain)

            out = db.find('member',
                          admin=admin,
                          name=ch_name,
                          from_=from_,
                          til=now)

            y = out[:, 0]
            if len(out) < 3:
                content.bot.edit_message_text(
                    chat_id=admin,
                    message_id=um.message.message_id,
                    text="حداقل باید سه روز از ثبت نام گذشته باشد")
                return ConversationHandler.END

            y = np.append(y, content.bot.get_chat_members_count(ch_name))
            x = np.arange(len(y), dtype=int)

            plt.plot(x, y, marker='o', label='now', color='red', markersize=4)
            plt.plot(list(x)[:-1],
                     y[:-1],
                     marker='o',
                     label='members',
                     color='blue',
                     markersize=4)

            plt.ticklabel_format(style='plain', axis='x', useOffset=False)
            plt.ticklabel_format(style='plain', axis='y', useOffset=False)
            plt.grid()
            plt.xlim(x.min(), x.max())
            plt.ylim(y.min(), y.max())
            plt.xlabel('days')
            plt.ylabel('members')
            plt.legend(loc=4)

            plt.savefig(save_in)
            plt.close()

            days = len(y) - 1
            diff = np.mean(np.diff(y))
            prediction = round(y[-1] + domain * diff)
            diff = format(diff, '.2f')
            now = JalaliDatetime().from_date(now)
            til = now + timedelta(days=days)

            content.bot.send_photo(chat_id=um.message.chat_id,
                                   photo=open(save_in, 'rb'),
                                   caption="از {} تا {} در {} روز\n" \
                                           " کمترین میزان تعداد اعضا 🔻 {}\n" \
                                           " بیشترین تعداد اعضا🔺 {}\n" \
                                           " میانگین سرعت عضو شدن اعضا در روز {}\n" \
                                           "پیش بینی برای {} روز آینده برابر {}".format(
                                       days, til, now, y.min(), y.max(), diff, prediction, domain))
            os.remove(save_in)
            return ConversationHandler.END
    except Exception as E:
        logging.error("graph {}".format(E))
Esempio n. 13
0
def step2(update, content):
    if update.callback_query:
        um = update.callback_query
        data = um.data.split(';')
        interval = data[0]
        ch_name = data[1]
        admin = um.message.chat_id
        message_id = um.message.message_id

        if interval.endswith('m'):
            interval = int(interval[:-1])
            if 1 <= interval <= 30:
                content.bot.edit_message_text(
                    chat_id=um.message.chat_id,
                    message_id=um.message.message_id,
                    text="گام دوم:\n"
                    "1️⃣ پیام ها هر {0} دقیقه ارسال شوند. برای مثال بصورت 01:{0}, "
                    "01:{1} و ...\n"
                    "2️⃣ پیام ها وقتی دقیقه شمار برابر {0} است ارسال شوند برای مثال "
                    "01:{0}, 02:{0}, 03:{0} و ...\n"
                    "کدام یک مورد پسند شماست؟\n"
                    "از ما کمک بگیرید:\n"
                    "@s_for_cna".format(
                        str(interval).zfill(2),
                        str(interval * 2).zfill(2)),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            Inline('حالت  1️⃣',
                                   callback_data='{}mr;{}'.format(
                                       interval, ch_name)),
                            Inline('حالت  2️⃣',
                                   callback_data='{}mf;{}'.format(
                                       interval, ch_name))
                        ],
                         [
                             Inline('لغو، بازگشت',
                                    callback_data='_;{}'.format(ch_name))
                         ]]))
            else:
                content.bot.edit_message_text(
                    chat_id=um.message.chat_id,
                    message_id=um.message.message_id,
                    text="گام دوم:\n"
                    "پیام ها در ساعاتی مانند 01:{0}, 02:{0} ارسال میشوند\n"
                    "از ما کمک بگیرید:\n"
                    "@s_for_cna".format(str(interval).zfill(2)),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            Inline('تایید',
                                   callback_data='{}mr;{}'.format(
                                       interval, ch_name))
                        ],
                         [
                             Inline('لغو، بازگشت',
                                    callback_data='_;{}'.format(ch_name))
                         ]]))

            return done
        elif interval.endswith('h'):
            interval = int(interval[:-1])
            if 1 <= interval <= 12:
                content.bot.edit_message_text(
                    chat_id=um.message.chat_id,
                    message_id=um.message.message_id,
                    text="گام دوم:\n"
                    "1️⃣ پیام ها هر {0} ساعت ارسال شوند. برای مثال بصورت {0}:00, "
                    " {1}:00 و ... "
                    "2️⃣ پیام ها هر روز راس ساعت {0}:00 ارسال شوند"
                    "کدام یک مورد پسند شماست؟\n"
                    "از ما کمک بگیرید:\n"
                    "@s_for_cna".format(
                        str(interval).zfill(2),
                        str(interval * 2).zfill(2)),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            Inline('حالت  1️⃣',
                                   callback_data='{}hr;{}'.format(
                                       interval, ch_name)),
                            Inline('حالت  2️⃣',
                                   callback_data='{}hf;{}'.format(
                                       interval, ch_name))
                        ],
                         [
                             Inline('لغو، بازگشت',
                                    callback_data='_;{}'.format(ch_name))
                         ]]))
            else:
                content.bot.edit_message_text(
                    chat_id=um.message.chat_id,
                    message_id=um.message.message_id,
                    text="گام دوم:\n"
                    "پیام ها هر روز راس ساعت {0}:00 ارسال شوند"
                    "کدام یک مورد پسند شماست؟\n"
                    "از ما کمک بگیرید:\n"
                    "@s_for_cna".format(str(interval).zfill(2)),
                    reply_markup=InlineKeyboardMarkup(
                        [[
                            Inline('تایید',
                                   callback_data='{}mr;{}'.format(
                                       interval, ch_name))
                        ],
                         [
                             Inline('لغو، بازگشت',
                                    callback_data='_;{}'.format(ch_name))
                         ]]))
            return done
        elif interval == "setting":
            channel = db.find("channel", name=ch_name)
            text, keyboard = strings.status(
                channel=channel, remain=util.remain(channel=channel))
            content.bot.edit_message_text(chat_id=admin,
                                          text=text,
                                          message_id=message_id,
                                          reply_markup=keyboard)
            return select
Esempio n. 14
0
    def admin(self, update, content):
        try:
            chat_id = update.message.chat_id
            message_id = update.message.message_id
            command = group_id = admin = channel_name = plan = expire = None
            if content.args:
                self.updater.bot.send_chat_action(
                    chat_id=chat_id, action=telegram.ChatAction.TYPING)
                command = content.args[0]
                if command == "add":
                    group_id, admin, channel_name, plan, expire = content.args[
                        1:]
                    if not db.find('channel', name=channel_name):
                        channel = db.Channel(
                            name=channel_name,
                            admin=int(admin),
                            group_id=int(group_id),
                            plan=int(plan),
                            expire=timedelta(days=int(expire)))
                        db.add(channel)
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "ren":
                    channel_name, expire = content.args[1:]
                    if db.find("channel", name=channel_name):
                        channel = db.find("channel", name=channel_name)
                        channel.expire += timedelta(days=int(expire))
                        db.update(channel)
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "plan":
                    channel_name, plan = content.args[1:]
                    channel = db.find("channel", name=channel_name)
                    channel.plan = int(plan)
                    db.update(channel)
                    self.updater.bot.send_message(
                        chat_id=chat_id,
                        reply_to_message_id=message_id,
                        text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "del":
                    channel_name = content.args[1]
                    channel = db.find("channel", name=channel_name)
                    if channel:
                        db.delete(channel)
                elif command == "edit":
                    channel_name, n_channel_name = content.args[1:]
                    channel = db.find("channel", name=channel_name)
                    if channel:
                        channel.name = n_channel_name
                        db.update(channel)
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text="ثبت شد \n\n{}".format(channel.__str__()))
                elif command == "lst":
                    channels = db.find('channel')
                    text = "channel          expire_date\n"
                    for ch in channels:
                        expire = JalaliDatetime().from_date(ch.expire)
                        now = JalaliDatetime().now()
                        diff = expire - now
                        if diff.days < 7:
                            text += "{} {} 🔴\n\n".format(
                                ch.name, expire.strftime("%A %d %B"))
                        else:
                            text += "{} {} ⚪️\n\n".format(
                                ch.name, expire.strftime("%A %d %B"))

                    self.updater.bot.send_message(chat_id=cna, text=text)
                elif command == "det":
                    channel_name, = content.args[1:]
                    channel = db.find("channel", name=channel_name)
                    if isinstance(channel, db.Channel):
                        self.updater.bot.send_message(
                            chat_id=chat_id,
                            reply_to_message_id=message_id,
                            text=strings.status(channel,
                                                util.remain(channel),
                                                button=False))
                elif command == "db":
                    # db
                    self.updater.bot.send_document(chat_id=cna,
                                                   document=open(
                                                       "bot_db.db", "rb"),
                                                   timeout=time_out)
                else:
                    self.updater.bot.send_message(
                        chat_id=chat_id,
                        reply_to_message_id=message_id,
                        text="command {} not found".format(content.args[0]))

            else:
                self.updater.bot.send_message(chat_id=chat_id,
                                              text=strings.admin_hint)
        except Exception as E:
            logging.error("admin: {}".format(E))
Esempio n. 15
0
    def save(self, update, content):
        try:
            um = update.message
            ue = update.edited_message
            message = None
            # edited
            if ue:
                from_gp = ue.chat_id
                msg_gp_id = ue.message_id
                # channel = db.find('channel', group_id=from_gp)
                message = db.find('message',
                                  msg_gp_id=msg_gp_id,
                                  gp_id=from_gp)
                if isinstance(message, db.Message):
                    if ue.reply_to_message:
                        if ue.text:
                            message = db.find(
                                "message",
                                msg_gp_id=ue.reply_to_message.message_id,
                                gp_id=ue.chat_id)
                            if isinstance(message, db.Message):
                                if message.other.isnumeric():
                                    message = db.find("message",
                                                      media=message.other)
                                    for msg in message:
                                        msg.txt = ue.text
                                        db.update(msg)
                                else:
                                    message.txt = ue.text
                                    db.update(message)

                    # # after sent
                    # elif ue.text and message.sent:
                    #     message.txt = editor.id_remove(text=ue.text, channel=channel)
                    #     if len(um.entities) > 0:
                    #         entities = um.entities
                    #         url = ''.join([entities[i].url if entities[i].url else '' for i in range(len(entities))])
                    #         message.txt += '\n<a href="{}">​​​​​​​​​​​</a>'.format(url)
                    #         message.other = 'url'
                    #     parse_mode = 'HTML' if message.other == 'url' else None
                    #     self.robot.edit_message_text(chat_id=message.to_channel, message_id=message.msg_ch_id,
                    #                                  text=message.txt, parse_mode=parse_mode)
                    #     message.sent = message.ch_a = True
                    # elif message.sent:
                    #     media = out = None
                    #     text = ue.caption if ue.caption else ' '
                    #     text = editor.id_remove(text=text, channel=channel)
                    #
                    #     if ue.photo:
                    #         media = ue.photo[-1].file_id
                    #         dir_ = "image/{}.jpg".format(channel.name)
                    #         out = 'image/{}_out.jpg'.format(channel.name)
                    #         self.robot.getFile(media).download(dir_)
                    #
                    #         message.kind = "photo"
                    #         if channel.plan >= 1:
                    #             text = editor.image_watermark(photo=dir_, out=out, caption=text, channel=channel)
                    #             media = telegram.InputMediaPhoto(media=open(out, 'rb'), caption=text)
                    #         else:
                    #             text = editor.id_remove(text=text, channel=channel)
                    #             media = telegram.InputMediaPhoto(media=media, caption=text)
                    #
                    #     elif ue.animation:
                    #         media = ue.animation.file_id
                    #         mime = str(um.animation.mime_type).split('/')[1]
                    #         dir_ = "gif/{}.{}".format(channel.name, mime)
                    #         out = "gif/{}_out.mp4".format(channel.name)
                    #         size = ue.video.file_size / (1024 ** 2)
                    #
                    #         message.mime = mime
                    #         message.kind = 'animation'
                    #
                    #         if size <= limit_size and channel.plan >= 2:
                    #             self.robot.getFile(media).download(dir_)
                    #             text = editor.vid_watermark(vid=dir_, out=out, kind=message.kind,
                    #                                         caption=text, channel=channel)
                    #             media = telegram.InputMediaVideo(media=open(out, 'rb'), caption=text)
                    #         else:
                    #             text = editor.id_remove(text=text, channel=channel)
                    #             media = telegram.InputMediaAnimation(media=media, caption=text)
                    #
                    #     elif ue.video:
                    #         media = ue.video.file_id
                    #         mime = str(um.video.mime_type).split('/')[1]
                    #         dir_ = "vid/{}.{}".format(channel.name, mime)
                    #         out = 'vid/{}_out.mp4'.format(channel.name)
                    #         size = ue.video.file_size / (1024 ** 2)
                    #
                    #         message.mime = mime
                    #         message.kind = 'video'
                    #
                    #         if size < limit_size and channel.plan >= 3:
                    #             self.robot.getFile(media).download(dir_)
                    #             text = editor.vid_watermark(vid=dir_, out=out, kind=message.kind,
                    #                                         caption=text, channel=channel)
                    #             media = telegram.InputMediaVideo(media=open(out, 'rb'), caption=text)
                    #         else:
                    #             text = editor.id_remove(text=text, channel=channel)
                    #             media = telegram.InputMediaVideo(media=media, caption=text)
                    #
                    #     elif ue.document:
                    #         media = ue.document.file_id
                    #         media = telegram.InputMediaDocument(media=media, caption=text)
                    #
                    #     elif ue.audio:
                    #         media = ue.audio.file_id
                    #         media = telegram.InputMediaAudio(media=media, caption=text)
                    #
                    #     if media:
                    #         self.robot.edit_message_media(media=media, chat_id=message.to_channel,
                    #                                       message_id=message.msg_ch_id, timeout=time_out)
                    #
                    #     if out:
                    #         os.remove(out)
                    #     if ue.caption:
                    #         self.robot.edit_message_caption(chat_id=message.to_channel, message_id=message.msg_ch_id,
                    #                                         caption=text)
                    #
                    #     message.sent = message.ch_a = True
                    #     message.txt = text

                    # before sent
                    elif ue.text:
                        message.txt = ue.text
                        message.sent = message.ch_a = False
                        if len(um.entities) > 0:
                            entities = um.entities
                            url = ''.join([
                                entities[i].url if entities[i].url else ''
                                for i in range(len(entities))
                            ])
                            message.txt += '\n<a href="{}">​​​​​​​​​​​</a>'.format(
                                url)
                            message.other = 'url'
                    elif ue.caption:
                        message.txt = ue.caption if ue.caption else " "
                        message.sent = message.ch_a = False
                        if ue.photo:
                            message.kind = 'photo'
                            message.file_id = ue.photo[-1].file_id
                        elif ue.video:
                            message.kind = 'video'
                            message.file_id = ue.video.file_id
                        elif ue.animation:
                            message.kind = 'animation'
                            message.file_id = ue.animation.file_id
                        elif ue.document:
                            message.kind = 'document'
                            message.file_id = ue.document.file_id
                        elif ue.audio:
                            message.kind = 'audio'
                            message.file_id = ue.audio.file_id
                    db.update(message)

            # regular
            elif um:
                channel = db.find(table="channel", group_id=um.chat_id)
                if um.reply_to_message:
                    if um.text:
                        message = db.find(
                            "message",
                            msg_gp_id=um.reply_to_message.message_id,
                            gp_id=um.chat_id)
                        if message.other.isnumeric():
                            message = db.find("message", media=message.other)
                            for msg in message:
                                msg.txt = um.text
                                db.update(msg)
                        else:
                            message.txt = um.text
                            db.update(message)

                elif um.text:
                    other = ""
                    txt = um.text
                    if len(um.entities) > 0:
                        entities = um.entities
                        url = ''.join([
                            entities[i].url if entities[i].url else ''
                            for i in range(len(entities))
                        ])
                        txt += '\n<a href="{}">​​​​​​​​​​​</a>'.format(url)
                        other = 'url'
                    message = db.Message(from_group=um.chat_id,
                                         to_channel=channel.name,
                                         kind='text',
                                         msg_gp_id=um.message_id,
                                         txt=txt,
                                         other=other)
                    db.add(message)
                else:
                    text = um.caption if um.caption else ' '
                    file_id = kind = other = mime = ''
                    size = 0
                    if um.media_group_id:
                        if um.photo:
                            kind = 'photo'
                            file_id = um.photo[-1].file_id
                        elif um.video:
                            kind = 'video'
                            file_id = um.video.file_id
                        other = um.media_group_id
                    elif um.photo:
                        kind = 'photo'
                        file_id = um.photo[-1].file_id
                    elif um.video:
                        kind = 'video'
                        size = um.video.file_size / (1024**2)
                        mime = str(um.video.mime_type).split('/')[1]
                        file_id = um.video.file_id
                    elif um.animation:
                        kind = 'animation'
                        size = um.animation.file_size / (1024**2)
                        mime = str(um.document.mime_type).split('/')[1]
                        file_id = um.document.file_id
                    elif um.document:
                        kind = 'document'
                        file_id = um.document.file_id
                    elif um.voice:
                        kind = 'voice'
                        file_id = um.voice.file_id
                    elif um.audio:
                        kind = 'audio'
                        file_id = um.audio.file_id
                    elif um.video_note:
                        kind = 'v_note'
                        file_id = um.video_note.file_id
                    elif um.sticker:
                        kind = 'sticker'
                        file_id = um.sticker.file_id

                    message = db.Message(from_group=um.chat_id,
                                         to_channel=channel.name,
                                         msg_gp_id=um.message_id,
                                         kind=kind,
                                         txt=text,
                                         file_id=file_id,
                                         size=size,
                                         mime=mime,
                                         other=other)
                    db.add(message)

            if isinstance(message, db.Message):
                logging.info("save {}".format(message.__str__()))
        except Exception as E:
            logging.error('save {}'.format(E))