Esempio n. 1
0
 def __init__(self, order: asyncpg.Record) -> None:
     self.order_id = int(order.get('order_id'))
     self.weight = float(order.get('weight'))
     self.region = int(order.get('region'))
     self.delivery_hours = [
         TimeSpan(time_) for time_ in order.get('delivery_hours')
     ]
Esempio n. 2
0
    def __init__(self, status: asyncpg.Record) -> None:
        self.id = int(status.get('id'))
        self.courier_id = int(status.get('courier_id'))
        self.order_id = int(status.get('order_id'))

        if assigned_time := status.get('assigned_time', None):
            self.assigned_time = parse_date(assigned_time)
Esempio n. 3
0
    def __init__(self, ctx, record: asyncpg.Record):
        super().__init__(ctx)
        self.member_id = record["member_id"]
        self.render_settings = get_user_settings(self.member_id)

        # Attributes for the User object (Needs to be constructed with the data fetched from the database)
        self.fame = record["fame"]
        self.created_at = record["created_at"]

        self.sex = record["sex"]
        self.preference = record["preference"]
        self.birth = record["birth"]
        self.age = self.calculate_age(record["birth"])
        self.name = record["name"]
        self.country = record["country"]
        self.bio = record["bio"]

        # Like limits
        self.likes = record.get("likes")
        self.superlikes = record.get("superlikes")
        # These will have a value if it has been fetched when swiping
        self.compat = record.get("compat")

        # if we're using a specific filter
        self.filter = record.get("filter")
 def _from_db_full(auth_code: Record) -> AuthCode:
     account_main_dict = filter_keys_by_substr(auth_code, ACCOUNT_MAIN)
     return AuthCode(id=auth_code.get(AUTH_CODE_ID),
                     created_at=auth_code.get(AUTH_CODE_CREATED_AT),
                     edited_at=auth_code.get(AUTH_CODE_EDITED_AT),
                     account_main=AccountMainDeserializer.deserialize(
                         account_main_dict, DES_ACCOUNT_MAIN_FROM_DB_FULL),
                     code=auth_code.get(AUTH_CODE_CODE))
def load_record(r: Record) -> FnRecord:
    fn_name = r.get("fn_name")
    args = [s.strip() for s in r.get("args").split(",")]

    def to_fn_arg(arg_str: str) -> FnArg:
        parts = arg_str.split(" ")
        return FnArg(name=parts[0], type=parts[1])

    return FnRecord(name=fn_name, args=[to_fn_arg(arg) for arg in args])
Esempio n. 6
0
 def deserialize(self, rowdata: Record) -> None:
     self.level = rowdata.get('level')
     self.message = rowdata.get('message')
     self.pid = rowdata.get('pid')
     self.time = datetime.utcfromtimestamp(rowdata.get('time'))
     self.function_id = rowdata.get('functionID')
     self.logger_id = rowdata.get('loggerID')
     self.hostname_id = rowdata.get('hostnameID')
def _parse_record(record: Record) -> Optional[tuple]:
    """
    Parse a asyncpg Record object to a tuple of values
    :param record: the asyncpg Record object
    :return: the tuple of values if it's not None, else None
    """
    try:
        return tuple(record.values())
    except AttributeError:
        return None
Esempio n. 8
0
    async def _modify_entry(self,
                            ctx,
                            user: UserProfile,
                            swipe: bool,
                            entry: asyncpg.Record,
                            superlike=False):
        # Update fame for the target if it was swiped right on
        if swipe:
            fame = 1
            # Gives more fame if you superlike someone
            if superlike:
                fame = 3
            query = "UPDATE users SET fame=$1 WHERE member_id = $2"
            await ctx.db.execute(query, user.fame + fame, user.member_id)

        # If the entry exists
        if entry:
            superlike = entry.get("superlike", False)
            status = entry["status"]

            # It's a match
            if status and swipe:

                # dispatches the image creation and sending of the matched image
                self.bot.loop.create_task(self.match(ctx, user))

                # delete the targets entry, and the authors if an entry existed since earlier
                query = "DELETE FROM entries WHERE (member_id = $1 AND target_id = $2) OR (member_id = $2 AND target_id = $1)"
                await ctx.db.execute(query, ctx.author.id, user.member_id)

                # we also add an entry to the matches table
                query = "INSERT INTO matches (source_id, target_id, date) VALUES ($1, $2, $3)"
                await ctx.db.execute(query, ctx.author.id, user.member_id,
                                     datetime.now())

                #Return as we do not need to do any insertion or updating of previous entries
                return

        # If we had an earlier entry with this user, we update it if we didn't match
        compat = user.compat
        if compat is not None:
            # If we disliked, we up the compat
            if not swipe:
                compat += 1
            query = "UPDATE entries SET status = $1, date = $2, compat = $3, superlike = $4 WHERE member_id = $5 AND target_id = $6"
            await ctx.db.execute(query, swipe, datetime.now(), compat,
                                 superlike, ctx.author.id, user.member_id)

        # If it's a new user, we have to add an entry if we didn't match
        else:
            query = "INSERT INTO entries (member_id, target_id, status, date, compat, superlike) VALUES ($1, $2, $3, $4, $5, $6)"
            await ctx.db.execute(query, ctx.author.id, user.member_id, swipe,
                                 datetime.now(), 0, superlike)
Esempio n. 9
0
 def __init__(self, courier: asyncpg.Record) -> None:
     self.courier_id = int(courier.get('courier_id'))
     self.courier_type = courier.get('type')
     self.regions = [int(region) for region in courier.get('regions')]
     self.working_hours = [
         TimeSpan(time_) for time_ in courier.get('working_hours')
     ]
     self.coeff = int(courier.get('c'))
     self.payload = int(courier.get('payload'))
Esempio n. 10
0
def record_to_model(record: Record, model_class: ModelType) -> Model:
    """Convert a Record object to Model object.

    Args:
        record (Record): Record object.
        model_class (ModelType): Model class

    Returns:
        Model: Model instance.
    """
    new_record = model_class()
    for k, v in record.items():
        new_record.Meta._fromdb_.append(k)
        setattr(new_record, k, v)
    return new_record
Esempio n. 11
0
 def converter(record: asyncpg.Record):
     return clazz(**dict([(field, record.get(field))
                          for field in field_names]))  # type: ignore
Esempio n. 12
0
 def deserialize(self, rowdata: Record) -> None:
     self.name = rowdata.get('name')
Esempio n. 13
0
    def __init__(self, bot: commands.Bot, row: asyncpg.Record):
        self.__guild_id: int = row.get(_COLUMN_NAME_GUILD_ID)
        self.__prefix: str = row.get(_COLUMN_NAME_PREFIX)
        self.__use_pagination: bool = row.get(_COLUMN_NAME_USE_PAGINATION)
        daily_channel_id = row.get(_COLUMN_NAME_DAILY_CHANNEL_ID)
        can_post_daily = row.get(_COLUMN_NAME_DAILY_CAN_POST)
        daily_latest_message_id = row.get(_COLUMN_NAME_DAILY_LATEST_MESSAGE_ID)
        daily_post_mode = row.get(_COLUMN_NAME_DAILY_DELETE_ON_CHANGE)
        daily_notify_id = row.get(_COLUMN_NAME_DAILY_NOTIFY_ID)
        daily_notify_type = convert_to_autodaily_notify_type(
            row.get(_COLUMN_NAME_DAILY_NOTIFY_TYPE))
        daily_latest_message_created_at = row.get(
            _COLUMN_NAME_DAILY_LATEST_MESSAGE_CREATED_AT)
        daily_latest_message_modified_at = row.get(
            _COLUMN_NAME_DAILY_LATEST_MESSAGE_MODIFIED_AT)

        try:
            channel = bot.get_channel(daily_channel_id)
        except Exception as error:
            channel = None
            print(f'Could not get channel for id {daily_channel_id}: {error}')
        if channel is None and daily_channel_id is not None:
            print(f'Could not get channel for id {daily_channel_id}')

        try:
            self.__guild = bot.get_guild(self.__guild_id)
        except Exception as error:
            self.__guild = None
            print(f'Could not get guild for id {self.__guild_id}: {error}')
        if self.__guild is None and self.__guild_id is not None:
            print(f'Could not get channel for id {daily_channel_id}')

        notify = None
        if daily_notify_id and daily_notify_type and self.__guild:
            if daily_notify_type == AutoDailyNotifyType.USER:
                notify = self.__guild.get_member(daily_notify_id)
            elif daily_notify_type == AutoDailyNotifyType.ROLE:
                notify = self.__guild.get_role(daily_notify_id)

        self.__autodaily_settings: AutoDailySettings = AutoDailySettings(
            self.__guild, channel, can_post_daily, daily_latest_message_id,
            daily_post_mode, notify, daily_latest_message_created_at,
            daily_latest_message_modified_at)
Esempio n. 14
0
 def from_record(cls: Type[T], record: Record) -> T:
     """Converts a database record (row) to entity of this type."""
     # Pass all values (including id) to constructor as named arguments
     return cls(**dict(record.items()))  # type: ignore
Esempio n. 15
0
 def process_row_dict(row: asyncpg.Record) -> Dict[str, Any]:
     d = dict(row)
     del d[list(row.keys())[remove]]
     return d
Esempio n. 16
0
def record_to_activation(record: Record):
    return Activation(identifier=record['identifier'],
                      reading_identifier=record['reading_identifier'],
                      activation_count=record['activation_count'],
                      sensor_identifier=record['sensor_identifier'],
                      timestamp=record.get('timestamp', None))
Esempio n. 17
0
    def __init__(self, bot: Bot, row: asyncpg.Record) -> None:
        self.__bot = bot
        self.__guild_id: int = row.get(_COLUMN_NAME_GUILD_ID)
        self.__prefix: str = row.get(_COLUMN_NAME_PREFIX)
        self.__use_pagination: bool = row.get(_COLUMN_NAME_USE_PAGINATION)
        self.__bot_news_channel_id: int = row.get(_COLUMN_NAME_BOT_NEWS_CHANNEL_ID)
        self.__use_embeds: bool = row.get(_COLUMN_NAME_USE_EMBEDS)

        self.__guild: Guild = None
        self.__bot_news_channel: TextChannel = None

        daily_channel_id = row.get(_COLUMN_NAME_DAILY_CHANNEL_ID)
        can_post_daily = row.get(_COLUMN_NAME_DAILY_CAN_POST)
        daily_latest_message_id = row.get(_COLUMN_NAME_DAILY_LATEST_MESSAGE_ID)
        daily_post_mode = row.get(_COLUMN_NAME_DAILY_CHANGE_MODE)
        daily_latest_message_created_at = row.get(_COLUMN_NAME_DAILY_LATEST_MESSAGE_CREATED_AT)
        daily_latest_message_modified_at = row.get(_COLUMN_NAME_DAILY_LATEST_MESSAGE_MODIFIED_AT)

        self.__autodaily_settings: AutoDailySettings = AutoDailySettings(self.__bot, self.__guild_id, daily_channel_id, can_post_daily, daily_latest_message_id, daily_post_mode, daily_latest_message_created_at, daily_latest_message_modified_at)
Esempio n. 18
0
 def process_row_single(row: asyncpg.Record) -> Any:
     return row[0 if next(iter(row.keys())) != remove else 1] if len(
         row) > 1 else None
Esempio n. 19
0
def as_box(record: asyncpg.Record) -> Box:
    return Box(record.items())
Esempio n. 20
0
 async def populate_cleaning_feed_item(self, *, cleaning_feed_item: Record) -> CleaningFeedItem:
     return CleaningFeedItem(
         **{k: v for k, v in cleaning_feed_item.items() if k != "owner"},
         owner=await self.users_repo.get_user_by_id(user_id=cleaning_feed_item["owner"])
     )
Esempio n. 21
0
 def deserialize(self, rowdata: Record) -> None:
     self.path = rowdata.get('path')
Esempio n. 22
0
    def __init__(self, bot: commands.Bot, row: asyncpg.Record):
        self.__guild_id: int = row.get(_COLUMN_NAME_GUILD_ID)
        self.__prefix: str = row.get(_COLUMN_NAME_PREFIX)
        self.__use_pagination: bool = row.get(_COLUMN_NAME_USE_PAGINATION)
        self.__bot_news_channel_id: int = row.get(
            _COLUMN_NAME_BOT_NEWS_CHANNEL_ID)
        self.__use_embeds: bool = row.get(_COLUMN_NAME_USE_EMBEDS)

        self.__guild: discord.Guild = None
        self.__bot_news_channel: discord.TextChannel = None

        daily_channel_id = row.get(_COLUMN_NAME_DAILY_CHANNEL_ID)
        can_post_daily = row.get(_COLUMN_NAME_DAILY_CAN_POST)
        daily_latest_message_id = row.get(_COLUMN_NAME_DAILY_LATEST_MESSAGE_ID)
        daily_post_mode = row.get(_COLUMN_NAME_DAILY_CHANGE_MODE)
        daily_latest_message_created_at = row.get(
            _COLUMN_NAME_DAILY_LATEST_MESSAGE_CREATED_AT)
        daily_latest_message_modified_at = row.get(
            _COLUMN_NAME_DAILY_LATEST_MESSAGE_MODIFIED_AT)

        try:
            channel = bot.get_channel(daily_channel_id)
        except Exception as error:
            channel = None
            print(f'Could not get channel for id {daily_channel_id}: {error}')
        if channel is None and daily_channel_id is not None:
            print(f'Could not get channel for id {daily_channel_id}')

        try:
            self.__guild = bot.get_guild(self.__guild_id)
        except Exception as error:
            self.__guild = None
            print(f'Could not get guild for id {self.__guild_id}: {error}')
        if self.__guild is None and self.__guild_id is not None:
            print(f'Could not get channel for id {daily_channel_id}')

        try:
            self.__bot_news_channel = bot.get_channel(
                self.__bot_news_channel_id)
        except Exception as error:
            self.__bot_news_channel = None
            print(
                f'Could not get channel for id {self.__bot_news_channel_id}: {error}'
            )
        if self.__bot_news_channel is None and self.__bot_news_channel_id is not None:
            print(f'Could not get channel for id {self.__bot_news_channel_id}')

        self.__autodaily_settings: AutoDailySettings = AutoDailySettings(
            self.__guild, channel, can_post_daily, daily_latest_message_id,
            daily_post_mode, daily_latest_message_created_at,
            daily_latest_message_modified_at)