Exemplo n.º 1
0
    def test_others(self):
        self.assertTrue(JalaliDateTime.fromtimestamp(time.time()) <= JalaliDateTime.now())
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc).timestamp(), 578723400)
        self.assertEqual(JalaliDateTime.fromtimestamp(578723400, pytz.utc),
                         JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc))
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).jdate(), JalaliDate(1367, 2, 14))
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).date(), date(1988, 5, 4))
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).replace(tzinfo=pytz.utc).__repr__(),
                         'JalaliDateTime(1367, 2, 14, 4, 30, tzinfo=<UTC>)')
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).replace(year=1395, day=3, minute=59),
                         JalaliDateTime(1395, 2, 3, 4, 59, 4, 4444))

        self.assertEqual(JalaliDateTime.now(pytz.utc).tzname(), "UTC")
        self.assertIsNone(JalaliDateTime.today().tzname())
        self.assertIsNone(JalaliDateTime.today().dst())

        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).ctime(), "Chaharshanbeh 14 Ordibehesht 1367 04:30:00")
        self.assertEqual(JalaliDateTime(1396, 7, 27, 21, 48, 0, 0).ctime(), "Panjshanbeh 27 Mehr 1396 21:48:00")
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).replace(locale="fa").ctime(),
                         "چهارشنبه ۱۴ اردیبهشت ۱۳۶۷ ۰۴:۳۰:۰۰")

        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).isoformat(),
                         "1367-02-14T04:30:00.000001+00:00")
        self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).__str__(),
                         "1367-02-14 04:30:00.000001+00:00")
Exemplo n.º 2
0
    def test_others(self):
        self.assertTrue(
            JalaliDateTime.fromtimestamp(time.time() -
                                         10) <= JalaliDateTime.now())
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc).timestamp(),
            578723400)
        self.assertEqual(
            JalaliDateTime.fromtimestamp(578723400, pytz.utc),
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc),
        )
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).jdate(),
            JalaliDate(1367, 2, 14))
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).date(),
            date(1988, 5, 4))
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 0,
                           0).replace(tzinfo=pytz.utc).__repr__(),
            "JalaliDateTime(1367, 2, 14, 4, 30, tzinfo=<UTC>)",
        )
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).replace(year=1395,
                                                                day=3,
                                                                minute=59),
            JalaliDateTime(1395, 2, 3, 4, 59, 4, 4444),
        )

        self.assertEqual(JalaliDateTime.now(pytz.utc).tzname(), "UTC")
        self.assertIsNone(JalaliDateTime.today().tzname())
        self.assertIsNone(JalaliDateTime.today().dst())

        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).ctime(),
            "Chaharshanbeh 14 Ordibehesht 1367 04:30:00",
        )
        self.assertEqual(
            JalaliDateTime(1396, 7, 27, 21, 48, 0, 0).ctime(),
            "Panjshanbeh 27 Mehr 1396 21:48:00",
        )
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 0,
                           0).replace(locale="fa").ctime(),
            "چهارشنبه ۱۴ اردیبهشت ۱۳۶۷ ۰۴:۳۰:۰۰",
        )
        self.assertEqual(
            JalaliDateTime(1397, 12, 1, 23, 32, 0,
                           0).replace(locale="fa").ctime(),
            "چهارشنبه ۰۱ اسفند ۱۳۹۷ ۲۳:۳۲:۰۰",
        )

        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).isoformat(),
            "1367-02-14T04:30:00.000001+00:00",
        )
        self.assertEqual(
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).__str__(),
            "1367-02-14 04:30:00.000001+00:00",
        )
Exemplo n.º 3
0
    def test_base(self):
        self.assertEqual(JalaliDateTime(1367, 2, 14, 14, 0, 0, 0),
                         JalaliDateTime.to_jalali(datetime(1988, 5, 4, 14, 0, 0, 0)))
        self.assertEqual(JalaliDateTime(1369, 7, 1, 14, 14, 1, 1111),
                         JalaliDateTime(datetime(1990, 9, 23, 14, 14, 1, 1111)))
        self.assertEqual(JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111),
                         JalaliDateTime(JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111)))

        g = JalaliDateTime.now()
        self.assertEqual(g.time(), _time(g.hour, g.minute, g.second, g.microsecond))

        g = g.replace(tzinfo=pytz.timezone("America/Los_Angeles"))
        self.assertEqual(g.timetz(),
                         _time(g.hour, g.minute, g.second, g.microsecond, pytz.timezone("America/Los_Angeles")))

        self.assertEqual(JalaliDateTime.fromtimestamp(578723400, pytz.utc),
                         JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc))
        self.assertEqual(JalaliDateTime.utcfromtimestamp(578723400), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0))

        try:
            JalaliDateTime._check_time_fields(20, 1, 61, 1000)
        except ValueError:
            assert True
        else:
            assert False

        try:
            JalaliDateTime._check_time_fields("20", 1, 61, 1000)
        except TypeError:
            assert True
        else:
            assert False
Exemplo n.º 4
0
    def test_base(self):
        self.assertEqual(
            JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111),
            JalaliDateTime(JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111)),
        )

        g = JalaliDateTime.now()
        self.assertEqual(g.time(),
                         _time(g.hour, g.minute, g.second, g.microsecond))

        g = g.replace(tzinfo=pytz.timezone("America/Los_Angeles"))
        self.assertEqual(
            g.timetz(),
            _time(
                g.hour,
                g.minute,
                g.second,
                g.microsecond,
                pytz.timezone("America/Los_Angeles"),
            ),
        )

        self.assertEqual(
            JalaliDateTime.fromtimestamp(578723400, pytz.utc),
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc),
        )
        self.assertEqual(
            JalaliDateTime.utcfromtimestamp(578723400),
            JalaliDateTime(1367, 2, 14, 4, 30, 0, 0),
        )

        with pytest.raises(TypeError):
            JalaliDateTime._check_time_fields("20", 1, 61, 1000)

        with pytest.raises(ValueError):
            JalaliDateTime(1367, 2, 14, 25, 0, 0, 0)

        with pytest.raises(ValueError):
            JalaliDateTime(1367, 2, 14, 22, 61, 0, 0)

        with pytest.raises(ValueError):
            JalaliDateTime(1367, 2, 14, 22, 1, 722, 0)

        with pytest.raises(ValueError):
            JalaliDateTime(1367, 2, 14, 22, 1, 0, 1000000)
Exemplo n.º 5
0
    async def forward_handler(self, new_forward: NewMessage.Event):
        try:
            print(type(new_forward))
            await new_forward.reply("👌")

            forward_from = await self.client.get_entity(
                new_forward.message.forward.chat.id)
            print(forward_from)

            channel = None
            for auto_channel in self.auto_channels:
                if auto_channel.origin.id == forward_from.id:
                    channel = auto_channel.channel
                    break

            invite_link = ''
            if channel:
                try:
                    # noinspection PyTypeChecker
                    invite_link = (await
                                   self.client(ExportChatInviteRequest(channel)
                                               )).link
                except Exception as e:
                    print(e)

            if not invite_link:
                created_private_channel = await self.client(
                    CreateChannelRequest(forward_from.title + '*',
                                         '',
                                         megagroup=False))
                channel_id = created_private_channel.chats[0].id
                new_channel_access_hash = created_private_channel.chats[
                    0].access_hash
                print(new_channel_access_hash, channel_id)

                channel = await self.client.get_entity(channel_id)

                auto_channel = AutoChannel(channel, forward_from, {})
                self.auto_channels.append(auto_channel)

                db_users.update_one({'_id': self.db_id}, {
                    '$push': {
                        'autoChannels': {
                            'origin': forward_from.id,
                            'channel': channel_id,
                            'messagesMap': [],
                        }
                    }
                })

                # noinspection PyTypeChecker
                invite_link = (await
                               self.client(ExportChatInviteRequest(channel)
                                           )).link
                print(invite_link)
                await self.client.send_message(
                    self.me,
                    "**Your channel is created, but it's not ready yet:**\n%s\n\n"
                    "Go [there](%s) and see the magic process. You should be patient until reach the"
                    "most recent post __(to estimate when, see stamped date on the foot of each "
                    "incoming post)__." % (invite_link, invite_link))

                # pull history from original chat:
                reversed_messages = []
                # Avoid `FloodWaitError` (70 messages per each 5 minutes MAX!):
                async for message in self.client.iter_messages(forward_from,
                                                               limit=600):
                    if type(message) == MessageService:
                        print(message)
                        continue
                    if message.date < new_forward.message.forward.date:
                        break
                    reversed_messages.append(message)

                # send history for new channel:
                messages = reversed(reversed_messages)
                pushed_to_map = []

                try:
                    i = 0
                    for message in messages:
                        i += 1
                        j = i / 2
                        while j.is_integer():
                            print(i)
                            await asyncio.sleep(0.5)
                            j = j / 2

                        date_time_stamp = '`' + en_to_fa(  # Use timestamp-converting to avoid time-zone issues:
                            JalaliDateTime.fromtimestamp(
                                message.date.timestamp()).strftime(
                                    '%Y/%m/%d %H:%M')) + '`'

                        sent_message = await self.send_message(
                            date_time_stamp, message,
                            auto_channel.messages_map, channel, forward_from,
                            False)

                        pushed_to_map.append({
                            'origin': message.id,
                            'channel': sent_message.id
                        })

                    db_users.update_one(
                        {
                            '_id': self.db_id,
                            'autoChannels': {
                                '$elemMatch': {
                                    'channel': channel.id
                                }
                            }
                        }, {
                            '$push': {
                                'autoChannels.$.messagesMap': {
                                    '$each': pushed_to_map
                                }
                            }
                        })
                except FloodWaitError:
                    print(traceback.format_exc(), file=sys.stderr)
                    return

            # noinspection PyUnboundLocalVariable
            await self.set_event_handlers(channel, forward_from,
                                          auto_channel.messages_map)

            self.client.remove_event_handler(forward_from)

            await self.client.send_message(
                self.me, '**Your channel is ready!** 👇\n' + invite_link)
        except:
            print(traceback.format_exc(), file=sys.stderr)
            try:
                await self.client.send_message(self.me,
                                               'Unexpected error # 1894')
            except:
                print(traceback.format_exc(), file=sys.stderr)
Exemplo n.º 6
0
from datetime import timedelta
from persiantools.jdatetime import JalaliDateTime, JalaliDate
import pytz
import time


one_hour_in_ms = 60 * 60 * 1000
one_day_in_ms = one_hour_in_ms * 24
get_current_epoch = lambda : int(round(time.time() * 1000))
get_tehran_tzinfo_by_epoch = lambda e: JalaliDateTime.fromtimestamp(e//1000, pytz.timezone("Asia/Tehran")).tzinfo # will be used indirectly and by other functions
now = JalaliDateTime.now(tz=get_tehran_tzinfo_by_epoch(get_current_epoch()))

jalali_to_gregorian = lambda j: j.to_gregorian().date() # needed when using plotly

epoch_to_jalali = lambda e: JalaliDateTime.fromtimestamp(e/1000, tz=get_tehran_tzinfo_by_epoch(e)) 

def utc_date_to_jalali(year, month, day):
    return JalaliDate.to_jalali(year, month, day)

def jalali_to_epoch(year, month, day=1, hour=0, minute=0, second=0, milliseconds=0):
    tehran_tzinfo = get_tehran_tzinfo_by_epoch(int(JalaliDateTime(year, month, day, hour, minute, second, milliseconds*1000).timestamp() * 1000))
    return int(JalaliDateTime(year, month, day, hour, minute, second, milliseconds*1000, tzinfo=tehran_tzinfo).timestamp() * 1000)

today_epoch = jalali_to_epoch(now.year, now.month, now.day)
# ---------------------------------------------------------
def back_days_epoch(n):
    d = now - timedelta(days = n)
    e = jalali_to_epoch(d.year, d.month, d.day)
    x = epoch_to_jalali(e)
    if x.hour == 23:
        e += one_hour_in_ms
Exemplo n.º 7
0
    def process(self, path) -> None:
        err_begin = "ANALYZER ( " + path + " ): "
        print(err_begin, "STARTED")
        data: dict = Analyzer.read_temp(path)
        if data is None:
            Analyzer.annihilate(path)
            print(err_begin, "This temp file is corrupted!")
            return
        data["state"] = 1
        Analyzer.save_temp(path, data)
        if data["timeframe"] is not None:
            table = ("s" + str(data["sym"]) + "_" +
                     fn.tf_name(data["timeframe"])).lower()
        else:
            table = None
        if data["action"] == "insert":
            c = dt.cur(True)
            c.execute("SELECT name FROM symbol WHERE id='" + str(data["sym"]) +
                      "' LIMIT 1")
            found = c.fetchone()
            dt.cur(False)
            if len(found) == 0:
                Analyzer.annihilate(path)
                print(err_begin,
                      "Could not find this symbol in the database!!!")
                return
            found = found[0]
            rates = mt5.copy_rates_range(
                found, data["timeframe"],
                datetime.fromtimestamp(data["start"], tz=utc),
                datetime.fromtimestamp(data["end"], tz=utc))
            if rates is None:
                Analyzer.annihilate(path)
                try:
                    print(err_begin, str(mt5.last_error()))
                    print("DETAILS:", str(data))
                except:
                    print(err_begin, "UNKNOWN ERROR!")
                return
            if len(rates) > 0:
                data: List[tuple] = list()
                for r in rates:
                    # time, open, high, close, tick_volume, spread, real_volume
                    unix = int(r["time"])
                    greg = datetime.fromtimestamp(unix, tz=utc)
                    jala = JalaliDateTime.fromtimestamp(unix, tz=utc)
                    data.append(
                        (int(r["time"]), float(r["open"]), float(r["close"]),
                         float(r["high"]), float(r["low"]),
                         int(r['tick_volume']), int(r['spread']),
                         int(r['real_volume']), greg.strftime("%Y.%m.%d"),
                         jala.strftime("%Y.%m.%d"), greg.strftime("%H:%M")))
            else:
                Analyzer.annihilate(path)
                print(err_begin, "No candles were found!")
                return
            c = dt.cur(True)
            c.execute(
                "SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';"
            )
            if table not in fn.tables(c):
                try:
                    c.execute(
                        "CREATE TABLE " + table +
                        " (unix BIGINT NOT NULL PRIMARY KEY, " +
                        "open FLOAT, close FLOAT, high FLOAT, low FLOAT, " +
                        "tick_volume INT, spread INT, real_volume BIGINT, " +
                        "greg VARCHAR(10), jala VARCHAR(10), time VARCHAR(5))")
                except sqlite3.OperationalError:
                    pass  # already exists
            for d in data:
                try:
                    c.execute(
                        "INSERT INTO " + table +
                        " (unix, open, close, high, low, tick_volume, spread, real_volume, "
                        + "greg, jala, time) " +
                        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", d)
                except sqlite3.IntegrityError:
                    pass
            dt.connect.commit()
            dt.cur(False)

        elif data["action"] == "delete":
            c = dt.cur(True)
            c.execute(
                "SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';"
            )
            tables = fn.tables(c)
            if data["start"] is not None and data["end"] is not None:
                c.execute(
                    "SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';"
                )
                if table in tables:
                    c.execute("DELETE FROM " + table + " WHERE unix BETWEEN " +
                              str(data["start"]) + " AND " + str(data["end"]))
                else:
                    dt.cur(False)
                    raise dt.SaamError("Such table does not exist!")
            elif data["timeframe"] is not None:
                if table in tables:
                    c.execute("TRUNCATE TABLE " + table)
                else:
                    dt.cur(False)
                    raise dt.SaamError("Such table does not exist!")
            else:
                for tfr in dt.config["timeframes"]:
                    c.execute("DROP TABLE IF EXISTS " +
                              ("s" + str(data["sym"]) + "_" +
                               tfr["name"]).lower())
            dt.cur(False)
        Analyzer.annihilate(path)
        print(err_begin, "DONE")