Discordia Documentation

repository·master·Indexed 20 days ago

https://github.com/sinisterrectus/discordia

A high-level, object-oriented Lua wrapper for the official Discord RESTful API, designed for the Luvit runtime environment. It provides an event-driven interface using the Client class to manage gateway intents, shards, and Discord entities such as Users, Guilds, and Channels. The library utilizes Lua coroutines to enable a synchronous coding style while maintaining asynchronous non-blocking I/O for HTTP and WebSockets.

Tokens
2.4K
Snippets
5
Records
10
Agent score
73%

What's inside Discordia

  1. How Discordia's event-driven interface works

    master

    Discordia provides an object-oriented, event-driven interface. You interact with the Client object by attaching callbacks to specific events using the client:on(eventName, callback) pattern.

    Common patterns include:

    • ready: Triggered when the bot has successfully logged in and is ready to interact with the API.
    • messageCreate: Triggered when a new message is sent in a channel the bot can see. The callback receives a message object which provides access to message.content and message.channel.
  2. Install Discordia and Luvit

    master

    Discordia requires the Luvit runtime environment.

    1. Install Luvit: Visit https://luvit.io and follow the platform-specific instructions.
    2. Install Discordia: Use the lit package manager to install the library via:
      lit install SinisterRectus/discordia
    3. Run your bot: Execute your Lua script using the luvit command:
      luvit bot.lua
    lit install SinisterRectus/discordia
  3. Configure dynamic libraries for Windows

    master

    Discordia relies on dynamic libraries loaded via LuaJIT's ffi.load. If you are running on Windows, you must perform the following steps to ensure libopus and libsodium are correctly loaded:

    1. Rename the files:
      • Rename libopus to opus.dll.
      • Rename libsodium to sodium.dll.
    2. Placement: Place these .dll files in a directory accessible to the application. If you are unsure which directory to use, place them in your main application directory.
    3. Architecture Match: Ensure you are using the version of the library that matches your system architecture. You can verify your current architecture in Lua using jit.arch.
    print(jit.arch) -- Check your architecture (e.g., 'x64', 'x86')
  4. How the Client manages shards

    master

    The Client can manage multiple shards to handle large numbers of guilds.

    • Automatic Sharding: If shardCount is set to a value greater than 0, the client will attempt to launch that many shards.
    • Shard Range: You can specify a specific range of shards to manage using firstShard and lastShard. For example, if you have 10 shards but only want this process to handle shards 5 through 7, set firstShard = 5 and lastShard = 7.
    • Concurrency: Discordia uses coroutines and a libuv event loop to allow multiple shards to operate concurrently within a single process.
    • Properties:
      • client.shardCount: The number of shards this client is currently managing.
      • client.totalShardCount: The total number of shards the user is on (provided by Discord).
  5. Initialize and run a Discordia Client

    master

    The Client class is the main entry point for a Discordia application. To start a client, you must instantiate it with an options table and then call the run method with your Discord token.

    Important Lifecycle Note: Most client data and methods should not be accessed or called until after the ready event has been received. Base emitter methods (like on, emit, info, error) can be called at any time.

    To configure the client, you can pass an options table to the constructor. Common options include:

    • gatewayIntents: A number representing the intents to enable (defaults to all non-privileged intents).
    • shardCount: The number of shards to manage.
    • logLevel: The logging verbosity.
    • cacheAllMembers: Whether to cache all members (requires guildMembers intent).
    • autoReconnect: Whether to automatically reconnect on disconnect.
    local Client = require('client')
    
    local client = Client({
      gatewayIntents = 3243773, -- example intents
      cacheAllMembers = true
    })
    
    client:on('ready', function() 
      print('Connected as ' .. client.user.username)
    end)
    
    client:run('YOUR_DISCORD_TOKEN')
  6. Create a basic Discord bot with Discordia

    master

    To use Discordia, require the module, instantiate a discordia.Client(), register event listeners using the :on method, and start the bot using :run().

    Discordia uses Lua coroutines to allow you to write code in a synchronous, blocking style while the underlying I/O (HTTP and WebSockets) remains asynchronous and non-blocking.

    local discordia = require('discordia')
    local client = discordia.Client()
    
    client:on('ready', function()
    	print('Logged in as '.. client.user.username)
    end)
    
    client:on('messageCreate', function(message)
    	if message.content == '!ping' then
    		message.channel:send('Pong!')
    	end
    end)
    
    client:run('Bot INSERT_TOKEN_HERE')
  7. Client Configuration Options Reference

    master

    When initializing a Client, you can provide a table of options. The following keys are supported:

    KeyTypeDefaultDescription
    routeDelaynumber250Delay for API routes
    maxRetriesnumber5Maximum number of retries for failed requests
    shardCountnumber0Number of shards to manage
    firstShardnumber0The ID of the first shard to launch
    lastShardnumber-1The ID of the last shard to launch
    largeThresholdnumber100Threshold for large data handling
    cacheAllMembersbooleanfalseWhether to cache all members (requires guildMembers intent)
    autoReconnectbooleantrueWhether to automatically reconnect on disconnect
    compressbooleantrueWhether to use compression
    bitratenumber64000Bitrate for voice connections
    logFilestring'discordia.log'Path to the log file
    logLevelenumlogLevel.infoLogging verbosity
    gatewayFilestring'gateway.json'File used to cache gateway information
    dateTimestring'%F %T'Date/time format for logs
    syncGuildsbooleanfalseWhether to sync guilds
    gatewayIntentsnumber3243773Bitmask of gateway intents to use
  8. Retrieve Discord objects (Users, Guilds, Channels, etc.)

    master

    The Client provides several methods to retrieve Discord entities. These methods behave differently depending on whether the object is cached or requires an API request.

    Cached Retrieval (Fast, no API call)

    Use these methods to get objects that the client is already tracking via the gateway. If the object is not in the cache, these return nil.

    • Client:getGuild(id): Returns a Guild object.
    • Client:getChannel(id): Returns a Channel object (text, voice, category, or private).
    • Client:getRole(id): Returns a Role object.
    • Client:getEmoji(id): Returns an Emoji object.
    • Client:getSticker(id): Returns a Sticker object.

    API-based Retrieval (May perform HTTP request)

    Use these methods when you need an object that might not be in the local cache.

    • Client:getUser(id): Returns a User object. If cached, returns the cached version; otherwise, performs an HTTP request and caches the result.
    • Client:getWebhook(id): Returns a Webhook object via HTTP request (not cached).
    • Client:getInvite(code, counts): Returns an Invite object via HTTP request (not cached).

    Accessing Caches Directly

    You can also access the internal caches via properties:

    • client.users: Cache of all visible User objects.
    • client.guilds: Cache of all visible Guild objects.
    • client.privateChannels: Cache of all opened private channels.
    • client.groupChannels: Cache of all group DM channels (user accounts only).
    • client.relationships: Cache of all visible relationships (user accounts only).
  9. Manage Gateway Intents

    master

    Gateway intents control which events your client receives from Discord. You can manage them using the following methods. Note that changes to intents will not take effect until the client re-identifies (restarts/reconnects).

    • Client:enableIntents(...args): Enables one or more individual intents.
    • Client:disableIntents(...args): Disables one or more individual intents.
    • Client:enableAllIntents(): Enables all known gateway intents.
    • Client:disableAllIntents(): Disables all intents (sets to 0).
    • Client:getIntents(): Returns the current bitmask of enabled intents.
  10. Set User Presence (Status and Activity)

    master

    You can update your client's presence (status and activity) using the following methods. These updates are sent to all managed shards.

    • Client:setStatus(status): Sets the status (e.g., 'online', 'idle', 'dnd', or nil to remove). Passing 'idle' automatically sets a since timestamp.
    • Client:setActivity(activity): Sets the current activity.
      • If passed a string, it is treated as the activity name.
      • If passed a table, it must have a name field and can optionally include url or type.
      • Passing nil removes the activity.
    • Client:setAFK(afk): Sets the AFK status (boolean).
    • Client:setGame(game): (Deprecated) Use setActivity instead.
    -- Set status to idle and activity to 'Playing Lua'
    client:setStatus('idle')
    client:setActivity('Playing Lua')
    
    -- Set a complex activity (e.g., streaming)
    client:setActivity({
      name = 'My Stream',
      type = 1, -- streaming
      url = 'https://twitch.tv/example'
    })