Snippets

Sandu Liviu Catalin SqMod IRC Example

Created by Sandu Liviu Catalin last modified
  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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/* ------------------------------------------------------------------------------------------------
 * Enumeration used to have a standard set of user authority levels across the script.
*/
enum IrcAuthority
{
    // Unregistered user with least privileges
    Guest = 0,
    // Registered user with normal privileges
    User = 1,
    // Regular user with high visits and activity
    Addict = 2,
    // Regular user with bonus features and privileges
    Subscriber = 3,
    // First level of staff with minimal privileges
    Intern = 4,
    // Second level of staff with moderate privileges
    Moderator = 5,
    // Third level of staff with maximum privileges
    Administrator = 6,
    // Highest privileged user with access to everything
    SystemOperator = 7
}

// Listen to when the script was successfully loaded and connect to an IRC network
function onScriptLoaded()
{
    // Add an administrator
    g_Irc.SetStaff("SLC", IrcAuthority.SystemOperator);
    // Connect to a network
    g_Irc.Connect("irc.liberty-unleashed.co.uk", 6667, "SquirrelBot");
}

SqCore.Bind(SqEvent.ScriptLoaded, this, onScriptLoaded);


/* ------------------------------------------------------------------------------------------------
 * Class responsible for managing an IRC session session.
*/
class MyIRC extends SqIRC.Session
{
    /* --------------------------------------------------------------------------------------------
     * List of people who can send commands.
    */
    m_Staff = null;

    /* --------------------------------------------------------------------------------------------
     * Base constructor.
    */
    function constructor(name)
    {
        // Validate the name
        if (typeof(name) != "string")
        {
            SqLog.Err("Unknown or unsupported argument type");
            SqLog.Inf("=> Expected: (string) Got: (%s)", typeof(name));
            // Construction failed
            throw "Invalid IRC session name";
        }
        // Forward the call to the base session constructor.
        base.constructor();
        // Tell the session to clean the nicks before giving them to us
        base.SetOption(SqIrcOpt.StripNicks);
        // Bind to the session events
        base.Bind(SqIrcEvent.Connect,       this, onConnect);
        base.Bind(SqIrcEvent.Nick,          this, onNick);
        base.Bind(SqIrcEvent.Quit,          this, onQuit);
        base.Bind(SqIrcEvent.Join,          this, onJoin);
        base.Bind(SqIrcEvent.Part,          this, onPart);
        base.Bind(SqIrcEvent.Mode,          this, onMode);
        base.Bind(SqIrcEvent.Umode,         this, onUmode);
        base.Bind(SqIrcEvent.Topic,         this, onTopic);
        base.Bind(SqIrcEvent.Kick,          this, onKick);
        base.Bind(SqIrcEvent.Channel,       this, onChannel);
        base.Bind(SqIrcEvent.PrivMsg,       this, onPrivMsg);
        base.Bind(SqIrcEvent.Notice,        this, onNotice);
        base.Bind(SqIrcEvent.ChannelNotice, this, onChannelNotice);
        base.Bind(SqIrcEvent.Invite,        this, onInvite);
        //base.Bind(SqIrcEvent.CtcpReq,       this, onCtcpReq);
        //base.Bind(SqIrcEvent.CtcpRep,       this, onCtcpRep);
        //base.Bind(SqIrcEvent.CtcpAction,    this, onCtcpAction);
        base.Bind(SqIrcEvent.Unknown,       this, onUnknown);
        base.Bind(SqIrcEvent.Numeric,       this, onNumeric);
        // Save the name used in identifying where the output came from.
        this.Tag = name;
        // Initialize the staff to an empty table
        m_Staff = { /* ... */ };
    }

    function onConnect(event, origin, params)
    {
        // Specify that the IRC session was successfully connected
        SqLog.Scs(SqStr.Center('-', 72, " IRC CONNECTED "));
        // Output various other information about the connection
        SqLog.Inf("Server:  %s:%d", this.Server, this.Port);
        SqLog.Inf("Nick:    %s", this.Nick);
        SqLog.Inf("User:    %s", this.User);
        SqLog.Inf("Name:    %s", this.Name);
        // Now that we're connected to a network we can join channels
        if (base.CmdJoin("#SLC") != 0)
        {
            SqLog.Err("Unable to join channel: %s", session.ErrStr); 
        }
    }

    function onNick(event, origin, params)
    {
        SqLog.Inf("%s is now known as %s", origin, params[0]);
    }

    function onQuit(event, origin, params)
    {
        if (params.len() >= 1)
        {
            SqLog.Inf("%s has quit (%s)", origin, params[0]);
        }
        else
        {
            SqLog.Inf("%s has quit", origin);
        }
    }

    function onJoin(event, origin, params)
    {
        SqLog.Inf("%s joined %s", origin, params[0]);
    }

    function onPart(event, origin, params)
    {
        if (params.len() >= 2)
        {
            SqLog.Inf("%s left %s (%s)", origin, params[0], params[1]);
        }
        else
        {
            SqLog.Inf("%s left %s (Leaving...)", origin, params[0]);
        }
    }

    function onMode(event, origin, params)
    {
        if (params.len() >= 2)
        {
            SqLog.Inf("%s set modes %s on %s", origin, params[1], params[0]);
        }
        else
        {
            SqLog.Inf("%s changed modes on %s", origin, params[0]);
        }
    }

    function onUmode(event, origin, params)
    {
        if (params.len() >= 2)
        {
            SqLog.Inf("%s set modes %s for %s", origin, params[1], this.Nick);
        }
        else
        {
            SqLog.Inf("%s changed modes for %s", origin, this.Nick);
        }
    }

    function onTopic(event, origin, params)
    {
        SqLog.Inf("%s changed topic on %s", origin, params[0]);
        // Show the topic if one was specified
        if (params.len() >= 2)
        {
            SqLog.Inf("New topic is: %s", origin, params[1]);
        }
    }

    function onKick(event, origin, params)
    {
        if (params.len() >= 3)
        {
            SqLog.Inf("%s kicked %s from %s (%s)", origin, params[1], params[0], params[2]);
        }
        else if (params.len() >= 2)
        {
            SqLog.Inf("%s kicked %s from %s", origin, params[1], params[0]);
        }
        else
        {
            SqLog.Inf("%s kicked someone from %s", origin, params[0]);
        }
    }

    function onChannel(event, origin, params)
    {
        if (params.len() >= 1)
        {
            // Is this a command?
            if (params[1][0] == '.')
            {
                g_Ircmd.Run({"origin" : origin, "channel" : params[0]}, params[1].slice(1));
            }
            else
            {
                SqLog.Inf("%s said on %s : %s", origin, params[0], params[1]);
            }
        }
        else
        {
            SqLog.Inf("%s said something on %s", origin, params[0]);
        }
    }

    function onPrivMsg(event, origin, params)
    {
        if (params.len() >= 1)
        {
            // Is this a command?
            if (params[1][0] == '.')
            {
                g_Ircmd.Run({"origin" : origin, "channel" : origin}, params[1].slice(1));
            }
            else
            {
                SqLog.Inf("%s said to %s : %s", origin, params[0], params[1]);
            }
        }
        else
        {
            SqLog.Inf("%s said something to %s", origin, params[0]);
        }
    }

    function onNotice(event, origin, params)
    {
        if (params.len() >= 1)
        {
            SqLog.Inf("%s sent notice to %s : %s", origin, params[0], params[1]);
        }
        else
        {
            SqLog.Inf("%s sent a notice to %s", origin, params[0]);
        }
    }

    function onChannelNotice(event, origin, params)
    {
        if (params.len() >= 1)
        {
            SqLog.Inf("%s sent notice on %s : %s", origin, params[0], params[1]);
        }
        else
        {
            SqLog.Inf("%s sent a notice on %s", origin, params[0]);
        }
    }

    function onInvite(event, origin, params)
    {
        if (params.len() >= 2)
        {
            SqLog.Inf("%s invited %s on %s" origin, params[0], params[1]);
        }
        else
        {
            SqLog.Inf("%s invited %s" origin, params[0]);
        }
    }

    function onCtcpReq(event, origin, params)
    {
        // Not yet implemented...
    }

    function onCtcpRep(event, origin, params)
    {
        // Not yet implemented...
    }

    function onCtcpAction(event, origin, params)
    {
        // Not yet implemented...
    }

    function onUnknown(event, origin, params)
    {
        //SqLog.Inf("Unknown event received from %s" origin);
    }

    function onNumeric(event, origin, params)
    {
        switch (event)
        {
            case SqIrcRFC.RPL_CHANNELMODEIS:
            {
                print("Received RPL_CHANNELMODEIS from server");
                foreach (idx, val in params)
                {
                    printf("=> Arg %d contains: '%s'", idx, val);
                }
            } break;
            case SqIrcRFC.RPL_UMODEIS:
            {
                print("Received RPL_UMODEIS from server");
                foreach (idx, val in params)
                {
                    printf("=> Arg %d contains: '%s'", idx, val);
                }
            } break;
        }
    }

    // Staff list
    function SetStaff(name, level)
    {
        m_Staff.rawset(name.tostring(), level.tointeger());
    }

    function GetStaff(name)
    {
        name  = name.tostring();

        if (m_Staff.rawin(name))
        {
            return m_Staff.rawget(name);
        }

        return IrcAuthority.Guest;
    }

    function RemoveStaff(name)
    {
        name  = name.tostring();

        if (m_Staff.rawin(name))
        {
            n_Staff.rawdelete(name);
        }
    }
}



// Create an uninitialized instance of our IRC manager
g_Irc <- MyIRC("SquirrelBot");



/* ------------------------------------------------------------------------------------------------
 * The main IRC related command manager.
*/
g_Ircmd <- SqCmd.Manager();

/* ------------------------------------------------------------------------------------------------
 * Bind a function to handle command errors.
*/
g_Ircmd.BindFail(this, function(type, msg, payload) {
    // Retrieve the origin of the invocation
    local origin = g_Ircmd.Invoker.origin;
    // See if the invoker even exists
    if (typeof(origin) != "string" || origin.len() <= 0)
    {
        return; // No one to report!
    }
    // Identify the error type
    switch (type)
    {
        // The command failed for unknown reasons
        case SqCmdErr.Unknown:
        {
            g_Irc.CmdMsg(origin, "Unable to execute the command for reasons unknown");
            g_Irc.CmdMsg(origin, "=> Please contact the owner: no_email@to.me");
        } break;
        // The command failed to execute because there was nothing to execute
        case SqCmdErr.EmptyCommand:
        {
            g_Irc.CmdMsg(origin, "Cannot execute an empty command");
        } break;
        // The command failed to execute because the command name was invalid after processing
        case SqCmdErr.InvalidCommand:
        {
            g_Irc.CmdMsg(origin, "The specified command name is invalid");
        } break;
        // The command failed to execute because there was a syntax error in the arguments
        case SqCmdErr.SyntaxError:
        {
            g_Irc.CmdMsg(origin, "There was a syntax error in one of the command arguments");
        } break;
        // The command failed to execute because there was no such command
        case SqCmdErr.UnknownCommand:
        {
            g_Irc.CmdMsg(origin, "The specified command does no exist");
        } break;
        // The command failed to execute because the it's currently suspended
        case SqCmdErr.ListenerSuspended:
        {
            g_Irc.CmdMsg(origin, "The requested command is currently suspended");
        } break;
        // The command failed to execute because the invoker does not have the proper authority
        case SqCmdErr.InsufficientAuth:
        {
            g_Irc.CmdMsg(origin, "You don't have the proper authority to execute this command");
        } break;
        // The command failed to execute because there was no callback to handle the execution
        case SqCmdErr.MissingExecuter:
        {
            g_Irc.CmdMsg(origin, "The specified command is not being processed");
        } break;
        // The command was unable to execute because the argument limit was not reached
        case SqCmdErr.IncompleteArgs:
        {
            g_Irc.CmdMsgF(origin, "The specified command requires at least %d arguments", payload);
        } break;
        // The command was unable to execute because the argument limit was exceeded
        case SqCmdErr.ExtraneousArgs:
        {
            g_Irc.CmdMsgF(origin, "The specified command can allows up to %d arguments", payload);
        } break;
        // Command was unable to execute due to argument type mismatch
        case SqCmdErr.UnsupportedArg:
        {
            g_Irc.CmdMsgF(origin, "Argument %d requires a different type than the one you specified", payload);
        } break;
        // The command arguments contained more data than the internal buffer can handle
        case SqCmdErr.BufferOverflow:
        {
            g_Irc.CmdMsg(origin, "An internal error occurred and the execution was aborted");
            g_Irc.CmdMsg(origin, "=> Please contact the owner: no_email@to.me");
        } break;
        // The command failed to complete execution due to a runtime exception
        case SqCmdErr.ExecutionFailed:
        {
            g_Irc.CmdMsg(origin, "The command failed to complete the execution properly");
            g_Irc.CmdMsg(origin, "=> Please contact the owner: no_email@to.me");
        } break;
        // The command completed the execution but returned a negative result
        case SqCmdErr.ExecutionAborted:
        {
            g_Irc.CmdMsg(origin, "The command execution was aborted and therefore had no effect");
        } break;
        // The post execution callback failed to execute due to a runtime exception
        case SqCmdErr.PostProcessingFailed:
        {
            g_Irc.CmdMsg(origin, "The command post-processing stage failed to complete properly");
            g_Irc.CmdMsg(origin, "=> Please contact the owner: no_email@to.me");
        } break;
        // The callback that was supposed to deal with the failure also failed due to a runtime exception
        case SqCmdErr.UnresolvedFailure:
        {
            g_Irc.CmdMsg(origin, "Unable to resolve the failures during command execution");
            g_Irc.CmdMsg(origin, "=> Please contact the owner: no_email@to.me");
        } break;
        // Something bad happened and no one knows what
        default:
            g_Irc.CmdMsgF(origin, "Command failed to execute because [%s]", msg);
    }
});

/* ------------------------------------------------------------------------------------------------
 * Bind a function to handle command authority inspection.
*/
g_Ircmd.BindAuth(this, function(invoker, command) {
    // Is the command something that we can check against?
    if (typeof(command) != "SqCmdListener")
    {
        return true; // Not our kind? Not our problem!
    }
    // The specified invoker must be a table with 2 elements 'origin' and 'channel'
    else if (typeof(invoker) != "table" || !invoker.rawin("origin") || !invoker.rawin("channel"))
    {
        return false; // Missing information
    }
    // Is the specified invoker something of a known type?
    else if (typeof(invoker.origin) != "string" || typeof(invoker.channel) != "string")
    {
        return false; // What is this thing?
    }
    // Use the default authority system to make the call
    return (g_Irc.GetStaff(invoker.origin) >= command.Authority);
});



/* ------------------------------------------------------------------------------------------------
 * Global table used to scope IRC commands.
*/
_Ircmd <- { /* ... */ }


/* ------------------------------------------------------------------------------------------------
 * Evaluate a piece of code on the server.
*/
_Ircmd.Eval <- g_Ircmd.Create("eval", "g", ["code"], 1, 1, IrcAuthority.SystemOperator, true, true);

// ------------------------------------------------------------------------------------------------
_Ircmd.Eval.Help = "Evaluate the specified code";

// ------------------------------------------------------------------------------------------------
_Ircmd.Eval.BindExec(_Ircmd.Eval, function(invoker, args)
{
    // Attempt to compile and execute the specified code
    try
    {
        ::compilestring(args.code)();
    }
    catch (e)
    {
        g_Irc.CmdMsg(invoker.origin, e.tostring());
    }
    // Specify that this command was successfully executed
    return true;
});



/* ------------------------------------------------------------------------------------------------
 * Say a certain message on the server.
*/
_Ircmd.Say <- g_Ircmd.Create("say", "g", ["text"], 1, 1, IrcAuthority.Moderator, true, true);

// ------------------------------------------------------------------------------------------------
_Ircmd.Say.Help = "Say the specified message";

// ------------------------------------------------------------------------------------------------
_Ircmd.Say.BindExec(_Ircmd.Say, function(invoker, args)
{
        // Say the message back to to the origin
        g_Irc.CmdMsg(invoker.channel, args.text);
        // Specify that this command was successfully executed
        return true;
});



/* ------------------------------------------------------------------------------------------------
 * Say a certain message on the server with the /me command.
*/
_Ircmd.Me <- g_Ircmd.Create("me", "g", ["text"], 1, 1, IrcAuthority.Moderator, true, true);

// ------------------------------------------------------------------------------------------------
_Ircmd.Me.Help = "Say the specified /me message";

// ------------------------------------------------------------------------------------------------
_Ircmd.Me.BindExec(_Ircmd.Me, function(invoker, args)
{
        // Say the message back to to the origin
        g_Irc.CmdMe(invoker.channel, args.text);
        // Specify that this command was successfully executed
        return true;
});



/* ------------------------------------------------------------------------------------------------
 * Retrieve the modes of a certain user or channel.
*/
_Ircmd.Mode <- g_Ircmd.Create("mode", "s", ["name"], 1, 1, IrcAuthority.User, true, true);

// ------------------------------------------------------------------------------------------------
_Ircmd.Mode.Help = "Retrieve the modes of a user or channel";

// ------------------------------------------------------------------------------------------------
_Ircmd.Mode.BindExec(_Ircmd.Mode, function(invoker, args)
{
        // Say the raw MODE <#channel/nick> command to retrieve the modes of a user/channel
        g_Irc.SendRaw("MODE " + args.name);
        // Specify that this command was successfully executed
        return true;
});

Comments (0)