1 |
#define _GNU_SOURCE |
2 |
|
3 |
#include <stdio.h> |
4 |
#include <stdbool.h> |
5 |
#include <stdlib.h> |
6 |
#include <assert.h> |
7 |
#include <signal.h> |
8 |
#include <concord/discord.h> |
9 |
#include "io/log.h" |
10 |
#include "env.h" |
11 |
|
12 |
#include "events/on_ready.h" |
13 |
#include "events/on_message.h" |
14 |
#include "events/on_interaction.h" |
15 |
#include "utils/strutils.h" |
16 |
#include "core/command.h" |
17 |
#include "utils/utils.h" |
18 |
#include "sudobot.h" |
19 |
|
20 |
#define ENV_BOT_TOKEN "TOKEN" |
21 |
|
22 |
static const uint64_t INTENTS = DISCORD_GATEWAY_GUILD_MESSAGES | |
23 |
DISCORD_GATEWAY_GUILD_MEMBERS | |
24 |
DISCORD_GATEWAY_GUILDS | |
25 |
DISCORD_GATEWAY_MESSAGE_CONTENT; |
26 |
|
27 |
struct discord *client; |
28 |
env_t *env = { 0 }; |
29 |
|
30 |
void sudobot_atexit() |
31 |
{ |
32 |
discord_cleanup(client); |
33 |
env_free(env); |
34 |
} |
35 |
|
36 |
void sudobot_sigterm_handler() |
37 |
{ |
38 |
log_info("SIGTERM received. Exiting"); |
39 |
exit(EXIT_SUCCESS); |
40 |
} |
41 |
|
42 |
void sudobot_setup_signal_handlers() |
43 |
{ |
44 |
struct sigaction act = {0}; |
45 |
act.sa_handler = &sudobot_sigterm_handler; |
46 |
|
47 |
if (sigaction(SIGTERM, &act, NULL) != 0) |
48 |
{ |
49 |
log_error("Failed to set up signal handlers: %s", get_last_error()); |
50 |
exit(EXIT_FAILURE); |
51 |
} |
52 |
} |
53 |
|
54 |
bool sudobot_start_with_token(const char *token) |
55 |
{ |
56 |
assert(token != NULL && "Token must not be null"); |
57 |
client = discord_init(token); |
58 |
atexit(&sudobot_atexit); |
59 |
sudobot_setup_signal_handlers(); |
60 |
|
61 |
log_info("Attempting to boot..."); |
62 |
discord_add_intents(client, INTENTS); |
63 |
discord_set_on_interaction_create(client, &on_interaction_create); |
64 |
discord_set_on_message_create(client, &on_message); |
65 |
discord_set_on_ready(client, &on_ready); |
66 |
discord_run(client); |
67 |
|
68 |
return true; |
69 |
} |
70 |
|
71 |
bool sudobot_start() |
72 |
{ |
73 |
env = env_init(); |
74 |
|
75 |
if (!env_load(env)) |
76 |
{ |
77 |
log_fatal("env: parse error: %s", env->error); |
78 |
env_free(env); |
79 |
return false; |
80 |
} |
81 |
|
82 |
const char *token = env_get(env, ENV_BOT_TOKEN); |
83 |
|
84 |
if (token == NULL) |
85 |
{ |
86 |
log_error("No environment variable named `" ENV_BOT_TOKEN "` is present. Please set it and then rerun the bot."); |
87 |
return false; |
88 |
} |
89 |
|
90 |
return sudobot_start_with_token(token); |
91 |
} |