Esempio n. 1
0
def remain(channel):
    try:
        remaining = db.remain(channel)
        step = JalaliDatetime().now()
        rem = remaining
        if channel.up:
            while remaining > 0:

                # assume to send
                if time_is_in(now=step, channel=channel):
                    remaining -= 1
                step += timedelta(minutes=1)
        if rem > 0 :
            date = step.strftime("%A %d %B %H:%M")
            if channel.up:
                text = "پیام های باقیمانده: {0}\nکانال تا {1} تامین خواهد بود".format(rem, date)
            else:
                text = "پیام های باقیمانده: {0}\nموقتا بات غیر فعال است".format(rem)

        else:
            text = "هیچ پیامی در صف نیست"

        return text

    except Exception as E:
        logging.error("remain {}".format(E))
Esempio n. 2
0
File: strings.py Progetto: cna74/SSP
def status(channel, remain, button=True):
    expire = JalaliDatetime().from_datetime(channel.expire).strftime("%x")
    logo = "استفاده از نام کانال" if not channel.logo else "✔️"
    plan = dict([(0, "پایه 🏅"), (1, "برنز 🥉"), (2, "نقره 🥈"),
                 (3, "طلایی 🥇")]).get(channel.plan)
    bed = "off" if channel.bed == -1 else channel.bed
    wake = "off" if channel.wake == -1 else channel.wake

    text = "میزان وقفه ⏳= {}\nساعت توقف 🕰= {}\nساعت شروع 🕰= {}\nلوگو = {}\n\n طرح = {}\n{}\nاعتبار شما تا {}".format(
        channel.interval, bed, wake, logo, plan, remain, expire)
    if button:
        keyboard = [
            [
                Inline('وقفه ⏲️',
                       callback_data='interval;{}'.format(channel.name)),
                Inline('ساعت توقف 🕰️',
                       callback_data='bed;{}'.format(channel.name)),
                Inline('ساعت شروع 🕰️',
                       callback_data='wake;{}'.format(channel.name))
            ],
            [
                Inline('مشاهده نمودار 📈',
                       callback_data="graph;{}".format(channel.name)),
                Inline('تنظیم لوگو 🖼️',
                       callback_data="logo;{}".format(channel.name))
            ], [Inline('تمدید 📆', callback_data='up;{}'.format(channel.name))]
        ]
        keyboard = InlineKeyboardMarkup(keyboard)

        return text, keyboard

    return text
Esempio n. 3
0
 def error_callback(self, _, __, error):
     try:
         logging.error(error)
         self.updater.bot.send_message(
             chat_id=cna,
             text="Heyyy {}".format(JalaliDatetime().now().strftime("%x")))
     except BaseException as E:
         logging.error("TelegramError {}".format(E))
Esempio n. 4
0
 def add_member(self, channel):
     try:
         current_date = JalaliDatetime().now().to_date()
         num = self.updater.bot.get_chat_members_count(channel.name)
         member = db.Member(number=num,
                            channel_name=channel.name,
                            calendar=current_date)
         db.add(member)
     except Exception as E:
         logging.error('add_members {}'.format(E))
Esempio n. 5
0
def sleep(now=None, bed=None, wake=None):
    try:
        now = JalaliDatetime().now().hour if not now else now.hour

        if -1 in (bed, wake):
            return False

        elif now >= bed > wake < now or now >= bed < wake > now:
            return True

        else:
            return False
    except Exception as E:
        logging.error("sleep {}".format(E))
Esempio n. 6
0
    def run(self):
        try:
            dpa = self.updater.dispatcher.add_handler
            job = self.updater.job_queue
            self.updater.start_polling()
            self.updater.dispatcher.add_error_handler(self.error_callback)

            conv.conversation(self.updater)

            dpa(
                CommandHandler(command="admin",
                               filters=Filters.user([cna, rhn]),
                               callback=self.admin,
                               pass_args=True))
            dpa(
                CommandHandler(command="state",
                               filters=Filters.private,
                               callback=self.state,
                               pass_args=True))
            dpa(
                CommandHandler(command="set",
                               filters=Filters.private,
                               callback=self.set,
                               pass_args=True))

            # to get group id
            dpa(
                MessageHandler(filters=Filters.status_update.new_chat_members,
                               callback=self.send_info))
            dpa(
                MessageHandler(filters=Filters.group,
                               callback=self.save,
                               edited_updates=True))

            first = 60 - JalaliDatetime().now().second
            job.run_repeating(callback=self.task, interval=60, first=first)

            user_name = self.updater.bot.name
            print("{}".format(user_name))
            logging.info("{} started".format(user_name))
            self.updater.bot.send_message(chat_id=cna, text="started")

            self.updater.idle()
        except telegram.error.NetworkError as E:
            self.updater.stop()
            logging.error("NETWORK ERROR !!! {}".format(E))
            exit()
Esempio n. 7
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. 8
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. 9
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))