Exemplo n.º 1
0
def conversation(updater):
    # start
    updater.dispatcher.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(command='start',
                               callback=start,
                               filters=Filters.private)
            ],
            states={
                start_select: [CallbackQueryHandler(callback=start_select)],
                start_register: [
                    CallbackQueryHandler(callback=start_register),
                    MessageHandler(
                        filters=Filters.private,
                        callback=start_register,
                    )
                ]
            },
            fallbacks=[CommandHandler(command='cancel', callback=cancel)],
            conversation_timeout=timedelta(minutes=1)))

    # setting
    updater.dispatcher.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(command='setting',
                               callback=status,
                               filters=Filters.private)
            ],
            states={
                setting: [CallbackQueryHandler(setting)],
                select: [CallbackQueryHandler(select)],
                step2: [CallbackQueryHandler(step2)],
                done: [CallbackQueryHandler(done)],
                graph: [CallbackQueryHandler(graph)],
                set_pos: [CallbackQueryHandler(set_pos)],
                set_logo: [
                    CallbackQueryHandler(set_logo),
                    MessageHandler(filters=Filters.private, callback=set_logo)
                ]
            },
            fallbacks=[CommandHandler(command='cancel', callback=cancel)],
            conversation_timeout=timedelta(minutes=1)))

    # delay
    updater.dispatcher.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(command='delay',
                               callback=set_interval,
                               filters=Filters.private,
                               pass_args=True)
            ],
            states={done: [CallbackQueryHandler(callback=done)]},
            fallbacks=[CommandHandler(command='cancel', callback=cancel)],
            conversation_timeout=timedelta(minutes=1)))
Exemplo n.º 2
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))
Exemplo n.º 3
0
def start_register(update, content):
    try:
        um = update.message
        message_id = um.message_id
        chat_id = um.chat_id
        admin = um.from_user.id

        text = um.text
        text = text.split()

        group_id = text[0]
        name = text[1]
        if group_id.startswith(
                '-') and group_id[1:].isnumeric() and name.startswith('@'):
            user = um.from_user.username if um.from_user.username else admin

            channel = db.Channel(name=name,
                                 admin=admin,
                                 group_id=int(group_id),
                                 plan=1,
                                 expire=timedelta(days=7))
            db.add(channel)
            content.bot.send_message(chat_id=chat_id,
                                     text="user {} registered\n\n{}".format(
                                         user, channel.__str__()))
            content.bot.send_message(chat_id=chat_id,
                                     text=strings.start_test_register_true,
                                     reply_to_message_id=message_id)

            return ConversationHandler.END
        else:
            content.bot.send_message(chat_id=chat_id,
                                     text=strings.start_test_register_false)

            return start_register
    except Exception as E:
        logging.error("start_register {}".format(E))
Exemplo n.º 4
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))
Exemplo n.º 5
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))