Skip to content

Commit

Permalink
op: 10!
Browse files Browse the repository at this point in the history
  • Loading branch information
troit5ky committed Jul 30, 2022
0 parents commit 16e5e02
Show file tree
Hide file tree
Showing 7 changed files with 258 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Discord Relay for Garry's Mod

### How to install:
1. Install [GWSocket](https://github.com/FredyH/GWSockets/releases/) module
2. Install [CHTTP](https://github.com/timschumi/gmod-chttp/releases) module
3. Install this addon
4. Configurate in discord-realy/lua/cl_config.lua and discord-realy/lua/sv_config.lua
5. Done! Restart server
17 changes: 17 additions & 0 deletions lua/autorun/init.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
if SERVER then
include("sv_config.lua")
include("relay/sv_msgSend.lua")
include("relay/sv_msgGet.lua")

AddCSLuaFile('cl_config.lua')
AddCSLuaFile('relay/cl_msgReceive.lua')

print( "----------------------\n" )
print( "DISCORD RELAY LOADED!\n" )
print( "----------------------" )
end

if CLIENT then
include('cl_config.lua')
include('relay/cl_msgReceive.lua')
end
6 changes: 6 additions & 0 deletions lua/cl_config.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Discord = {
-- In CLIENT chat
['prefix'] = "Discord",

['prefixClr'] = Color(88, 101, 242),
}
5 changes: 5 additions & 0 deletions lua/relay/cl_msgReceive.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
net.Receive("!!discord-receive", function()
local msg = net.ReadTable()

chat.AddText( Discord.prefixClr, "["..Discord.prefix.."] ", Color(255, 255, 255), msg.author..": ", msg.content)
end)
98 changes: 98 additions & 0 deletions lua/relay/sv_msgGet.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
require("gwsockets")
util.AddNetworkString("!!discord-receive")

Discord.isSocketReloaded = false

if Discord.socket != nil then Discord.isSocketReloaded = true; Discord.socket:closeNow(); end

Discord.socket = Discord.socket or GWSockets.createWebSocket("wss://gateway.discord.gg/?encoding=json", true)
local socket = Discord.socket

local function broadcastMsg(msg)
print('[Discord] ' .. msg.author..': '.. msg.content)

net.Start("!!discord-receive")
net.WriteTable(msg)
net.Broadcast()
end

local function heartbeat()
socket:write([[
{
"op": 1,
"d": null
}
]])
end

local function createHeartbeat()
timer.Create('!!discord_hearbeat', 10, 0, function()
socket:write([[
{
"op": 1,
"d": null
}
]])
end)
end

function socket:onMessage(txt)
local resp = util.JSONToTable(txt)
if Discord.debug then
print("[Discord] Received: ")
PrintTable(resp)
end

if resp.op == 10 and resp.t == nil then createHeartbeat() end
if resp.op == 1 then heartbeat() end
if resp.d then
if resp.t == "MESSAGE_CREATE" && resp.d.channel_id == Discord.readChannelID && resp.d.content != '' then
if resp.d.author.bot == true then return end
broadcastMsg({
['author'] = resp.d.author.username,
['content'] = resp.d.content
})
end
end
end

function socket:onError(txt)
print("[Discord] Error: ", txt)
end

function socket:onConnected()
print("[Discord] connected to Discord server")
local req = [[
{
"op": 2,
"d": {
"token": "]]..Discord.botToken..[[",
"intents": 512,
"status": "dnd",
"properties": {
"os": "linux",
"browser": "disco",
"device": "disco"
}
}
}
]]

timer.Simple(2, function() socket:write(req) end)
end

function socket:onDisconnected()
print("[Discord] WebSocket disconnected")
timer.Remove('!!discord_hearbeat')

if Discord.isSocketReloaded != true then
print('[Discord] WebSocket reload in 5 sec...')
timer.Simple(5, function() socket:open() end)
end
end

print('[Discord] Socket init...')
timer.Simple(3, function()
socket:open()
Discord.isSocketReloaded = false
end)
112 changes: 112 additions & 0 deletions lua/relay/sv_msgSend.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
require("chttp")

local tmpAvatars = {}

function Discord.send(form)
if type(form) ~= "table" then Error("[Discord] invalid type!") return end

local json = util.TableToJSON(form)

CHTTP({
["failed"] = function(msg)
print("[Discord] "..msg)
end,
["method"] = "POST",
["url"] = Discord.webhook,
["body"] = json,
["type"] = "application/json"
})
end

local function getAvatar(id, co)
http.Fetch("https://steamcommunity.com/profiles/"..id.."?xml=1",
function(body)
local _, _, url = string.find(body, '<avatarFull>.*.(https://.*)]].*\n.*<vac')
tmpAvatars[id] = url

coroutine.resume(co)
end,
function (msg)
Error("[Discord] error getting avatar ("..msg..")")
end)
end

local function formMsg(ply, str)
local id = ply:SteamID64()

local co = coroutine.create(function()
local form = {
["username"] = ply:Nick(),
["content"] = str,
["avatar_url"] = tmpAvatars[id],
["allowed_mentions"] = {
["parse"] = {}
},
}

Discord.send(form)
end)

if tmpAvatars[id] == nil then
getAvatar(id, co)
return
end

coroutine.resume(co)
end

local function playerConnect(ply)
local form = {
["username"] = Discord.hookname,
["embeds"] = {{
["title"] = "Игрок "..ply.name.." ("..ply.networkid..") подключается...",
["color"] = 16763979,
}}
}

Discord.send(form)
end

local function plyFrstSpawn(ply)
local form = {
["username"] = Discord.hookname,
["embeds"] = {{
["title"] = "Игрок "..ply:GetName().." ("..ply:SteamID()..") подключился",
["color"] = 4915018,
}}
}

Discord.send(form)
end

local function plyDisconnect(ply)
local form = {
["username"] = Discord.hookname,
["embeds"] = {{
["title"] = "Игрок "..ply.name.." ("..ply.networkid..") отключился",
["color"] = 16730698,
}}
}

Discord.send(form)
end

hook.Add("PlayerSay", "!!discord_sendmsg", formMsg)
gameevent.Listen( "player_connect" )
hook.Add("player_connect", "!!discord_plyConnect", playerConnect)
hook.Add("PlayerInitialSpawn", "!!discordPlyFrstSpawn", plyFrstSpawn)
gameevent.Listen( "player_disconnect" )
hook.Add("player_disconnect", "!!discord_onDisconnect", plyDisconnect)
hook.Add("Initialize", "!!discord_srvStarted", function()
local form = {
["username"] = Discord.hookname,
["embeds"] = {{
["title"] = "Сервер запущен!",
["description"] = "Карта сейчас - " .. game.GetMap(),
["color"] = 5793266
}}
}

Discord.send(form)
hook.Remove("Initialize", "!!discord_srvStarted")
end)
12 changes: 12 additions & 0 deletions lua/sv_config.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Discord = {
['webhook'] = "paste_url",

['hookname'] = "Discord relay",

['readChannelID'] = "channel_ID_for_get_msg",

['botToken'] = 'token',

-- For developers (logs)
['debug'] = false
}

0 comments on commit 16e5e02

Please sign in to comment.