discord.js でメンバーのロールを反復処理するときにエラーが発生する

okwaves2024-01-25  12

そこで、Discord ボット用のブラックリスト機能を作成しています。基本的には単語と役割を入力するだけで、誰かがその役割を持っていれば...何かが起こるでしょうか?まだよくわかりません。しかし、メンバーのロールを反復処理しようとすると、次のエラーが発生します。

(node:21803) UnhandledPromiseRejectionWarning: TypeError: message.member.roles is not iterable

これが私のコードです:

for (const word of message.content.split(" ")) {
        for (const role of message.member.roles) {
            console.log(role.name);
        }
    }

これを修正する方法について何かアイデアはありますか?



------------------------

役割とは何のことを言っているのか正確にはわかりませんが、ギルドの役割のことを言っているのだと思います。メッセージからギルドを取得すると、それがRoleManagerになるため、そのキャッシュをマップしてその中のすべてのロールを取得できます。その方法は次のとおりです。

const roles = message.guild.roles.cache.map(role => role);

JavaScript の他の配列と同様に、forEach ループを使用して配列を反復処理できます。

// This log every role in the Guild the message was sent
roles.forEach(role => {
  console.log(role);
});

言及されたユーザーについては、MessageMentions オブジェクトを通じて取得できます。そのように:

// In case you want the User Object
const user = message.mentions.users.first();
// In case you want the GuildMember object (most likely)
const member = message.mentions.members.first();

これで、自分が達成しようとしていることに取り組むことができると思います。いずれにしても、メッセージ内で言及されたロールについて話している場合は、ユーザーと同じように (MessageMentions オブジェクトから) ロールを取得できます。

const role = message.mentions.roles.first();

あなたが言ったように、何をしようとしているのかはわかりませんが、「ユーザーにロールを割り当てる」コマンドのようなものであれば、次のように実行できます。

const member = message.mentions.members.first();
const role = message.mentions.roles.first();

member.roles.add(role);

// !command @user @role - adds the user to the role

あるいは、ずっとメンバーの役割を反復しようとしていただけだった場合は、これは多かれ少なかれ最初の例と同じように機能します。さあ、どうぞ:

// In case you want the mentioned user
const member = message.mentions.members.first();
// In case you want the message author user
const member = message.member;

// Map the User Roles
const roles = member.roles.cache.map(role => role);

// Iterate though it =)
roles.forEach(role => {
  console.log(role);
});

役立つリンク: メッセージ#ギルド | discord.js ギルド#役割 |discord.js ロールマネージャー#キャッシュ | discord.js

1

message.member は message.author と同等ですが、GuildMember オブジェクトを返します。

– ライオネス100

2020 年 9 月 4 日 23:07



------------------------

次の場合は、キャッシュ プロパティを通じて GuildMemberRoleManager を渡す必要があります。v12 以降を使用しています

for (const role of message.member.roles.cache) {
   // ...

1

私はこれを試しました: for (const role of message.member.roles.cache) { console.log(role.name);しかし、console.log() を実行すると、単に未定義が返されるだけですか?

– 

user13923447

2020 年 9 月 4 日 22:12

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。