DIscord API -使用node js express添加公会成员



我已经创建了一个有几个命令的Discord bot,直到这里都很好。

现在的想法是手动询问用户的ID,一旦这个信息,我想通过API "/guilds/{guilds . ID}/members/{user.id}"中描述的端点将他们添加为我的公会成员。

因此我将重述:

  1. 要求用户提供ID,
  2. 输入以下URL http://localhost:3000/add-member/:userID
  3. 添加成员到公会。

如果我自动添加自己,一切都很好。当我使用外部用户的ID时出现错误。

错误是:

出现错误DiscordAPIError[50025]: Invalid OAuth2 access token.

应用程序具有guilds.join,application.commandsbot所需的所有权限。并且bot具有Admin权限。

这是我在github中的repo:https://github.com/Srizza93/harry-botter

在过去的2天里,我很挣扎,网上没有太多的细节。

提前感谢您的回复。

到目前为止,这是我在server .js中的代码:
// Adding Members
app.get(`/add-member/:userId`, async (req, res) => {
try {
await rest.put(Routes.guildMember(guildId, req.params.userId), {
headers: {
["Content-Type"]: "application/json",
Authorization: `${token}`,
},
body: {
access_token: accessToken,
nick: "New",
},
});
console.log("Successfully added memeber id " + req.params.userId);
} catch (error) {
console.log("There was an error " + error);
}
});

这是我的第一个点index。js:

const server = require("./server");
const fs = require("node:fs");
const path = require("node:path"); // Require the necessary discord.js classes
const { Client, Collection, Events, GatewayIntentBits } = require("discord.js");
const { token } = require("./config.json");
// Create a new client instance
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
server(client);
client.commands = new Collection();
const commandsPath = path.join(__dirname, "commands");
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, (c) => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Once ready, listen for events
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({
content: "There was an error while executing this command!",
});
}
});
// Add a Default role to each new member
client.on(Events.GuildMemberAdd, (member) => {
try {
const role = member.guild.roles.cache.find(
(role) => role.name === "discorder"
);
if (role) {
member.roles.add(role);
console.log(member.user.id + " is in da house");
} else {
console.log(
`The role discorder was not assigned to '${member}' as it wasn't created`
);
}
} catch (error) {
console.error(error);
}
});
// Log in to Discord with your client's token
client.login(token);

编辑我设法交换了OAuth2,并使用以下代码发送了我的请求:

app.get("/login", (req, res) => {
// Redirect the client to the authorization URL
res.redirect(
`https://discord.com/api/oauth2/authorize?client_id=1055994237243637812&permissions=8&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&response_type=code&scope=bot%20guilds.join%20applications.commands`
);
});
app.get("/callback", async (req, res) => {
// Get the OAuth2 token from the query parameters
const code = req.query.code;
// Exchange the code for an OAuth2 token
if (code) {
try {
const tokenResponseData = await request(
"https://discord.com/api/oauth2/token",
{
method: "POST",
body: new URLSearchParams({
client_id: clientId,
client_secret: clientSecret,
code,
grant_type: "authorization_code",
redirect_uri: redirectUri,
scope: "guilds.join",
}).toString(),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
const oauthData = await tokenResponseData.body.json();
await rest.put(Routes.guildMember(guildId, oauthData.owner_id), {
headers: {
["Content-Type"]: "application/json",
Authorization: `${token}`,
},
body: {
access_token: oauthData.access_token,
nick: "New",
},
});
console.log(`Successfully added user ${oauthData.owner_id}`);
} catch (error) {
// NOTE: An unauthorized token will not throw an error
// tokenResponseData.statusCode will be 401
console.error(error);
}
}
});

但是,错误现在是:

DiscordAPIError[20001]: Bots cannot use this endpoint

但我实际上使用的是服务器而不是bot。在这一点上,我的问题是,是否有可能通过服务器添加成员?

最后我用下面的代码解决了这个问题:

// Add member
await rest
.put(Routes.guildMember(guildId, user.id), {
body: {
access_token: oauthData.access_token,
nick: "New",
roles: [role.id, channelRole.id],
},
headers: {
Authorization: `Bot ${botToken}`,
["Content-Type"]: "application/json",
},
})
.catch(console.error);

这个错误是指向机器人的权限,但是,语法是错误的。

相关内容

  • 没有找到相关文章

最新更新