Как я могу получить доступ к действиям канала гильдии Discord API? - PullRequest
0 голосов
/ 30 июня 2019

Я новичок в Javascript.Сейчас я работаю над расширением Chrome.Мне нужно реализовать возможность создания канала гильдии Discord, нажав ссылку в расширении Chrome.

Я успешно выполняю вход через Discord в расширение Chrome и получаю токен доступа.После этого я пытаюсь создать канал, но всегда получаю 401 Unauthorized.

Но когда я делаю запрос GET, чтобы показать пользовательские гильдии (/ users / @ me / guilds), это работает, но при попытке получить каналы (/ users / @ me / channel) я получил только 401 несанкционированный ..

Может кто-нибудь объяснить, что я делаю не так?Заранее спасибо)

Вот мой код: (область действия первого запроса: guilds.join, идентификация, гильдии, электронная почта, соединения, messages.read, bot, rpc, rpc.api)

$("#discord_sign_in").click(function () {
    chrome.identity.launchWebAuthFlow(
        {'url': 'https://discordapp.com/api/oauth2/authorize?client_id=*hidden*&redirect_uri=https%3A%2F%2Fgnbkehnofikpgioaajgmejnkihdkpiap.chromiumapp.org%2Fsettings%2Findex.html&response_type=code&scope=guilds.join%20identify%20guilds%20email%20connections%20messages.read%20bot%20rpc%20rpc.api',
        'interactive': true},
        function(redirect_url) { 
            console.log('Authorization success'); 
            console.log(redirect_url);
            // var redirect_url = redirect.replace("#", "?");
            var url = new URL(redirect_url);
            var code = url.searchParams.get("code");
            console.log(code);

            localStorage.setItem('discord_code', code);

            console.log('get new code: ' + localStorage.getItem('discord_code'));

        });
    });


$("#discord_sign_in_bot").click(function() {
    $.ajax( {
        url: 'https://discordapp.com/api/v6/oauth2/token',
        type: 'POST',
        data: { grant_type: 'authorization_code',
                scope: 'bot',
                client_id: 'localStorage.getItem('client_id')',
                client_secret: 'localStorage.getItem('client_secret')',
                code: localStorage.getItem('discord_code'),
                permissions: 8,
                redirect_uri: 'https://gnbkehnofikpgioaajgmejnkihdkpiap.chromiumapp.org/settings/index.html' },
        success: function( response ) {
            console.log("Successfully authorized bot (Discord).")
            console.log(response);
            console.log("access_token: " + response['access_token']);
            localStorage.setItem('discord_token', response['access_token']);
        },
        error: function () {
            console.log("Failed to bot authorization (Discord).")
        }
    } );
});

$("#discord_create_channel").click(function() {
    $.ajax( {
        url: 'https://discordapp.com/api/v6/guilds/594100687508340776/channels/',
        type: 'POST',
        data: { name: 'Test-channel-5' },
        beforeSend : function( xhr ) {
            xhr.setRequestHeader( "Authorization", "Bot " + localStorage.getItem('discord_token'));
        },
        success: function( response ) {
            console.log("Successfully created guild channel (Discord).")
        },
        error: function (response) {
            console.log(response);
            console.log("Failed to create guild channel (Discord).")
        }
    } );
});
...