Skip to content

Commit

Permalink
add post-listener & add example
Browse files Browse the repository at this point in the history
  • Loading branch information
Bilal2453 committed Dec 1, 2024
1 parent 696b70d commit 048c30b
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 5 deletions.
70 changes: 70 additions & 0 deletions examples/latency-example.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
--[[
Usage: send `!new-button` command to get a message with components.
Pressing the buttons will do stuff!
]]

local timer = require 'timer'
local discordia = require 'discordia'
require 'discordia-interactions'

local client = discordia.Client()
client:enableIntents('messageContent')

local Stopwatch = discordia.Stopwatch

client:on('messageCreate', function (msg)
-- Use discordia-extensions instead of this!
-- this is just to get the example working
if msg.content == '!new-button' then
client._api:createMessage(msg.channel.id, {
content = 'Here is a button!',
components = {
{
type = 1,
components = {
{
type = 2,
label = 'API Ping',
style = 1,
custom_id = 'api_ping',
},
{
type = 2,
label = 'API Ping Message',
style = 3,
custom_id = 'api_ping_msg',
},
},
},
}
})
end
end)

---@param intr Interaction
client:on('interactionCreate', function (intr)
if intr.data.custom_id == 'api_ping' then
local sw = Stopwatch()
local msg, err = intr:replyDeferred(true)
sw:stop()
if not msg then
return print(err)
end
intr:reply('The API latency (one-way) is ' .. (sw:getTime() / 2):toString())
timer.sleep(3000)
intr:deleteReply()
elseif intr.data.custom_id == 'api_ping_msg' then
local sw = Stopwatch()
local msg, err = intr:reply('Calculating latency...')
sw:stop()
if not msg then
return print(err)
end
intr:editReply('The API latency (one-way) is ' .. (sw:getTime() / 2):toString())
timer.sleep(3000)
intr:deleteReply()
end
end)

client:run('Bot TOKEN')
17 changes: 12 additions & 5 deletions libs/client/EventHandler.lua
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
local Interaction = require("containers/Interaction")
local events = {
interaction_create_prelisteners = {}
interaction_create_prelisteners = {},
interaction_create_postlisteners = {},
}

local function emitListeners(listeners, ...)
for _, v in pairs(listeners) do
v(...)
end
end

function events.INTERACTION_CREATE(d, client)
local interaction = Interaction(d, client)
for _, v in pairs(events.interaction_create_prelisteners) do
v(interaction, client)
end
return client:emit("interactionCreate", interaction)
emitListeners(events.interaction_create_prelisteners, interaction, client)
client:emit("interactionCreate", interaction)
emitListeners(events.interaction_create_postlisteners, interaction, client)
end

-- This code is part of Discordia
local function checkReady(shard)
for _, v in pairs(shard._loading) do
if next(v) then return end
Expand Down

0 comments on commit 048c30b

Please sign in to comment.