local cqueues = require 'cqueues' local websocket = require'http.websocket' local request = require'http.request' local json = require 'dkjson' local pprint = require 'pprint' local class = require 'r.class' local BasePylon = require 'pylon' local Channel = require 'channel' local consts = require 'discord.consts' local opcodes = consts.opcodes local exec_webhook = require'discord.the' local API_BASE = "https://discord.com/api/v10/" local Discord = class.extend(BasePylon) function Discord.init(self) self:_check_fields "token" end local function identify_payload(token) local I = consts.intents return json.encode{ op = opcodes.identify, d = { properties = {os="wilson",browser="wilson",device="wilson"}, intents = I.guilds + I.guild_messages + I.message_content, token = token } } end function Discord._req_get(self, url) local req = request.new_from_uri(API_BASE..url) req.headers:upsert('content-type','application/json') req.headers:upsert(':method','GET') req.headers:upsert('authorization','Bot '..self.token) req.headers:upsert('user-agent','wilson (https://g.gh0.pw/wilson/, v0.0)') local head,body = assert(req:go()) local status = head:get':status' assert(status:sub(1,1)=='2','status was '..status) return assert(json.decode(body:get_body_as_string())) end function Discord._connect(self) local uri = "wss://gateway.discord.gg/?v=10&encoding=json" self.ws = websocket.new_from_uri(uri) assert(self.ws:connect()) self.ws:send(identify_payload(self.token), 'text') local me = self:_req_get"users/@me" pprint('I AM ',me) end function Discord._heartbeating(self, interval_ms) local interval = interval_ms / 1000 cqueues.sleep(interval * math.random()) while true do self.ws:send(json.encode{ op = opcodes.heartbeat, d = self.sequence_number, }) cqueues.sleep(interval) end end function Discord.recving(self) for packet in self.ws:each() do local event = json.decode(packet) print(event.s, event.op, event.t) if event.op ~= opcodes.dispatch then pprint(event.d) end if event.s then self.sequence_number = event.s end if event.op == opcodes.hello then self.cq:wrap(self._heartbeating, self, event.d.heartbeat_interval) elseif event.op == opcodes.dispatch then self:handle_dispatch(event) end end end function Discord.handle_dispatch(self, event) local d = event.d if event.t == 'MESSAGE_CREATE' then if d.author.id == '293066066605768714' then self.wilson:deliver(Channel(self, d.channel_id), { body = d.content, sender = '[d]' .. d.author.username }) end end end function Discord.sending(self) for dest_channel, message in self.inbox:iter() do print('DDD',message.sender,message.body) exec_webhook(self.temp_wh, { username = message.sender, content = message.body, }) end end return Discord