summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 4bd15fe7017bc0a2a6e189c73bf55097a67a5821 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
const types = @import("types.zig");
const std = @import("std");

const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Bot = @import("Bot.zig");
const Config = @import("Config.zig");
const GPA = std.heap.GeneralPurposeAllocator(.{});

pub fn main() !void {
    defer std.log.info("We're done", .{});

    var gpa = GPA{};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();

    // Load config
    var config = try Config.load(allocator, "config.default.json");
    defer config.deinit();
    try config.merge("config.json");

    var bot = try Bot.init(allocator, config.config);
    defer bot.deinit();

    // TODO: Catch fatal errors, report them
    try wrappedMain(&bot);
}

fn loadConfig(allocator: Allocator, filename: []const u8) !std.json.Parsed(Config) {
    const file = try std.fs.cwd().openFile(filename, .{});
    defer file.close();

    var reader = std.json.reader(allocator, file.reader());
    defer reader.deinit();

    return try std.json.parseFromTokenSource(
        Config,
        allocator,
        &reader,
        .{
            .duplicate_field_behavior = .use_last,
            .ignore_unknown_fields = true,
            .allocate = .alloc_always,
        },
    );
}

fn wrappedMain(bot: *Bot) !void {
    try bot.sendMessage_(.{
        .chat_id = bot.config.dev_group,
        .text = "Initializing...",
    });

    try bot.setMyName(.{ .name = "Ukko's bot" });

    var gup = types.GetUpdatesParams{ .timeout = 60 };
    while (bot.poweron) {
        // TODO: Catch major errors, report them (and crash after 5 of them or so)
        const updates = try bot.getUpdates(gup);
        defer updates.deinit();
        for (updates.value) |update| {
            defer gup.offset = update.update_id + 1;

            if (update.message) |message| {
                // TODO: Catch minor errors, report them
                try onMessage(bot, message);
            }
        }
    }

    // one last getUpdates to make sure offset is saved
    gup.timeout = 0;
    gup.limit = 1;
    (try bot.getUpdates(gup)).deinit();

    try bot.sendMessage_(.{
        .chat_id = bot.config.dev_group,
        .text = "Shutting down...",
    });
}

fn onMessage(bot: *Bot, msg: types.Message) !void {
    if (msg.text) |text| {
        try onTextMessage(bot, msg, text);
    }

    if (msg.new_chat_members) |new_chat_members| {
        for (new_chat_members) |new_chat_member| {
            try onNewMember(bot, msg, new_chat_member);
        }
    }
}

fn onNewMember(bot: *Bot, msg: types.Message, new_member: types.User) !void {
    var sb = ArrayList(u8).init(bot.allocator);
    defer sb.deinit();

    const w = sb.writer();

    try w.writeAll("Hello there, ");
    try new_member.writeFormattedName(w);
    try w.writeAll("!  Be on your bestest behaviour now!!");

    try bot.sendMessage_(.{
        .chat_id = msg.chat.id,
        .text = sb.items,
        .parse_mode = .html,
        .reply_parameters = .{
            .allow_sending_without_reply = true,
            .message_id = msg.message_id,
            .chat_id = msg.chat.id,
        },
    });
}

fn isBadText(text: []const u8) bool {
    _ = text;
    return false;
}

fn onTextMessage(bot: *Bot, msg: types.Message, text: []const u8) !void {
    if (isBadText(text)) {
        // TODO: Delete message, mute & warn user
        // 0 current warns: 5 minute mute, +1 warn
        // 1 current warn : 10 minute mute, +1 warn
        // 2 current warns: 30 minute mute, +1 warn
        // 3 current warns: 1 hour mute, +1 warn
        // 4 current warns: 1 day mute, +1 warn
        // 5 current warns: Ban
        //
        // warn gets removed after a month of no warns
        //
        // Lines to say in response:
        // Your head will be my new trophy!
        // Your cursed bloodline ends here!
        // This is the end of you, s'wit!
        // Your life's end is approaching.
        // Surrender your life to me and I will end your pain!
        // Your pain is nearing an end.
        // May our Lords be merciful!
        // You have sealed your fate!
        // You cannot escape the righteous!
        // You will pay with your blood!
        // You will die.
        // There is no escape.
        // Die, fetcher.
        // I shall enjoy watching you take your last breath.
        // You'll soon be nothing more than a bad memory!
        // You will die in disgrace.
        // I'll see you dead.
        // One of us will die here and it won't be me.
        // You don't deserve to live.
        // Surrender now and I might let you live!
        // I will bathe in your blood.
        // Your bones will be my dinner.
        // So small and tasty. I will enjoy eating you.
        return;
    }

    if (msg.entities) |entities| {
        for (entities) |entity| {
            if (entity.type == .bot_command and entity.offset == 0) {
                const cmd = try entity.extract(text);
                try onTextCommand(bot, msg, text, cmd);
            }
        }
    }

    if (std.mem.eql(u8, text, ":3")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = ">:3",
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.mem.eql(u8, text, ">:3")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "<b>&gt;:3</b>",
            .parse_mode = .html,
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.startsWithIgnoreCase(text, "big ")) {
        var output = try bot.allocator.alloc(u8, text.len + 3);
        defer bot.allocator.free(output);

        std.mem.copyForwards(u8, output, "<b>");
        _ = std.ascii.upperString(output[3..], text[4..]);
        std.mem.copyForwards(u8, output[output.len - 4 ..], "</b>");

        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = output,
            .parse_mode = .html,
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.eqlIgnoreCase(text, "forgor")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "💀",
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.eqlIgnoreCase(text, "huh")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "idgi",
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.mem.eql(u8, text, "H")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "<code>Randomly selected reminder that h &gt; H.</code>",
            .parse_mode = .html,
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.startsWithIgnoreCase(text, "say ")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = text[4..],
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.eqlIgnoreCase(text, "uwu")) {
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "OwO",
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.eqlIgnoreCase(text, "waow")) {
        const reply_to = if (msg.reply_to_message) |r|
            r.message_id
        else
            msg.message_id;

        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED BASED",
            .reply_parameters = .{
                .message_id = reply_to,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.ascii.eqlIgnoreCase(text, "what")) {
        var sb = try ArrayList(u8).initCapacity(bot.allocator, 9);
        defer sb.deinit();

        if (text[0] == 'w') {
            sb.appendSliceAssumeCapacity("g");
        } else {
            sb.appendSliceAssumeCapacity("G");
        }
        if (text[1] == 'h') {
            sb.appendSliceAssumeCapacity("ood ");
        } else {
            sb.appendSliceAssumeCapacity("OOD ");
        }
        if (text[2] == 'a') {
            sb.appendSliceAssumeCapacity("gir");
        } else {
            sb.appendSliceAssumeCapacity("GIR");
        }
        if (text[3] == 't') {
            sb.appendSliceAssumeCapacity("l");
        } else {
            sb.appendSliceAssumeCapacity("L");
        }

        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = sb.items,
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    }
}

fn onTextCommand(bot: *Bot, msg: types.Message, text: []const u8, cmd: []const u8) !void {
    _ = text;

    const simple_cmd = if (std.mem.indexOfScalar(u8, cmd, '@')) |idx| blk: {
        const cmd_username = cmd[idx + 1 ..];
        if (!std.mem.eql(u8, cmd_username, try bot.getUsername())) {
            return;
        }
        break :blk cmd[1..idx];
    } else cmd[1..];

    // TODO: StaticStringMap :)
    if (std.mem.eql(u8, simple_cmd, "chatid")) {
        var sb = ArrayList(u8).init(bot.allocator);
        defer sb.deinit();
        try sb.writer().print("<code>{}</code>", .{msg.chat.id});

        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = sb.items,
            .parse_mode = .html,
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    } else if (std.mem.eql(u8, simple_cmd, "ping")) {
        var timer = try std.time.Timer.start();

        var sb = ArrayList(u8).init(bot.allocator);
        defer sb.deinit();
        try sb.writer().print("Pong!\nSend time: ...", .{});

        const reply = try bot.sendMessage(.{
            .chat_id = msg.chat.id,
            .text = sb.items,
            .reply_parameters = .{
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
        defer reply.deinit();

        const send = @as(f64, @floatFromInt(timer.read())) / std.time.ns_per_ms;
        sb.clearRetainingCapacity();
        try sb.writer().print("Pong!\n\nSend time: {d}ms", .{send});

        try bot.editMessageText_(.{
            .chat_id = reply.value.chat.id,
            .message_id = reply.value.message_id,
            .text = sb.items,
        });
    } else if (std.mem.eql(u8, simple_cmd, "shutdown")) blk: {
        if (msg.from == null or msg.from.?.id != bot.config.owner) {
            break :blk;
        }

        bot.poweron = false;
        try bot.sendMessage_(.{
            .chat_id = msg.chat.id,
            .text = "Initialising shutdown...",
            .reply_parameters = .{
                .allow_sending_without_reply = true,
                .message_id = msg.message_id,
                .chat_id = msg.chat.id,
            },
        });
    }
}