示例#1
0
    def __init__(self, settings, **kwargs):
        self.settings = settings
        super().__init__(
            self.settings["PREFIX"], **kwargs
        )  # This just runs the original commands.Bot __init__ function.

        self.Scheduler = Scheduler()  # Handles commands that run on timers.
        self.ReactiveMessageManager = ReactiveMessageManager(self)

        self.owner_id = self.settings["OWNER_ID"]  # Who owns the bot
        self.uptime_seconds = helpers.time_now(
        )  # Used to check how long the bot has been active for
        self.uptime_datetime = datetime.now()

        # Used for the "core" help command, which is called with c.help. Any non-specific commands are placed here.
        # This relies on dictionaries maintaining their declared order, rather than taking their hash order.
        self.core_help_text = {
            "modules": [],
            "General": [],
        }
        self.core_help_text = defaultdict(list, **self.core_help_text)

        # Assigned in start(), as they run on a different thread.
        self.db = None
        self.cursor = None
示例#2
0
    async def uptime(self, ctx):
        if not await self.bot.has_perm(ctx, dm=True): return
        uptime = helpers.time_now() - self.bot.uptime_seconds
        uptime_string = helpers.time_to_string(seconds=uptime)
        uptime_start = self.bot.uptime_datetime.strftime("%Y/%m/%d T %H:%M:%S")

        await ctx.send(f"{uptime_string}; Started at: {uptime_start}")
示例#3
0
    async def create_reactive_message(self, message, message_page_function: Callable, message_pages: list,
                                *, page_back: str = "◀️", page_forward: str = "▶️", cancel: str = "🇽",
                                on_message_func: Callable = None, users: List[int] = None,
                                seconds_active: int = 20, wrap: bool = True,
                                custom_reactions=None):
        """

        Arguments:
            message - The discord message object that should respond to reactions.
            message_page_function - A function that generates the new message, when given a page.
            message_pages - The data to provide to message_page_function.
            reaction_previous - Reaction that calls previous page
            reaction_next - Reaction that calls next page.

            seconds_active - How long the will react for.
            wrap - Whether to wrap to the start page when we reach the end.
            users - A list of user IDs
            custom_reactions - A dictionary of emoji:function
        """
        current_time = time_now()
        await message.add_reaction(page_back)
        await message.add_reaction(page_forward)
        await message.add_reaction(cancel)
        custom_reactions = {} if custom_reactions is None else custom_reactions
        for r in custom_reactions:
            await message.add_reaction(r)

        rm = ReactingMessage(message, on_message_func, message_page_function, message_pages, page_back, page_forward, cancel,
                             0, wrap, current_time, seconds_active, users, custom_reactions)
        self.reacting_message[message.id] = rm
示例#4
0
 async def save_word(self, reacting_message, user_id):
     """Called on a `define word` by pressing the little save emoji."""
     d = reacting_message.message_pages[reacting_message.page_num]
     data = (d.search_term, d.definition, d.example, d.part_of_speech,
             d.phonetic, user_id, helpers.time_now())
     self.bot.cursor.execute(
         "INSERT INTO saved_definitions VALUES(?,?,?,?,?,?,?)", data)
     self.bot.cursor.execute("commit")
     await reacting_message.message.channel.send(
         content=f"­ЪњЙ Saved! Use `c.dict.saved` to view!")
示例#5
0
    def generate_schedule(self):
        """Creates a schedule from self.timed_functions."""
        new_schedule = []
        time = helpers.time_now()  # Current Unix Epoch time.
        for function, timer in self.timed_functions:
            event = ScheduledEvent(function, timer)
            try:
                event.update_time(time)
            except TypeError as e:
                print(e)
            new_schedule.append(event)

        return sorted(new_schedule)
示例#6
0
    async def on_user_update(self, before, after):
        old_name = before.name
        new_name = after.name
        time = helpers.time_now()
        user_id = after.id
        guild_id = 0

        if old_name == new_name:
            return

        c = self.bot.cursor
        c.execute("""INSERT INTO username_history VALUES(?,?,?,?,?)""",
                  (old_name, new_name, guild_id, user_id, time))
        c.execute("commit")
示例#7
0
def update_db_hotels_by_destination(dest):
    data = _request_hotel(destination=dest)
    combined_details = []
    for _, hotel in data.items():
        detail = _merge_hotel_info(hotel)
        save_hotel_to_db(detail)
        combined_details.append(detail)

    db.ascenda.dest_update.update_one(
        {DOCUMENT_KEY_DESTINATION: dest},
        {'$set': {
            DOCUMENT_KEY_UPDATE_AT: time_now()
        }},
        upsert=True)
    return jsonify(combined_details)
示例#8
0
 async def start(self):
     """
     Main loop.
     Will continually check each ScheduledEvent and run if necessary.
     """
     self.schedule = self.generate_schedule()
     if not self.schedule:
         print("No scheduled functions.")
         return
     while True:
         await asyncio.sleep(self.schedule_time)
         time_now = helpers.time_now()  # Current Unix Epoch time.
         while time_now > self.schedule[0].time:
             # FIXME: If an event's time doesn't increase this will cause an infinite loop.
             #  Will never come up through proper use of the Scheduler, but should be prevented still.
             #  Could maybe limit how many times something is allowed to repeat in one tick.
             event = self.schedule[0]
             await event.function(time_now)
             event.update_time(time_now)
             self.schedule = sorted(
                 self.schedule)  # Find the next most recent event
示例#9
0
 def get_page(self) -> str:
     page = self.message_pages[self.page_num]
     self.started_time = time_now()
     return self.message_page_function(page)
示例#10
0
def save_hotel_to_db(hotel_json):
    hotel_json.update({DOCUMENT_KEY_UPDATE_AT: time_now()})
    db.ascenda.hotels.update_one(
        {DOCUMENT_KEY_ID: hotel_json[DOCUMENT_KEY_ID]}, {'$set': hotel_json},
        upsert=True)