Skip to content

Commit

Permalink
Host an HTTP server for heartbeat instead of creating a file
Browse files Browse the repository at this point in the history
  • Loading branch information
gepbird committed Jan 15, 2024
1 parent 7e41752 commit dcb687b
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 11 deletions.
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# Sensitive files
*.env
token.json
storage.db
logs
backups
.heartbeat

# Generated files
obj
Expand Down
2 changes: 2 additions & 0 deletions Environment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class Environment
public List<ulong> Owners { get; set; } = default!;
public TimeSpan BackupInterval { get; set; } = default!;
public int BackupsToKeep { get; set; } = default!;
public int StatusPort { get; set; } = default!;

public static async Task<Environment> Load()
{
Expand All @@ -38,6 +39,7 @@ public static async Task<Environment> Load()
.ToList(),
BackupInterval = TimeSpan.FromMinutes(int.Parse(GetEnv("BACKUP_INTERVAL_MINUTES"))),
BackupsToKeep = int.Parse(GetEnv("BACKUPS_TO_KEEP")),
StatusPort = int.Parse(GetEnv("STATUS_PORT")),
};
}

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ SERVERID=<DISCORD_SERVER_ID>
OWNERS=<DISCORD_USER_ID>
BACKUP_INTERVAL_MINUTES=60
BACKUPS_TO_KEEP=50
STATUS_PORT=8000
```

Replace the placeholders enclosed in angle brackets with their appropriate value. You can get the **Server ID** by right clicking on a server and choosing Copy ID. Same concept applies to **User ID**s. You probably want to assign your user's ID to **OWNERS**.
Expand Down Expand Up @@ -98,6 +99,7 @@ To tell the bot which configuration should it use, run it with `--development` o
- OWNERS: Comma separated list of User IDs who have full access to the bot. Overrides [modranks](#modranks).
- BACKUP_INTERVAL_MINUTES: Minutes between automatic database backups.
- BACKUPS_TO_KEEP: Delete old backups after the number of backups exceeds this.
- STATUS_PORT: Start a web server on this port to appear online for status services.

Commands (including slash commands and context commands) are registered at guild (discord server) scope when using development mode, and global scope when using production mode. Global command registration may take a few seconds or minutes due to Discord's API, but guild scoped commands are almost instant. In order to register commands, you need to run the bot with `--register-commands` parameter. The reason why registering commands is not the default is Discord can rate limit the bot when it tries to register commands over and over again in a short period of time. This can be annoying when debugging.

Expand Down
19 changes: 10 additions & 9 deletions Services/HeartbeatService.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Net;
using Discord;

namespace Moe.Services;
Expand All @@ -8,23 +9,23 @@ public void Init()
{
Task.Run(async () =>
{
HttpListener listener = new HttpListener();
var url = $"http://localhost:{ConfigService.Environment.StatusPort}/";
listener.Prefixes.Add(url);
listener.Start();
await LogService.LogToFileAndConsole($"HTTP server started on {url}");

while (true)
{
if (DiscordService.Discord.ConnectionState != ConnectionState.Connected)
{
continue;
}

var seconds = GetSecondsSinceEpoch().ToString();
File.WriteAllText(".heartbeat", seconds);
await Task.Delay(1000);
HttpListenerContext context = listener.GetContext();
// return 200
context.Response.OutputStream.Close();
}
});
}

private int GetSecondsSinceEpoch()
{
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
return (int)t.TotalSeconds;
}
}

0 comments on commit dcb687b

Please sign in to comment.