discord.io icon indicating copy to clipboard operation
discord.io copied to clipboard

No DELETE HTTP Method

Open FluffyMittens opened this issue 6 years ago • 6 comments

I've just started working on a bot, of course it's bad timing as there was an api update to discord. I'm not completely sure if the method was there in the first place or if it was never implemented.

I am using npm install woor/discord.io#gateway_v6

npm install woor/discord.io#gateway_v6
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.

+ [email protected]
updated 1 package in 37.571s

Delete Message

DELETE/channels/{channel.id}/messages/{message.id} Delete a message. If operating on a guild channel and trying to delete a message that was not sent by the current user, this endpoint requires the 'MANAGE_MESSAGES' permission. Returns a 204 empty response on success. Fires a Message Delete Gateway event.

https://discordapp.com/developers/docs/resources/channel#delete-message

My code

note : I had to do some hacking to get to the response object correctly

fluffyBot.sendMessage({
    to          : "XXXXXX",
    message     : access.monitorBots[SID][BID].command
}, function(error, response){
    var delMessage = {};
    for(var RES in response){
        if(RES === "channel_id"){   delMessage.channelID    = response[RES] ;}
        if(RES === "id"){           delMessage.messageIDs   = response[RES] ;}
    }
    setTimeout(function(){ fluffyBot.deleteMessage(delMessage, function(error){console.log(error);}); }, 3000);
});

Returns this on deletion

{ ResponseError: Unable to delete message
    at handleResCB (C:\Program Files\iisnode\www\node_modules\discord.io\lib\index.js:1394:10)
    at C:\Program Files\iisnode\www\node_modules\discord.io\lib\index.js:313:3
    at Gunzip.cb (C:\Program Files\iisnode\www\node_modules\discord.io\lib\index.js:1480:13)
    at Gunzip.zlibBufferOnError (zlib.js:90:8)
    at Gunzip.emit (events.js:159:13)
    at Zlib.zlibOnError [as onerror] (zlib.js:136:8)
  name: 'ResponseError',
  statusCode: 405,
  statusMessage: 'METHOD NOT ALLOWED',
  response: { code: 0, message: '405: Method Not Allowed' } }

\lib\index.js

/* LINE 313 */
/**
 * Delete a posted message.
 * @arg {Object} input
 * @arg {Snowflake} input.channelID
 * @arg {Snowflake} input.messageID
 */
DCP.deleteMessage = function(input, callback) {
	this._req('delete', Endpoints.MESSAGES(input.channelID, input.messageID), function(err, res) {
		handleResCB("Unable to delete message", err, res, callback);
	});
};
/* LINE 1462 */
/* - Functions - Utils */
function APIRequest(method, url) {
        var data, callback, opts, req, headers = messageHeaders(this);
        callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

        if (isNode) {
                opts = URL.parse(url);
                opts.method = method;
                opts.headers = headers;

                req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
                        var chunks = [];
                        res.on('data', function(c) { chunks[chunks.length] = c; });
                        res.once('end', function() {
                                chunks = Buffer.concat(chunks);
                                Zlib.gunzip(chunks, function(err, uc) {
                                        if (!err) uc = uc.toString();
                                        try { res.body = JSON.parse(uc || chunks); } catch(e) {}
                                        return callback(null, res);
                                });
                        });
                });
                if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
                if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
                if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
                req.end();

                return req.once('error', function(e) { return callback(e.message); });
        }

        req = new XMLHttpRequest();
        req.open(method.toUpperCase(), url, true);
        for (var key in headers) {
                req.setRequestHeader(key, headers[key]);
        }
        req.onreadystatechange = function() {
                if (req.readyState == 4) {
                        req.statusCode = req.status;
                        req.statusMessage = req.statusText;
                        try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
                        callback(null, req);
                }
        };
        if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
        if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
        req.send(null);
}

FluffyMittens avatar Dec 09 '17 06:12 FluffyMittens

You can do this with the standard code. No library modifications necessary.

bot.sendMessage({to: channelID, message: "something to delete"}, function(err, res) {
    bot.deleteMessage({channelID: channelID, messageID: res.id});
});

Is your developer application a bot user?

cloudrac3r avatar Dec 09 '17 07:12 cloudrac3r

As far as the code, I did initially do something similar. Interesting thing though, when I'd do a console.log on res.id it would give an error as if it wasn't part of the object. I believe I did rename the variable and it did not change the error. Not an undefined message.

Yes, the app is a bot user and has the permissions on the channel. I would assume i'd get a 403 (unauthorized) message if that were the case.

FluffyMittens avatar Dec 09 '17 07:12 FluffyMittens

The reason it's giving you 405 METHOD NOT ALLOWED is because you've got a typo/incorrect key for the input object for bot.deleteMessage(). You assign the keys channelID and messageIDs but deleteMessage expects channelID and messageID (no 's'). As a result when it builds the endpoint URL messageID is null, and the resulting endpoint is https://discordapp.com/api/channels/{channel.id}/messages which indeed does not accept the delete method.

Runi-c avatar Dec 09 '17 10:12 Runi-c

I will check it out when I work on it again. I think that may be something I forgot to change back from trying to do deleteMessages().

FluffyMittens avatar Dec 09 '17 18:12 FluffyMittens

Thanks. I must have been spending too much time working yesterday. Strangely I swear this exact thing that wasn't working last night.

fluffyBot.sendMessage({
    to          : "xxxx",
    message     : access.monitorBots[SID][BID].command
}, function(error, response){
    var delMessage = {};
    for(var RES in response){
        if(RES === "channel_id"){   delMessage.channelID    = response.channel_id ;}
        if(RES === "id"){           delMessage.messageID    = response.id ;}
    }
    setTimeout(function(){ fluffyBot.deleteMessage(delMessage); }, 3000);
});

This issue still exists though.

C:\Program Files\iisnode\www\bot.js:56
                    setTimeout(function(){ fluffyBot.deleteMessage( { channelID : res.channel_id, messageID : res.id} ); }, 3000);
                                                                                      ^

TypeError: Cannot read property 'channel_id' of undefined
    at Timeout._onTimeout (C:\Program Files\iisnode\www\bot.js:56:87)
    at ontimeout (timers.js:478:11)
    at tryOnTimeout (timers.js:302:5)
    at Timer.listOnTimeout (timers.js:262:5)

Code

fluffyBot.sendMessage( {to : "X", message : access.monitorBots[SID][BID].command}, function(error, res){
    setTimeout(function(){ fluffyBot.deleteMessage( { channelID : res.channel_id, messageID : res.id} ); }, 3000);
});

FluffyMittens avatar Dec 09 '17 21:12 FluffyMittens

Check for errors before attempting to delete the message. The response object being null probably means Discord rejected the sendMessage request.

Runi-c avatar Dec 09 '17 23:12 Runi-c