Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto shutdown and restart bot periodically #51

Merged
merged 1 commit into from
Apr 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion script/run.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
#!/bin/bash
# Start the HoJBot program

if [[ -z "$HOJBOT_DISCORD_TOKEN" ]]; then
echo "Error: please set up HOJBOT_DISCORD_TOKEN environment variable"
exit 1
fi

julia --project=. -e 'using HoJBot; start_bot();'
# Default environment settings
: ${RUN_ONCE=no}
: ${RUN_DURATION_MINUTES=360}

while true; do
echo "`date`: Starting HoJBot..."
julia --project=. -e "using HoJBot, Dates; start_bot(; run_duration = Minute(${RUN_DURATION_MINUTES}));"
if [[ "$RUN_ONCE" == "yes" ]]; then
break
fi
sleep 1 # throttle to avoid a hot loop when the process keep crashing
done
echo "`date`: Program exited normally"
19 changes: 19 additions & 0 deletions src/main.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ end
function start_bot(;
commands = active_commands,
handlers = handlers_list,
run_duration = Days(365), # run for a very long time by default
)
@info "Starting bot... command prefix = $COMMAND_PREFIX"
global client = Client(ENV["HOJBOT_DISCORD_TOKEN"];
Expand All @@ -56,6 +57,7 @@ function start_bot(;
init_commands!(client, commands)
# add_help!(client; help = help_message())
open(client)
auto_shutdown(run_duration)
wait(client)
end

Expand All @@ -71,6 +73,23 @@ function init_commands!(client::Client, commands)
end
end

"""
auto_shutdown(run_duration::TimePeriod)

Run a background process to track the program's run time and exit
the program when it has exceeded the specified `run_duration`.
"""
function auto_shutdown(run_duration::TimePeriod)
start_time = now()
@async while true
if now() > start_time + run_duration
@info "Times up! The bot is shutting down automatically."
exit(0)
end
sleep(5)
end
end

commander(c::Client, m::Message, service) =
begin
@info "commander" c m service
Expand Down