Skip to content

Instantly share code, notes, and snippets.

@tignear
Created July 11, 2021 16:01
Show Gist options
  • Save tignear/7769daf3d5c2fb2ebc216f4d111eaf5d to your computer and use it in GitHub Desktop.
Save tignear/7769daf3d5c2fb2ebc216f4d111eaf5d to your computer and use it in GitHub Desktop.

Gateway Intents と Discord.js の内部実装

Gateway Intents と Discord.js の内部実装

for (const id of ids) {
 //client.options.partials に Message がない場合は、 api から 関連する完全な情報が提供されず、かつMessageManagerに存在しない message も無視される
  const message = this.getMessage(
    {
      id,
      guild_id: data.guild_id,
    },
    channel,
    false
  );
  if (message) {
    message.deleted = true;
    messages.set(message.id, message);
    channel.messages.cache.delete(id);
  }
}
if (messages.size > 0) client.emit(Events.MESSAGE_BULK_DELETE, messages);
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var client: import("discord.js").Client;
for (const id of ids) {
    //client.options.partials に Message がない場合は、 api から 関連する完全な情報が提供されず、かつMessageManagerに存在しない message も無視される
    const message = this.getMessage({
        id,
        guild_id: data.guild_id,
    }, channel, false);
    if (message) {
        message.deleted = true;
        messages.set(message.id, message);
        channel.messages.cache.delete(id);
    }
}
if (messages.size > 0)
    client.emit(Events.MESSAGE_BULK_DELETE, messages);
  • test.ts (4,18): Cannot find name 'ids'.
  • test.ts (6,26): Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
  • test.ts (8,19): Cannot find name 'data'.
  • test.ts (12,9): Cannot find name 'messages'. Did you mean 'message'?
  • test.ts (16,5): Cannot find name 'messages'. Did you mean 'onmessage'?
  • test.ts (17,17): Cannot find name 'Events'. Did you mean 'Event'?
  • test.ts (17,45): Cannot find name 'messages'. Did you mean 'onmessage'?

guildCreate
guildCreate;
  • test.ts (2,1): Cannot find name 'guildCreate'.

guildUpdate
guildUpdate;
  • test.ts (2,1): Cannot find name 'guildUpdate'.

guildDelete
guildDelete;
  • test.ts (2,1): Cannot find name 'guildDelete'.

guild.deleted = true
declare var guild: import("discord.js").Guild;
guild.deleted = true;

guildUnavailable
guildUnavailable;
  • test.ts (2,1): Cannot find name 'guildUnavailable'.

guild.available = false
declare var guild: import("discord.js").Guild;
guild.available = false;

roleCreate
roleCreate;
  • test.ts (2,1): Cannot find name 'roleCreate'.

roleUpdate
roleUpdate;
  • test.ts (2,1): Cannot find name 'roleUpdate'.

roleDelete
roleDelete;
  • test.ts (2,1): Cannot find name 'roleDelete'.

channelCreate
channelCreate;
  • test.ts (2,1): Cannot find name 'channelCreate'.

channelUpdate
channelUpdate;
  • test.ts (2,1): Cannot find name 'channelUpdate'.

ChannelManager.remove()
ChannelManager.remove();
  • test.ts (2,1): Cannot find name 'ChannelManager'.

channelManager.cache
channelManager.cache;
  • test.ts (2,1): Cannot find name 'channelManager'.

guildChannelManger.cache
guildChannelManger.cache;
  • test.ts (2,1): Cannot find name 'guildChannelManger'.

channelDelete
channelDelete;
  • test.ts (2,1): Cannot find name 'channelDelete'.

channel.lastPinTimestamp = time.getTime() || null
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.lastPinTimestamp = time.getTime() || null;
  • test.ts (3,28): Cannot find name 'time'.

channelPinsUpdate
channelPinsUpdate;
  • test.ts (2,1): Cannot find name 'channelPinsUpdate'.

guild.memberCount++
declare var guild: import("discord.js").Guild;
guild.memberCount++;

guildMemberAdd
guildMemberAdd;
  • test.ts (2,1): Cannot find name 'guildMemberAdd'.

guildMemberUpdate
guildMemberUpdate;
  • test.ts (2,1): Cannot find name 'guildMemberUpdate'.

guild.memberCount--
declare var guild: import("discord.js").Guild;
guild.memberCount--;

member.deleted = true;
declare var member: import("discord.js").GuildMember;
member.deleted = true;

guildMemberRemove
guildMemberRemove;
  • test.ts (2,1): Cannot find name 'guildMemberRemove'.

guildBanAdd
guildBanAdd;
  • test.ts (2,1): Cannot find name 'guildBanAdd'.

guildBanRemove
guildBanRemove;
  • test.ts (2,1): Cannot find name 'guildBanRemove'.

guildIntegrationsUpdate
guildIntegrationsUpdate;
  • test.ts (2,1): Cannot find name 'guildIntegrationsUpdate'.

webhookUpdate
webhookUpdate;
  • test.ts (2,1): Cannot find name 'webhookUpdate'.

inviteCreate
inviteCreate;
  • test.ts (2,1): Cannot find name 'inviteCreate'.

inviteDelete
inviteDelete;
  • test.ts (2,1): Cannot find name 'inviteDelete'.

voiceStateUpdate
voiceStateUpdate;
  • test.ts (2,1): Cannot find name 'voiceStateUpdate'.

userUpdate
userUpdate;
  • test.ts (2,1): Cannot find name 'userUpdate'.

guildMemberAvailable
guildMemberAvailable;
  • test.ts (2,1): Cannot find name 'guildMemberAvailable'.

presenceUpdate
presenceUpdate;
  • test.ts (2,1): Cannot find name 'presenceUpdate'.

message
declare var message: import("discord.js").Message;
message;

messageUpdate
messageUpdate;
  • test.ts (2,1): Cannot find name 'messageUpdate'.

message.deleted = true
declare var message: import("discord.js").Message;
message.deleted = true;

messageDelete
messageDelete;
  • test.ts (2,1): Cannot find name 'messageDelete'. Did you mean 'MessageEvent'?

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

messageReactionRemove
messageReactionRemove;
  • test.ts (2,1): Cannot find name 'messageReactionRemove'.

messageReactionRemoveAll
messageReactionRemoveAll;
  • test.ts (2,1): Cannot find name 'messageReactionRemoveAll'.

messageReactionRemoveEmoji
messageReactionRemoveEmoji;
  • test.ts (2,1): Cannot find name 'messageReactionRemoveEmoji'.

音声を再生する

音声を再生する

const { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioResource, StreamType, createAudioPlayer, AudioPlayerStatus, NoSubscriberBehavior, generateDependencyReport } = require("@discordjs/voice");
console.log(generateDependencyReport());
const Discord = require("discord.js");
const client = new Discord.Client({
  intents: Discord.Intents.FLAGS.GUILDS | Discord.Intents.FLAGS.GUILD_VOICE_STATES //多分これでいい
});
async function play(interaction) {
  const guild = interaction.guild;
  const member = await guild.members.fetch(interaction.member.id);
  const memberVC = member.voice.channel;
  if (!memberVC) {
    return interaction.reply({
      content: "接続先のVCが見つかりません。",
      ephemeral: true,
    });
  }
  if (!memberVC.joinable) {
    return interaction.reply({
      content: "VCに接続できません。",
      ephemeral: true,
    });
  }
  if (!memberVC.speakable) {
    return interaction.reply({
      content: "VCで音声を再生する権限がありません。",
      ephemeral: true,
    });
  }
  const status = ["●Loading Sounds...", `●Connecting to ${memberVC}...`];
  const p = interaction.reply(status.join("\n"));
  const connection = joinVoiceChannel({
    guildId: guild.id,
    channelId: memberVC.id,
    adapterCreator: guild.voiceAdapterCreator,
    selfMute: false,
  });
  const resource = createAudioResource("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", {
    inputType: StreamType.Arbitrary,
  });
  const player = createAudioPlayer({
    behaviors: {
      noSubscriber: NoSubscriberBehavior.Pause,
    },
  });
  player.play(resource);
  const promises = [];

  promises.push(entersState(connection, VoiceConnectionStatus.Ready, 1000 * 10).then(() => status[0] += "Done!"));
  promises.push(entersState(player, AudioPlayerStatus.AutoPaused, 1000 * 10).then(() => status[1] += "Done!"));
  await Promise.race(promises);
  await p;
  await Promise.all([...promises, interaction.editReply(status.join("\n"))]);
  connection.subscribe(player);
  await entersState(player, AudioPlayerStatus.Playing, 100);

  await interaction.editReply("Playing");
  await entersState(player, AudioPlayerStatus.Idle, 2 ** 31 - 1);
  await interaction.editReply("End");
  connection.destroy();
}
/**
 * 
 * @param {Discord.CommandInteraction} interaction 
 */
async function onPlay(interaction) {
  try {
    await play(interaction);
  } catch (err) {
    if (interaction.replied) {
      interaction.editReply("エラーが発生しました。").catch(() => { });
    } else {
      interaction.reply("エラーが発生しました。").catch(() => { });
    }
    throw err;
  }
}
/**
 * 
 * @param {Discord.CommandInteraction} interaction 
 */
async function onCommandInteraction(interaction) {
  if (interaction.commandName === "play") {
    return onPlay(interaction);
  }
}
/**
 * 
 * @param {Discord.Interaction} interaction 
 */
async function onInteraction(interaction) {
  if (interaction.isCommand()) {
    return onCommandInteraction(interaction);
  }
}
client.on("interactionCreate", interaction => onInteraction(interaction).catch(err => console.error(err)));
client.login(process.env.DISCORD_TOKEN)
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { joinVoiceChannel, entersState, VoiceConnectionStatus, createAudioResource, StreamType, createAudioPlayer, AudioPlayerStatus, NoSubscriberBehavior, generateDependencyReport } from "@discordjs/voice";
console.log(generateDependencyReport());
import * as Discord from "discord.js";
const client = new Discord.Client({
    intents: Discord.Intents.FLAGS.GUILDS | Discord.Intents.FLAGS.GUILD_VOICE_STATES //多分これでいい
});
async function play(interaction) {
    const guild = interaction.guild;
    const member = await guild.members.fetch(interaction.member.id);
    const memberVC = member.voice.channel;
    if (!memberVC) {
        return interaction.reply({
            content: "\u63A5\u7D9A\u5148\u306EVC\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002",
            ephemeral: true,
        });
    }
    if (!memberVC.joinable) {
        return interaction.reply({
            content: "VC\u306B\u63A5\u7D9A\u3067\u304D\u307E\u305B\u3093\u3002",
            ephemeral: true,
        });
    }
    if (!memberVC.speakable) {
        return interaction.reply({
            content: "VC\u3067\u97F3\u58F0\u3092\u518D\u751F\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093\u3002",
            ephemeral: true,
        });
    }
    const status = ["\u25CFLoading Sounds...", `●Connecting to ${memberVC}...`];
    const p = interaction.reply(status.join("\n"));
    const connection = joinVoiceChannel({
        guildId: guild.id,
        channelId: memberVC.id,
        adapterCreator: guild.voiceAdapterCreator,
        selfMute: false,
    });
    const resource = createAudioResource("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", {
        inputType: StreamType.Arbitrary,
    });
    const player = createAudioPlayer({
        behaviors: {
            noSubscriber: NoSubscriberBehavior.Pause,
        },
    });
    player.play(resource);
    const promises = [];
    promises.push(entersState(connection, VoiceConnectionStatus.Ready, 1000 * 10).then(() => status[0] += "Done!"));
    promises.push(entersState(player, AudioPlayerStatus.AutoPaused, 1000 * 10).then(() => status[1] += "Done!"));
    await Promise.race(promises);
    await p;
    await Promise.all([...promises, interaction.editReply(status.join("\n"))]);
    connection.subscribe(player);
    await entersState(player, AudioPlayerStatus.Playing, 100);
    await interaction.editReply("Playing");
    await entersState(player, AudioPlayerStatus.Idle, 2 ** 31 - 1);
    await interaction.editReply("End");
    connection.destroy();
}
/**
 *
 * @param {Discord.CommandInteraction} interaction
 */
async function onPlay(interaction) {
    try {
        await play(interaction);
    }
    catch (err) {
        if (interaction.replied) {
            interaction.editReply("\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002").catch(() => { });
        }
        else {
            interaction.reply("\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002").catch(() => { });
        }
        throw err;
    }
}
/**
 *
 * @param {Discord.CommandInteraction} interaction
 */
async function onCommandInteraction(interaction) {
    if (interaction.commandName === "play") {
        return onPlay(interaction);
    }
}
/**
 *
 * @param {Discord.Interaction} interaction
 */
async function onInteraction(interaction) {
    if (interaction.isCommand()) {
        return onCommandInteraction(interaction);
    }
}
client.on("interactionCreate", interaction => onInteraction(interaction).catch(err => console.error(err)));
client.login(process.env.DISCORD_TOKEN);
  • index.ts (11,21): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (67,23): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (85,37): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (94,30): Parameter 'interaction' implicitly has an 'any' type.
  • D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/@discordjs/voice/dist/index.d.ts (6,8): Module '"D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/@types/ws/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flag

const { Client, ClientApplication } = require("discord.js");
/**
 * 
 * @param {Client} client 
 * @param {import("discord.js").ApplicationCommandData[]} commands 
 * @param {import("discord.js").Snowflake} guildID 
 * @returns {Promise<import("@discordjs/collection").Collection<string,import("discord.js").ApplicationCommand>>}
 */
async function register(client, commands, guildID) {
  if (guildID == null) {
    return client.application.commands.set(commands);
  }
  const guild = await client.guilds.fetch(guildID);
  return guild.commands.set(commands);
}
const ping = {
  name: "play",
  description: "play music!",
};
const commands = [ping];
const client = new Client({
  intents: 0,
});
client.token = process.env.DISCORD_TOKEN;
async function main() {
  client.application = new ClientApplication(client, {});
  await client.application.fetch();
  await register(client, commands, process.argv[2]);
  console.log("registration succeed!");
}
main().catch(err => console.error(err));
import { Client, ClientApplication } from "discord.js";
/**
 *
 * @param {Client} client
 * @param {import("discord.js").ApplicationCommandData[]} commands
 * @param {import("discord.js").Snowflake} guildID
 * @returns {Promise<import("@discordjs/collection").Collection<string,import("discord.js").ApplicationCommand>>}
 */
async function register(client, commands, guildID) {
    if (guildID == null) {
        return client.application.commands.set(commands);
    }
    const guild = await client.guilds.fetch(guildID);
    return guild.commands.set(commands);
}
const ping = {
    name: "play",
    description: "play music!",
};
const commands = [ping];
const client = new Client({
    intents: 0,
});
client.token = process.env.DISCORD_TOKEN;
async function main() {
    client.application = new ClientApplication(client, {});
    await client.application.fetch();
    await register(client, commands, process.argv[2]);
    console.log("registration succeed!");
}
main().catch(err => console.error(err));
  • register.ts (10,25): Parameter 'client' implicitly has an 'any' type.
  • register.ts (10,33): Parameter 'commands' implicitly has an 'any' type.
  • register.ts (10,43): Parameter 'guildID' implicitly has an 'any' type.
  • register.ts (25,1): Type 'string | undefined' is not assignable to type 'string | null'. Type 'undefined' is not assignable to type 'string | null'.

@discordjs/voice
/voice;;
  • test.ts (2,2): Unterminated regular expression literal.

ffmpeg
ffmpeg;
  • test.ts (2,1): Cannot find name 'ffmpeg'.

generateDependencyReport
generateDependencyReport;
  • test.ts (2,1): Cannot find name 'generateDependencyReport'.

@discordjs/voice
/voice;;
  • test.ts (2,2): Unterminated regular expression literal.

joinVoiceChannel
joinVoiceChannel;
  • test.ts (2,1): Cannot find name 'joinVoiceChannel'.

guildId
guildId;
  • test.ts (2,1): Cannot find name 'guildId'.

channelId
channelId;
  • test.ts (2,1): Cannot find name 'channelId'.

adapterCreator
adapterCreator;
  • test.ts (2,1): Cannot find name 'adapterCreator'.

VoiceConnection
VoiceConnection;
  • test.ts (2,1): Cannot find name 'VoiceConnection'.

createAudioResource
createAudioResource;
  • test.ts (2,1): Cannot find name 'createAudioResource'.

Arbitrary
Arbitrary;
  • test.ts (2,1): Cannot find name 'Arbitrary'.

AudioResource
AudioResource;
  • test.ts (2,1): Cannot find name 'AudioResource'.

createAudioPlayer
createAudioPlayer;
  • test.ts (2,1): Cannot find name 'createAudioPlayer'.

subscriber
subscriber;
  • test.ts (2,1): Cannot find name 'subscriber'.

pause
pause;
  • test.ts (2,1): Cannot find name 'pause'.

AudioPlayer
AudioPlayer;
  • test.ts (2,1): Cannot find name 'AudioPlayer'.

entersState
entersState;
  • test.ts (2,1): Cannot find name 'entersState'.

VoiceConnection
VoiceConnection;
  • test.ts (2,1): Cannot find name 'VoiceConnection'.

AudioPlayer
AudioPlayer;
  • test.ts (2,1): Cannot find name 'AudioPlayer'.

Promise
Promise;

v13の主な変更箇所

v13の主な変更箇所

channel.send('hello!');
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("hello!");

Client
import { Client } from "discord.js";
Client;

new Client(options)
import { Client } from "discord.js";
new Client(options);
  • test.ts (3,12): Cannot find name 'options'. Did you mean 'Option'?

options
options;
  • test.ts (2,1): Cannot find name 'options'. Did you mean 'Option'?

message
declare var message: import("discord.js").Message;
message;

messageCreate
messageCreate;
  • test.ts (2,1): Cannot find name 'messageCreate'.

ClientOptions
ClientOptions;
  • test.ts (2,1): Cannot find name 'ClientOptions'.

ClientOptions#disableMentions
ClientOptions;
#disableMentions;
  • test.ts (2,1): Cannot find name 'ClientOptions'.
  • test.ts (3,1): Cannot find name '#disableMentions'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

ClientOptions#allowedMentions
ClientOptions;
#allowedMentions;
  • test.ts (2,1): Cannot find name 'ClientOptions'.
  • test.ts (3,1): Cannot find name '#allowedMentions'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

ClientOptions#fetchAllMembers
ClientOptions;
#fetchAllMembers;
  • test.ts (2,1): Cannot find name 'ClientOptions'.
  • test.ts (3,1): Cannot find name '#fetchAllMembers'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

ClientOptions#messageEditHistoryMaxSize
ClientOptions;
#messageEditHistoryMaxSize;
  • test.ts (2,1): Cannot find name 'ClientOptions'.
  • test.ts (3,1): Cannot find name '#messageEditHistoryMaxSize'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Intents
import { Intents } from "discord.js";
Intents;

ALL
ALL;
  • test.ts (2,1): Cannot find name 'ALL'.

PRIVILEGED
PRIVILEGED;
  • test.ts (2,1): Cannot find name 'PRIVILEGED'.

NON_PRIVILEGED
NON_PRIVILEGED;
  • test.ts (2,1): Cannot find name 'NON_PRIVILEGED'.

Intents
import { Intents } from "discord.js";
Intents;

send
send;
  • test.ts (2,1): Cannot find name 'send'.

edit
edit;
  • test.ts (2,1): Cannot find name 'edit'.

MessageEmbed
MessageEmbed;
  • test.ts (2,1): Cannot find name 'MessageEmbed'.

MessageAttachment
MessageAttachment;
  • test.ts (2,1): Cannot find name 'MessageAttachment'.

MessageOptions#embed
MessageOptions;
#embed;
  • test.ts (2,1): Cannot find name 'MessageOptions'.
  • test.ts (3,1): Cannot find name '#embed'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

MessageOptions#embeds
MessageOptions;
#embeds;
  • test.ts (2,1): Cannot find name 'MessageOptions'.
  • test.ts (3,1): Cannot find name '#embeds'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

string
string;
  • test.ts (2,1): 'string' only refers to a type, but is being used as a value here.

StringResolvable
StringResolvable;
  • test.ts (2,1): Cannot find name 'StringResolvable'.

StringResolvable
StringResolvable;
  • test.ts (2,1): Cannot find name 'StringResolvable'.

StringResolvable
StringResolvable;
  • test.ts (2,1): Cannot find name 'StringResolvable'.

string
string;
  • test.ts (2,1): 'string' only refers to a type, but is being used as a value here.

Message#reply
Message;
#reply;
  • test.ts (2,1): Cannot find name 'Message'. Did you mean 'onmessage'?
  • test.ts (3,1): Cannot find name '#reply'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

MessageOptions#reply
MessageOptions;
#reply;
  • test.ts (2,1): Cannot find name 'MessageOptions'.
  • test.ts (3,1): Cannot find name '#reply'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

MessageOptions#allowedMentions.repliedUser
MessageOptions;
#allowedMentions.repliedUser;
  • test.ts (2,1): Cannot find name 'MessageOptions'.
  • test.ts (3,1): Cannot find name '#allowedMentions'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

MessageOptions#allowedMentions.repliedUser
MessageOptions;
#allowedMentions.repliedUser;
  • test.ts (2,1): Cannot find name 'MessageOptions'.
  • test.ts (3,1): Cannot find name '#allowedMentions'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Guild
Guild;
  • test.ts (2,1): Cannot find name 'Guild'.

Guild#member()
Guild;
#member();
  • test.ts (2,1): Cannot find name 'Guild'.
  • test.ts (3,1): Cannot find name '#member'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Guild#voice
Guild;
#voice;
  • test.ts (2,1): Cannot find name 'Guild'.
  • test.ts (3,1): Cannot find name '#voice'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Guild#owner
Guild;
#owner;
  • test.ts (2,1): Cannot find name 'Guild'.
  • test.ts (3,1): Cannot find name '#owner'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Guild#fetchOwner()
Guild;
#fetchOwner();
  • test.ts (2,1): Cannot find name 'Guild'.
  • test.ts (3,1): Cannot find name '#fetchOwner'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GuildMember
GuildMember;
  • test.ts (2,1): Cannot find name 'GuildMember'.

GuildMember#hasPermission
GuildMember;
#hasPermission;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#hasPermission'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Message
Message;
  • test.ts (2,1): Cannot find name 'Message'. Did you mean 'onmessage'?

MessageManager
MessageManager;
  • test.ts (2,1): Cannot find name 'MessageManager'.

Message#delete
Message;
#delete;
  • test.ts (2,1): Cannot find name 'Message'. Did you mean 'onmessage'?
  • test.ts (3,1): Cannot find name '#delete'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

setTimeout
setTimeout;

Client#setTimeout()
import { Client } from "discord.js";
Client;
#setTimeout();
  • test.ts (4,1): Cannot find name '#setTimeout'. Did you mean 'setTimeout'?
  • test.ts (4,1): Private identifiers are not allowed outside class bodies.

User
User;
  • test.ts (2,1): Cannot find name 'User'.

User#locale
User;
#locale;
  • test.ts (2,1): Cannot find name 'User'.
  • test.ts (3,1): Cannot find name '#locale'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

locale
locale;
  • test.ts (2,1): Cannot find name 'locale'.

Snowflake
Snowflake;
  • test.ts (2,1): Cannot find name 'Snowflake'.

SnowflakeUtil
SnowflakeUtil;
  • test.ts (2,1): Cannot find name 'SnowflakeUtil'.

Snowflake
Snowflake;
  • test.ts (2,1): Cannot find name 'Snowflake'.

string
string;
  • test.ts (2,1): 'string' only refers to a type, but is being used as a value here.

Snowflake
Snowflake;
  • test.ts (2,1): Cannot find name 'Snowflake'.

string
string;
  • test.ts (2,1): 'string' only refers to a type, but is being used as a value here.

Snowflake
Snowflake;
  • test.ts (2,1): Cannot find name 'Snowflake'.

Channel#isText

Channel#isText

    public isText(): this is TextChannel | DMChannel | NewsChannel;
import { TextChannel } from "discord.js";
import { DMChannel } from "discord.js";
import { NewsChannel } from "discord.js";
isText();
this;
is;
TextChannel | DMChannel | NewsChannel;
  • test.ts (5,1): Cannot find name 'isText'. Did you mean 'Text'?
  • test.ts (7,1): Cannot find name 'is'.
  • test.ts (8,1): The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (8,15): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (8,27): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

Channel#isText()
Channel;
#isText();
  • test.ts (2,1): Cannot find name 'Channel'.
  • test.ts (3,1): Cannot find name '#isText'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

SelectOptionsを使ってみよう

SelectOptionsを使ってみよう

const Discord = require("discord.js");
const client = new Discord.Client({
  intents: Discord.Intents.FLAGS.GUILD_MEMBERS | Discord.Intents.FLAGS.GUILDS
});
/**
 * 
 * @param {Array<Discord.Role>} roles
 * @param {Array<Discord.GuildMember>} members
 */
function buildEmbeds(roles, members) {
  return [
    new Discord.MessageEmbed().setTitle("検索対象のロール").setDescription(roles.map(e => `${e}`).join("\n")),
    new Discord.MessageEmbed().setTitle("検索結果").setDescription(members.map(e => `${e}`).join("\n")),
  ]
}
/**
 * 
 * @param {Array<[Discord.Role,boolean]>} roles
 * @param {Array<Discord.Member>} members
 */
function buildComponents(roles, customId) {
  return [
    new Discord.MessageActionRow().addComponents(
      new Discord.MessageSelectMenu().setCustomId(customId).setMaxValues(roles.length).setMinValues(0).addOptions(
        roles.map(role => ({
          label: role[0].name,
          value: role[0].id,
          default: role[1]
        }))
      )
    )
  ]
}
/**
 * 
 * @param {Discord.Interaction} interaction 
 */
async function onInteraction(interaction) {
  if (!interaction.isCommand()) {
    return;
  }
  if (!interaction.guildID) {
    await interaction.reply({
      content: "サーバーで実行する必要があります。"
    });
    return;
  }
  await interaction.reply({
    content: "全メンバーを取得中",
    ephemeral: true,
  });
  const guild = interaction.guild;
  const all_members = await guild.members.fetch();
  const customId = Math.random().toString(36).substring(7);
  /** @type {Array<Discord.GuildMember>} */
  let roles = [];
  await interaction.editReply({
    embeds: buildEmbeds([], []),
    components: buildComponents([...guild.roles.cache.values()].slice(0, 25).map(e => [e, false]), customId)
  });
  const collector = new Discord.InteractionCollector(client, {
    filter: (interaction) => interaction.isSelectMenu() && interaction.customID === customId,
    time: 15 * 60 * 1000
  });
  /**
   * 
   * @param {Discord.SelectMenuInteraction} interaction 
   */
  async function onInteraction(interaction) {
    roles = (interaction.values ?? []).map(id => guild.roles.resolve(id));
    await interaction.update({
      embeds: buildEmbeds(roles, all_members.filter(member => roles.every(e => member.roles.cache.has(e.id)))),
      components: buildComponents([...guild.roles.cache.values()].slice(0, 25).map(e => [e, roles.includes(e)]), customId)
    })
  }
  collector.on("collect", (interaction) => onInteraction(interaction).catch(console.error));
}
client.on("interactionCreate", (interaction) => onInteraction(interaction).catch(console.error));
client.login(process.env.DISCORD_TOKEN).catch(console.error);
declare var guild: import("discord.js").Guild;
import * as Discord from "discord.js";
const client = new Discord.Client({
    intents: Discord.Intents.FLAGS.GUILD_MEMBERS | Discord.Intents.FLAGS.GUILDS
});
/**
 *
 * @param {Array<Discord.Role>} roles
 * @param {Array<Discord.GuildMember>} members
 */
function buildEmbeds(roles, members) {
    return [
        new Discord.MessageEmbed().setTitle("\u691C\u7D22\u5BFE\u8C61\u306E\u30ED\u30FC\u30EB").setDescription(roles.map(e => `${e}`).join("\n")),
        new Discord.MessageEmbed().setTitle("\u691C\u7D22\u7D50\u679C").setDescription(members.map(e => `${e}`).join("\n")),
    ];
}
/**
 *
 * @param {Array<[Discord.Role,boolean]>} roles
 * @param {Array<Discord.Member>} members
 */
function buildComponents(roles, customId) {
    return [
        new Discord.MessageActionRow().addComponents(new Discord.MessageSelectMenu().setCustomId(customId).setMaxValues(roles.length).setMinValues(0).addOptions(roles.map(role => ({
            label: role[0].name,
            value: role[0].id,
            default: role[1]
        }))))
    ];
}
/**
 *
 * @param {Discord.Interaction} interaction
 */
async function onInteraction(interaction) {
    if (!interaction.isCommand()) {
        return;
    }
    if (!interaction.guildID) {
        await interaction.reply({
            content: "\u30B5\u30FC\u30D0\u30FC\u3067\u5B9F\u884C\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"
        });
        return;
    }
    await interaction.reply({
        content: "\u5168\u30E1\u30F3\u30D0\u30FC\u3092\u53D6\u5F97\u4E2D",
        ephemeral: true,
    });
    const guild = interaction.guild;
    const all_members = await guild.members.fetch();
    const customId = Math.random().toString(36).substring(7);
    /** @type {Array<Discord.GuildMember>} */
    let roles = [];
    await interaction.editReply({
        embeds: buildEmbeds([], []),
        components: buildComponents([...guild.roles.cache.values()].slice(0, 25).map(e => [e, false]), customId)
    });
    const collector = new Discord.InteractionCollector(client, {
        filter: (interaction) => interaction.isSelectMenu() && interaction.customID === customId,
        time: 15 * 60 * 1000
    });
    /**
     *
     * @param {Discord.SelectMenuInteraction} interaction
     */
    async function onInteraction(interaction) {
        roles = (interaction.values ?? []).map(id => guild.roles.resolve(id));
        await interaction.update({
            embeds: buildEmbeds(roles, all_members.filter(member => roles.every(e => member.roles.cache.has(e.id)))),
            components: buildComponents([...guild.roles.cache.values()].slice(0, 25).map(e => [e, roles.includes(e)]), customId)
        });
    }
    collector.on("collect", (interaction) => onInteraction(interaction).catch(console.error));
}
client.on("interactionCreate", (interaction) => onInteraction(interaction).catch(console.error));
client.login(process.env.DISCORD_TOKEN).catch(console.error);
  • index.ts (12,22): Parameter 'roles' implicitly has an 'any' type.
  • index.ts (12,29): Parameter 'members' implicitly has an 'any' type.
  • index.ts (14,122): Parameter 'e' implicitly has an 'any' type.
  • index.ts (15,100): Parameter 'e' implicitly has an 'any' type.
  • index.ts (23,26): Parameter 'roles' implicitly has an 'any' type.
  • index.ts (23,33): Parameter 'customId' implicitly has an 'any' type.
  • index.ts (25,172): Parameter 'role' implicitly has an 'any' type.
  • index.ts (36,30): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (54,9): Variable 'roles' implicitly has type 'any[]' in some locations where its type cannot be determined.
  • index.ts (60,76): Property 'customID' does not exist on type 'SelectMenuInteraction'. Did you mean 'customId'?
  • index.ts (67,34): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (68,48): Parameter 'id' implicitly has an 'any' type.
  • index.ts (70,59): Parameter 'member' implicitly has an 'any' type.
  • index.ts (70,69): Variable 'roles' implicitly has an 'any[]' type.
  • index.ts (71,99): Variable 'roles' implicitly has an 'any[]' type.

const { Client, ClientApplication } = require("discord.js");
/**
 * 
 * @param {Client} client 
 * @param {import("discord.js").ApplicationCommandData[]} commands 
 * @param {import("discord.js").Snowflake} guildID 
 * @returns {Promise<import("@discordjs/collection").Collection<string,import("discord.js").ApplicationCommand>>}
 */
async function register(client, commands, guildID) {
  if (guildID == null) {
    return client.application.commands.set(commands);
  }
  const guild = await client.guilds.fetch(guildID);
  return guild.commands.set(commands);
}
const search = {
  name: "search",
  description: "ロールでユーザーを検索します",
 };
const commands = [search];
const client = new Client({
  intents: 0,
});
client.token = process.env.DISCORD_TOKEN;
async function main() {
  client.application = new ClientApplication(client, {});
  await client.application.fetch();
  await register(client, commands, process.argv[2]);
  console.log("registration succeed!");
}
main().catch(err=>console.error(err));
import { Client, ClientApplication } from "discord.js";
/**
 *
 * @param {Client} client
 * @param {import("discord.js").ApplicationCommandData[]} commands
 * @param {import("discord.js").Snowflake} guildID
 * @returns {Promise<import("@discordjs/collection").Collection<string,import("discord.js").ApplicationCommand>>}
 */
async function register(client, commands, guildID) {
    if (guildID == null) {
        return client.application.commands.set(commands);
    }
    const guild = await client.guilds.fetch(guildID);
    return guild.commands.set(commands);
}
const search = {
    name: "search",
    description: "\u30ED\u30FC\u30EB\u3067\u30E6\u30FC\u30B6\u30FC\u3092\u691C\u7D22\u3057\u307E\u3059",
};
const commands = [search];
const client = new Client({
    intents: 0,
});
client.token = process.env.DISCORD_TOKEN;
async function main() {
    client.application = new ClientApplication(client, {});
    await client.application.fetch();
    await register(client, commands, process.argv[2]);
    console.log("registration succeed!");
}
main().catch(err => console.error(err));
  • register.ts (10,25): Parameter 'client' implicitly has an 'any' type.
  • register.ts (10,33): Parameter 'commands' implicitly has an 'any' type.
  • register.ts (10,43): Parameter 'guildID' implicitly has an 'any' type.
  • register.ts (25,1): Type 'string | undefined' is not assignable to type 'string | null'. Type 'undefined' is not assignable to type 'string | null'.

スラッシュコマンドを使ってみよう

スラッシュコマンドを使ってみよう

const { Client, ClientApplication } = require("discord.js");
/**
 * 
 * @param {Client} client 
 * @param {import("discord.js").ApplicationCommandData[]} commands 
 * @param {import("discord.js").Snowflake} guildID 
 * @returns {Promise<import("@discordjs/collection").Collection<string,import("discord.js").ApplicationCommand>>}
 */
async function register(client, commands, guildID) {
  if (guildID == null) {
    return client.application.commands.set(commands);
  }
  const guild = await client.guilds.fetch(guildID);
  return guild.commands.set(commands);
}
const ping = {
  name: "ping",
  description: "pong!",
};
const hello = {
  name: "hello",
  description: "botがあなたに挨拶します。",
  options: [
    {
      type: "STRING",
      name: "language",
      description: "どの言語で挨拶するか指定します。",
      required: true,
      choices: [
        {
          name: "English",
          value: "en"
        },
        {
          name: "Japanese",
          value: "ja"
        }
      ],
    }
  ]
};
const commands = [ping, hello];
const client = new Client({
  intents: 0,
});
client.token = process.env.DISCORD_TOKEN;
async function main() {
  client.application = new ClientApplication(client, {});
  await client.application.fetch();
  await register(client, commands, process.argv[2]);
  console.log("registration succeed!");
}
main().catch(err=>console.error(err));
import { Client, ClientApplication } from "discord.js";
/**
 *
 * @param {Client} client
 * @param {import("discord.js").ApplicationCommandData[]} commands
 * @param {import("discord.js").Snowflake} guildID
 * @returns {Promise<import("@discordjs/collection").Collection<string,import("discord.js").ApplicationCommand>>}
 */
async function register(client, commands, guildID) {
    if (guildID == null) {
        return client.application.commands.set(commands);
    }
    const guild = await client.guilds.fetch(guildID);
    return guild.commands.set(commands);
}
const ping = {
    name: "ping",
    description: "pong!",
};
const hello = {
    name: "hello",
    description: "bot\u304C\u3042\u306A\u305F\u306B\u6328\u62F6\u3057\u307E\u3059\u3002",
    options: [
        {
            type: "STRING",
            name: "language",
            description: "\u3069\u306E\u8A00\u8A9E\u3067\u6328\u62F6\u3059\u308B\u304B\u6307\u5B9A\u3057\u307E\u3059\u3002",
            required: true,
            choices: [
                {
                    name: "English",
                    value: "en"
                },
                {
                    name: "Japanese",
                    value: "ja"
                }
            ],
        }
    ]
};
const commands = [ping, hello];
const client = new Client({
    intents: 0,
});
client.token = process.env.DISCORD_TOKEN;
async function main() {
    client.application = new ClientApplication(client, {});
    await client.application.fetch();
    await register(client, commands, process.argv[2]);
    console.log("registration succeed!");
}
main().catch(err => console.error(err));
  • register.ts (10,25): Parameter 'client' implicitly has an 'any' type.
  • register.ts (10,33): Parameter 'commands' implicitly has an 'any' type.
  • register.ts (10,43): Parameter 'guildID' implicitly has an 'any' type.
  • register.ts (47,1): Type 'string | undefined' is not assignable to type 'string | null'. Type 'undefined' is not assignable to type 'string | null'.

 const client = new Client({
   intents: 0,
 });
import { Client } from "discord.js";
const client = new Client({
    intents: 0,
});

client.token = process.env.DISCORD_TOKEN;
declare var client: import("discord.js").Client;
client.token = process.env.DISCORD_TOKEN;
  • test.ts (3,1): Type 'string | undefined' is not assignable to type 'string | null'. Type 'undefined' is not assignable to type 'string | null'.

     client.application = new ClientApplication(client, {});
     await client.application.fetch();
declare var client: import("discord.js").Client;
client.application = new ClientApplication(client, {});
await client.application.fetch();
  • test.ts (3,26): Cannot find name 'ClientApplication'.
  • test.ts (4,1): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (4,1): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (4,7): Object is possibly 'null'.

const Discord = require("discord.js");

const commands = {
  /**
   * 
   * @param {Discord.CommandInteraction} interaction 
   * @returns 
   */
  async ping(interaction) {
    const now = Date.now();
    const msg = [
      "pong!",
      "",
      `gateway: ${interaction.client.ws.ping}ms`,
    ];
    await interaction.reply({ content: msg.join("\n"), ephemeral: true });
    await interaction.editReply([...msg, `往復: ${Date.now() - now}ms`].join("\n"));
    return;
  },
  /**
   * 
   * @param {Discord.CommandInteraction} interaction 
   * @returns 
   */
  async hello(interaction) {
    const source = {
      en(name){
        return `Hello, ${name}!`
      },
      ja(name){
        return `こんにちは、${name}さん。`
      }
    };
    const lang = interaction.options.get("language");
    return interaction.reply(source[lang.value](interaction.member.displayName));
  }
};


async function onInteraction(interaction) {
  if (!interaction.isCommand()) {
    return;
  }
  return commands[interaction.commandName](interaction);
}
const client = new Discord.Client({
  intents: 0
});
client.on("interactionCreate", interaction => onInteraction(interaction).catch(err => console.error(err)));
client.login(process.env.DISCORD_TOKEN).catch(err => {
  console.error(err);
  process.exit(-1);
});
declare var client: import("discord.js").Client;
declare var member: import("discord.js").GuildMember;
import * as Discord from "discord.js";
const commands = {
    /**
     *
     * @param {Discord.CommandInteraction} interaction
     * @returns
     */
    async ping(interaction) {
        const now = Date.now();
        const msg = [
            "pong!",
            "",
            `gateway: ${interaction.client.ws.ping}ms`,
        ];
        await interaction.reply({ content: msg.join("\n"), ephemeral: true });
        await interaction.editReply([...msg, `往復: ${Date.now() - now}ms`].join("\n"));
        return;
    },
    /**
     *
     * @param {Discord.CommandInteraction} interaction
     * @returns
     */
    async hello(interaction) {
        const source = {
            en(name) {
                return `Hello, ${name}!`;
            },
            ja(name) {
                return `こんにちは、${name}さん。`;
            }
        };
        const lang = interaction.options.get("language");
        return interaction.reply(source[lang.value](interaction.member.displayName));
    }
};
async function onInteraction(interaction) {
    if (!interaction.isCommand()) {
        return;
    }
    return commands[interaction.commandName](interaction);
}
const client = new Discord.Client({
    intents: 0
});
client.on("interactionCreate", interaction => onInteraction(interaction).catch(err => console.error(err)));
client.login(process.env.DISCORD_TOKEN).catch(err => {
    console.error(err);
    process.exit(-1);
});
  • index.ts (1,13): Duplicate identifier 'client'.
  • index.ts (11,16): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (27,17): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (29,16): Parameter 'name' implicitly has an 'any' type.
  • index.ts (32,16): Parameter 'name' implicitly has an 'any' type.
  • index.ts (37,34): Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ en(name: any): string; ja(name: any): string; }'.
  • index.ts (40,30): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (44,12): Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ ping(interaction: any): Promise; hello(interaction: any): Promise; }'.
  • index.ts (46,7): Duplicate identifier 'client'.

       const msg = [
         "pong!",
         "",
         `gateway: ${interaction.client.ws.ping}ms`,
       ];
       await interaction.reply({ content: msg.join("\n"), ephemeral: true });
declare var client: import("discord.js").Client;
const msg = [
    "pong!",
    "",
    `gateway: ${interaction.client.ws.ping}ms`,
];
await interaction.reply({ content: msg.join("\n"), ephemeral: true });
  • test.ts (6,17): Cannot find name 'interaction'.
  • test.ts (8,1): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (8,1): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (8,7): Cannot find name 'interaction'.

await interaction.editReply([...msg, `往復: ${Date.now() - now}ms`].join("\n"));
await interaction.editReply([...msg, `往復: ${Date.now() - now}ms`].join("\n"));
  • test.ts (2,1): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (2,1): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (2,7): Cannot find name 'interaction'.
  • test.ts (2,33): Cannot find name 'msg'.
  • test.ts (2,58): Cannot find name 'now'.

 const lang = interaction.options.get("language");
const lang = interaction.options.get("language");
  • test.ts (2,14): Cannot find name 'interaction'.

applications.commands
applications.commands;
  • test.ts (2,1): Cannot find name 'applications'.

bot
bot;
  • test.ts (2,1): Cannot find name 'bot'.

applications.commands
applications.commands;
  • test.ts (2,1): Cannot find name 'applications'.

Guild#joinedAt
Guild;
#joinedAt;
  • test.ts (2,1): Cannot find name 'Guild'.
  • test.ts (3,1): Cannot find name '#joinedAt'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

applications.commands
applications.commands;
  • test.ts (2,1): Cannot find name 'applications'.

node register.js <your guild id>
declare var guild: import("discord.js").Guild;
node;
register.js < your;
guild;
id > ;
  • test.ts (3,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (4,1): Cannot find name 'register'.
  • test.ts (4,15): Cannot find name 'your'.
  • test.ts (6,1): Cannot find name 'id'.
  • test.ts (6,6): Expression expected.

registration succeed!
registration;
succeed!;
  • test.ts (2,1): Cannot find name 'registration'.
  • test.ts (3,1): Cannot find name 'succeed'.

Error: Cannot find module 'D:\djs-v13\regist.js'
Error: Cannot;
find;
module "D:djs-v13\regist.js";
  • test.ts (2,8): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'find'.
  • test.ts (4,8): Only ambient modules can use quoted names.

D:\djs-v13\regist.js
D: ;
djs - v13;
regist.js;
  • test.ts (3,1): Cannot find name 'djs'.
  • test.ts (3,7): Cannot find name 'v13'.
  • test.ts (4,1): Cannot find name 'regist'.

HTTPError [DiscordjsError]: Request to use token, but token was unavailable to the client.
declare var client: import("discord.js").Client;
HTTPError[DiscordjsError];
Request;
to;
use;
token, but;
token;
was;
unavailable;
to;
the;
client.;
  • test.ts (3,1): Cannot find name 'HTTPError'.
  • test.ts (3,11): Cannot find name 'DiscordjsError'.
  • test.ts (5,1): Cannot find name 'to'.
  • test.ts (6,1): Cannot find name 'use'.
  • test.ts (7,1): Cannot find name 'token'.
  • test.ts (7,1): Left side of comma operator is unused and has no side effects.
  • test.ts (7,8): Cannot find name 'but'.
  • test.ts (8,1): Cannot find name 'token'.
  • test.ts (9,1): Cannot find name 'was'.
  • test.ts (10,1): Cannot find name 'unavailable'.
  • test.ts (11,1): Cannot find name 'to'.
  • test.ts (12,1): Cannot find name 'the'.
  • test.ts (13,8): Identifier expected.

DiscordAPIError: 401: Unauthorized
DiscordAPIError: 401;
Unauthorized;
  • test.ts (3,1): Cannot find name 'Unauthorized'.

path: "/oauth2/applications/@me"
path: "/oauth2/applications/@me";

DiscordAPIError: Missing Access
DiscordAPIError: Missing;
Access;
  • test.ts (2,18): Cannot find name 'Missing'.
  • test.ts (3,1): Cannot find name 'Access'.

code:50001
code: 50001;

path:'/guilds/<your guild id>?with_counts=true'
path: "/guilds/<your guild id>?with_counts=true";

DiscordAPIError: Missing Access
DiscordAPIError: Missing;
Access;
  • test.ts (2,18): Cannot find name 'Missing'.
  • test.ts (3,1): Cannot find name 'Access'.

code:50001
code: 50001;

path: '/applications/<your application id>/guilds/<your guild id>/commands
path: "/applications/<your application id>/guilds/<your guild id>/commands";

applications.commands
applications.commands;
  • test.ts (2,1): Cannot find name 'applications'.

register
register;
  • test.ts (2,1): Cannot find name 'register'.

guildID
guildID;
  • test.ts (2,1): Cannot find name 'guildID'.

null
null;

undefined
undefined;

client.application.commands.set
declare var client: import("discord.js").Client;
client.application.commands.set;
  • test.ts (3,1): Object is possibly 'null'.

client.application
declare var client: import("discord.js").Client;
client.application;

login
login;
  • test.ts (2,1): Cannot find name 'login'.

guildID
guildID;
  • test.ts (2,1): Cannot find name 'guildID'.

guildID
guildID;
  • test.ts (2,1): Cannot find name 'guildID'.

ping
ping;
  • test.ts (2,1): Cannot find name 'ping'.

/ping
/ping;;
  • test.ts (2,2): Unterminated regular expression literal.

ApplicationCommandData
ApplicationCommandData;
  • test.ts (2,1): Cannot find name 'ApplicationCommandData'.

name
name;

^[\w-]{1,32}$
    ^ [w - ];
{
    1, 32;
}
$;
  • test.ts (2,2): Expression expected.
  • test.ts (2,4): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (2,5): Cannot find name 'w'.
  • test.ts (2,9): Expression expected.
  • test.ts (4,5): Left side of comma operator is unused and has no side effects.
  • test.ts (6,1): Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i --save-dev @types/jquery and then add 'jquery' to the types field in your tsconfig.

a
a;
  • test.ts (2,1): Cannot find name 'a'.

z
z;
  • test.ts (2,1): Cannot find name 'z'.

0
0;

9
9;

-
-;
  • test.ts (2,2): Expression expected.

_
_;
  • test.ts (2,1): Cannot find name '_'.

description
description;
  • test.ts (2,1): Cannot find name 'description'.

help
help;
  • test.ts (2,1): Cannot find name 'help'.

/help
/help;;
  • test.ts (2,2): Unterminated regular expression literal.

help
help;
  • test.ts (2,1): Cannot find name 'help'.

botがあなたに挨拶します。
botがあなたに挨拶します;
  • test.ts (2,1): Cannot find name 'botがあなたに挨拶します'.

options
options;
  • test.ts (2,1): Cannot find name 'options'. Did you mean 'Option'?

language
language;
  • test.ts (2,1): Cannot find name 'language'.

[0]
[0];

type
type;
  • test.ts (2,1): Cannot find name 'type'.

name
name;

language
language;
  • test.ts (2,1): Cannot find name 'language'.

description
description;
  • test.ts (2,1): Cannot find name 'description'.

required
required;
  • test.ts (2,1): Cannot find name 'required'. Did you mean 'require'?

required
required;
  • test.ts (2,1): Cannot find name 'required'. Did you mean 'require'?

false
false;

choices
choices;
  • test.ts (2,1): Cannot find name 'choices'.

[idx]
[idx];
  • test.ts (2,2): Cannot find name 'idx'.

name
name;

value
value;
  • test.ts (2,1): Cannot find name 'value'.

type
type;
  • test.ts (2,1): Cannot find name 'type'.

intents
intents;
  • test.ts (2,1): Cannot find name 'intents'.

login
login;
  • test.ts (2,1): Cannot find name 'login'.

login
login;
  • test.ts (2,1): Cannot find name 'login'.

main
main;
  • test.ts (2,1): Cannot find name 'main'.

client.application
declare var client: import("discord.js").Client;
client.application;

ready
ready;
  • test.ts (2,1): Cannot find name 'ready'.

ready
ready;
  • test.ts (2,1): Cannot find name 'ready'.

set
set;
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

node index.js
node;
index.js;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (3,1): Cannot find name 'index'.

/ping
/ping;;
  • test.ts (2,2): Unterminated regular expression literal.

/hello language: en
/hello language: en;;
  • test.ts (2,2): Unterminated regular expression literal.

/hello language: ja
/hello language: ja;;
  • test.ts (2,2): Unterminated regular expression literal.

on_interaction
on_interaction;
  • test.ts (2,1): Cannot find name 'on_interaction'.

Interaction
Interaction;
  • test.ts (2,1): Cannot find name 'Interaction'.

CommandInteraction
CommandInteraction;
  • test.ts (2,1): Cannot find name 'CommandInteraction'.

Interaction#isCommand
Interaction;
#isCommand;
  • test.ts (2,1): Cannot find name 'Interaction'.
  • test.ts (3,1): Cannot find name '#isCommand'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Interaction
Interaction;
  • test.ts (2,1): Cannot find name 'Interaction'.

CommandInteraction
CommandInteraction;
  • test.ts (2,1): Cannot find name 'CommandInteraction'.

MessageComponentInteraction
MessageComponentInteraction;
  • test.ts (2,1): Cannot find name 'MessageComponentInteraction'.

ButtonInteraction
ButtonInteraction;
  • test.ts (2,1): Cannot find name 'ButtonInteraction'.

ping
ping;
  • test.ts (2,1): Cannot find name 'ping'.

ephemeral: true
ephemeral: true;

ephemeral
ephemeral;
  • test.ts (2,1): Cannot find name 'ephemeral'.

defer
defer;
  • test.ts (2,1): Cannot find name 'defer'.

reply
reply;
  • test.ts (2,1): Cannot find name 'reply'.

CommandInteraction#editReply
CommandInteraction;
#editReply;
  • test.ts (2,1): Cannot find name 'CommandInteraction'.
  • test.ts (3,1): Cannot find name '#editReply'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

reply
reply;
  • test.ts (2,1): Cannot find name 'reply'.

hello
hello;
  • test.ts (2,1): Cannot find name 'hello'.

CommandInteraction#options
CommandInteraction;
#options;
  • test.ts (2,1): Cannot find name 'CommandInteraction'.
  • test.ts (3,1): Cannot find name '#options'. Did you mean 'Option'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

language
language;
  • test.ts (2,1): Cannot find name 'language'.

interaction.member.displayName
declare var member: import("discord.js").GuildMember;
interaction.member.displayName;
  • test.ts (3,1): Cannot find name 'interaction'.

interaction
interaction;
  • test.ts (2,1): Cannot find name 'interaction'.

node register.js
node;
register.js;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (3,1): Cannot find name 'register'.

ボタンを使ってみよう

ボタンを使ってみよう

const Discord = require("discord.js");
const client = new Discord.Client({
  intents: 0
});
client.token = process.env.DISCORD_TOKEN;
const GUILD_ID = process.argv[2];
const CHANNEL_ID = process.argv[3];
const ROLE_ID = process.argv[4];
async function main() {
  const guild = await client.guilds.fetch(GUILD_ID);
  /** @type {Discord.TextChannel} */
  const channel = await guild.channels.fetch(CHANNEL_ID);
  const params = new URLSearchParams();
  params.append("d", "rp");
  params.append("rid", ROLE_ID);
  const button = new Discord.MessageButton()
    .setCustomId(params.toString())
    .setStyle("PRIMARY")
    .setLabel("にゃーん")
    .setEmoji("🐈");
  await channel.send({
    content: "猫になりたい",
    components: [
      new Discord.MessageActionRow().addComponents(button)
    ]
  });
}
main().catch(err => console.error(err));
import * as Discord from "discord.js";
const client = new Discord.Client({
    intents: 0
});
client.token = process.env.DISCORD_TOKEN;
const GUILD_ID = process.argv[2];
const CHANNEL_ID = process.argv[3];
const ROLE_ID = process.argv[4];
async function main() {
    const guild = await client.guilds.fetch(GUILD_ID);
    /** @type {Discord.TextChannel} */
    const channel = await guild.channels.fetch(CHANNEL_ID);
    const params = new URLSearchParams();
    params.append("d", "rp");
    params.append("rid", ROLE_ID);
    const button = new Discord.MessageButton()
        .setCustomId(params.toString())
        .setStyle("PRIMARY")
        .setLabel("\u306B\u3083\u30FC\u3093")
        .setEmoji("\uD83D\uDC08");
    await channel.send({
        content: "\u732B\u306B\u306A\u308A\u305F\u3044",
        components: [
            new Discord.MessageActionRow().addComponents(button)
        ]
    });
}
main().catch(err => console.error(err));
  • install.ts (6,1): Type 'string | undefined' is not assignable to type 'string | null'. Type 'undefined' is not assignable to type 'string | null'.
  • install.ts (11,45): No overload matches this call. Overload 1 of 2, '(options: ${bigint} | FetchGuildOptions): Promise', gave the following error. Argument of type 'string' is not assignable to parameter of type '${bigint} | FetchGuildOptions'. Overload 2 of 2, '(options?: FetchGuildsOptions | undefined): Promise<Collection<${bigint}, OAuth2Guild>>', gave the following error. Argument of type 'string' is not assignable to parameter of type 'FetchGuildsOptions | undefined'.
  • install.ts (13,48): No overload matches this call. Overload 1 of 2, '(id: ${bigint}, options?: BaseFetchOptions | undefined): Promise<CategoryChannel | TextChannel | NewsChannel | VoiceChannel | StageChannel | StoreChannel | null>', gave the following error. Argument of type 'string' is not assignable to parameter of type '${bigint}'. Overload 2 of 2, '(id?: undefined, options?: BaseFetchOptions | undefined): Promise<Collection<${bigint}, CategoryChannel | TextChannel | NewsChannel | VoiceChannel | StageChannel | StoreChannel>>', gave the following error. Argument of type 'string' is not assignable to parameter of type 'undefined'.
  • install.ts (22,19): Property 'send' does not exist on type '(CategoryChannel | TextChannel | NewsChannel | VoiceChannel | StageChannel | StoreChannel | null) & Collection<...>'. Property 'send' does not exist on type 'CategoryChannel & Collection<${bigint}, CategoryChannel | TextChannel | NewsChannel | VoiceChannel | StageChannel | StoreChannel>'.

const Discord = require("discord.js");
const client = new Discord.Client({ intents: 0, partials: ["GUILD_MEMBER", "USER"] });
/**
 * 
 * @param {unknown} err 
 * @param {object} ctx
 * @param {Discord.ButtonInteraction} ctx.interaction 
 * @param {Discord.Snowflake} ctx.role_id
 * @param {string} ctx.role_mention
 * @returns 
 */
async function handleError(err, { interaction, role_id, role_mention }) {
  if (err instanceof Discord.DiscordAPIError) {
    switch (err.code) {
      case 10011:
        await interaction.followUp(`役職の付与に失敗しました。\n付与しようとした役職(id: \`${role_id}\`)は存在しません。\n(サーバ管理者へ連絡してください。)`);
        return;
      case 50013:
        await interaction.followUp(
          `${role_mention}の付与に失敗しました。\nBotに十分な権限がありません。\n(サーバ管理者へ連絡してください。)`,
        );
        return;
    }
  }
  interaction.followUp(`${role_mention}の付与に失敗しました。\n時間をおいてやり直してください。`).catch(() => { });
  throw err;
}
/**
 * 
 * @param {Discord.ButtonInteraction} interaction 
 * @returns 
 */
function validateRequest(interaction) {
  return interaction.message.author.id === client.user.id && interaction.channelId === interaction.message.channel_id && interaction.message.components.flatMap((/** @type {Discord.MessageActionRow|(import("discord-api-types").APIActionRowComponent)} */ component) => {
    return component.components;
  }).some((/** @type {Discord.MessageActionRowComponent | import("discord-api-types").APIButtonComponent | import("discord-api-types").APISelectMenuComponent} */component) => {
    const customId = component.customId ?? component.custom_id;
    return customId === interaction.customId;
  });
}
/**
 * 
 * @param {Discord.ButtonInteraction} interaction 
 * @param {URLSearchParams} params 
 * @returns 
 */
async function rolePanel(interaction, params) {
  /** @type {Discord.Snowflake} */
  const role_id = params.get("rid");
  await interaction.defer({
    ephemeral: true
  });
  const guild = await interaction.guild.fetch();
  // APIからのメンバーオブジェクト(discord.jsのGuildMemberでないもの)がそのまま渡ってくることがあるのでfetchすることで確実にGuildMemberとする。
  // interaction.member.user.idでなければならない。なぜならば、APIInteractionGuildMemberはid を直接持たないからである。
  const member = await guild.members.fetch(interaction.member.user.id,{
    force: true // intentsによってはGuildMemberUpdateが配信されないため
  });
  const role_mention = `<@&${role_id}>`;
  if (member.roles.resolve(role_id)) {
    await interaction.followUp(`すでに、${role_mention}を持っています。`);
    return;
  }
  try {
    await member.roles.add(role_id);
  } catch (err) {
    await handleError(err, { interaction, role_id, role_mention });
    return;
  }
  await interaction.followUp({
    content: `${role_mention} を付与しました。`
  });
}
const buttons = {
  rp: rolePanel
};
/**
 * 
 * @param {Discord.Interaction} interaction 
 */
async function onInteraction(interaction) {
  if (!interaction.isButton()) {
    return;
  }
  const params = new URLSearchParams(interaction.customId);
  if (!validateRequest(interaction)) {
    throw new Error("invalid request!");
  }
  await buttons[params.get("d")](interaction, params);
}
client.once("ready", () => {
  console.log(`Logged in as: ${client.user.username}#${client.user.discriminator}`);
  // ready後にready以前に実行されたinteractionのinteractionCreateがemitされるが、そのときにはinteractionがtimeoutしておりfollowupで失敗することがよくある。
  // そのようなことを避けるためready内でハンドラを登録する。
  client.on("interactionCreate", (interaction) => onInteraction(interaction).catch(err => console.error(err)));
});
client.login(process.env.DISCORD_TOKEN);
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
declare var user: import("discord.js").User;
import * as Discord from "discord.js";
const client = new Discord.Client({ intents: 0, partials: ["GUILD_MEMBER", "USER"] });
/**
 *
 * @param {unknown} err
 * @param {object} ctx
 * @param {Discord.ButtonInteraction} ctx.interaction
 * @param {Discord.Snowflake} ctx.role_id
 * @param {string} ctx.role_mention
 * @returns
 */
async function handleError(err, { interaction, role_id, role_mention }) {
    if (err instanceof Discord.DiscordAPIError) {
        switch (err.code) {
            case 10011:
                await interaction.followUp(`役職の付与に失敗しました。\n付与しようとした役職(id: \`${role_id}\`)は存在しません。\n(サーバ管理者へ連絡してください。)`);
                return;
            case 50013:
                await interaction.followUp(`${role_mention}の付与に失敗しました。\nBotに十分な権限がありません。\n(サーバ管理者へ連絡してください。)`);
                return;
        }
    }
    interaction.followUp(`${role_mention}の付与に失敗しました。\n時間をおいてやり直してください。`).catch(() => { });
    throw err;
}
/**
 *
 * @param {Discord.ButtonInteraction} interaction
 * @returns
 */
function validateRequest(interaction) {
    return interaction.message.author.id === client.user.id && interaction.channelId === interaction.message.channel_id && interaction.message.components.flatMap((/** @type {Discord.MessageActionRow|(import("discord-api-types").APIActionRowComponent)} */ component) => {
        return component.components;
    }).some((/** @type {Discord.MessageActionRowComponent | import("discord-api-types").APIButtonComponent | import("discord-api-types").APISelectMenuComponent} */ component) => {
        const customId = component.customId ?? component.custom_id;
        return customId === interaction.customId;
    });
}
/**
 *
 * @param {Discord.ButtonInteraction} interaction
 * @param {URLSearchParams} params
 * @returns
 */
async function rolePanel(interaction, params) {
    /** @type {Discord.Snowflake} */
    const role_id = params.get("rid");
    await interaction.defer({
        ephemeral: true
    });
    const guild = await interaction.guild.fetch();
    // APIからのメンバーオブジェクト(discord.jsのGuildMemberでないもの)がそのまま渡ってくることがあるのでfetchすることで確実にGuildMemberとする。
    // interaction.member.user.idでなければならない。なぜならば、APIInteractionGuildMemberはid を直接持たないからである。
    const member = await guild.members.fetch(interaction.member.user.id, {
        force: true // intentsによってはGuildMemberUpdateが配信されないため
    });
    const role_mention = `<@&${role_id}>`;
    if (member.roles.resolve(role_id)) {
        await interaction.followUp(`すでに、${role_mention}を持っています。`);
        return;
    }
    try {
        await member.roles.add(role_id);
    }
    catch (err) {
        await handleError(err, { interaction, role_id, role_mention });
        return;
    }
    await interaction.followUp({
        content: `${role_mention} を付与しました。`
    });
}
const buttons = {
    rp: rolePanel
};
/**
 *
 * @param {Discord.Interaction} interaction
 */
async function onInteraction(interaction) {
    if (!interaction.isButton()) {
        return;
    }
    const params = new URLSearchParams(interaction.customId);
    if (!validateRequest(interaction)) {
        throw new Error("invalid request!");
    }
    await buttons[params.get("d")](interaction, params);
}
client.once("ready", () => {
    console.log(`Logged in as: ${client.user.username}#${client.user.discriminator}`);
    // ready後にready以前に実行されたinteractionのinteractionCreateがemitされるが、そのときにはinteractionがtimeoutしておりfollowupで失敗することがよくある。
    // そのようなことを避けるためready内でハンドラを登録する。
    client.on("interactionCreate", (interaction) => onInteraction(interaction).catch(err => console.error(err)));
});
client.login(process.env.DISCORD_TOKEN);
  • index.ts (17,28): Parameter 'err' implicitly has an 'any' type.
  • index.ts (17,35): Binding element 'interaction' implicitly has an 'any' type.
  • index.ts (17,48): Binding element 'role_id' implicitly has an 'any' type.
  • index.ts (17,57): Binding element 'role_mention' implicitly has an 'any' type.
  • index.ts (36,26): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (37,46): Object is possibly 'null'.
  • index.ts (37,256): Parameter 'component' implicitly has an 'any' type.
  • index.ts (39,165): Parameter 'component' implicitly has an 'any' type.
  • index.ts (50,26): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (50,39): Parameter 'params' implicitly has an 'any' type.
  • index.ts (85,30): Parameter 'interaction' implicitly has an 'any' type.
  • index.ts (93,19): Type 'null' cannot be used as an index type.
  • index.ts (96,34): Object is possibly 'null'.
  • index.ts (96,58): Object is possibly 'null'.

13.0.0-dev.5b6be0c.1625789033
13;
0 - dev;
0.5;
b6be0c;
0.1625789033;
  • test.ts (3,5): Cannot find name 'dev'.
  • test.ts (5,1): Cannot find name 'b6be0c'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

application/x-www-form-urlencoded
application / x - www - form - urlencoded;
  • test.ts (2,1): Cannot find name 'application'.
  • test.ts (2,15): Cannot find name 'x'.
  • test.ts (2,19): Cannot find name 'www'.
  • test.ts (2,25): Cannot find name 'form'.
  • test.ts (2,32): Cannot find name 'urlencoded'.

d
d;
  • test.ts (2,1): Cannot find name 'd'.

rp
rp;
  • test.ts (2,1): Cannot find name 'rp'.

rid
rid;
  • test.ts (2,1): Cannot find name 'rid'.

send
send;
  • test.ts (2,1): Cannot find name 'send'.

components
components;
  • test.ts (2,1): Cannot find name 'components'.

MessageOptions
MessageOptions;
  • test.ts (2,1): Cannot find name 'MessageOptions'.

PRIMARY
PRIMARY;
  • test.ts (2,1): Cannot find name 'PRIMARY'.

SUCCESS
SUCCESS;
  • test.ts (2,1): Cannot find name 'SUCCESS'.

SECONDARY
SECONDARY;
  • test.ts (2,1): Cannot find name 'SECONDARY'.

DANGER
DANGER;
  • test.ts (2,1): Cannot find name 'DANGER'.

LINK
LINK;
  • test.ts (2,1): Cannot find name 'LINK'.

setStyle
setStyle;
  • test.ts (2,1): Cannot find name 'setStyle'.

setEmoji
setEmoji;
  • test.ts (2,1): Cannot find name 'setEmoji'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

LINK
LINK;
  • test.ts (2,1): Cannot find name 'LINK'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

url
url;
  • test.ts (2,1): Cannot find name 'url'. Did you mean 'URL'?

URLSearchParams
URLSearchParams;

https://google.com/search?q=xxxx
https: ; //google.com/search?q=xxxx

q=xxxx
q = xxxx;
  • test.ts (2,1): Cannot find name 'q'.
  • test.ts (2,5): Cannot find name 'xxxx'.

TypeError: guild.channels.fetch is not a function
declare var guild: import("discord.js").Guild;
TypeError: guild.channels.fetch;
is;
not;
a;
function ();
  • test.ts (4,1): Cannot find name 'is'.
  • test.ts (5,1): Cannot find name 'not'.
  • test.ts (6,1): Cannot find name 'a'.
  • test.ts (7,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (7,10): Identifier expected.

ButtonInteraction#defer
ButtonInteraction;
#defer;
  • test.ts (2,1): Cannot find name 'ButtonInteraction'.
  • test.ts (3,1): Cannot find name '#defer'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

ButtonInteraction#followUp
ButtonInteraction;
#followUp;
  • test.ts (2,1): Cannot find name 'ButtonInteraction'.
  • test.ts (3,1): Cannot find name '#followUp'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

validateRequest
validateRequest;
  • test.ts (2,1): Cannot find name 'validateRequest'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

message
declare var message: import("discord.js").Message;
message;

message
declare var message: import("discord.js").Message;
message;

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

message
declare var message: import("discord.js").Message;
message;

Gateway Intents を指定するサンプル

Gateway Intents を指定するサンプル

const { Intents, Client } = require("discord.js");
// import { Intents, Client } from "discord.js";
import { Intents, Client } from "discord.js";
// import { Intents, Client } from "discord.js";

const options = {
   intents: ["GUILDS", "GUILD_MESSAGES"],
};
const client = new Client(options);
import { Client } from "discord.js";
const options = {
    intents: ["GUILDS", "GUILD_MESSAGES"],
};
const client = new Client(options);
  • main.ts (6,27): Argument of type '{ intents: string[]; }' is not assignable to parameter of type 'ClientOptions'. Types of property 'intents' are incompatible. Type 'string[]' is not assignable to type 'BitFieldResolvable<IntentsString, number>'. Type 'string[]' is not assignable to type 'RecursiveReadonlyArray<number | ${bigint} | IntentsString | Readonly<BitField<IntentsString, number>>>'. Type 'string' is not assignable to type 'number | ${bigint} | IntentsString | Readonly<BitField<IntentsString, number>> | RecursiveReadonlyArray<number | ${bigint} | IntentsString | Readonly<...>>'.

const options = {
  intents: Intents.FLAGS.GUILDS | Intents.FLAGS.GUILD_MESSAGES,
};
const client = new Client(options);
import { Intents } from "discord.js";
import { Client } from "discord.js";
const options = {
    intents: Intents.FLAGS.GUILDS | Intents.FLAGS.GUILD_MESSAGES,
};
const client = new Client(options);

 const options = {
   ws: {
     intents: Intents.ALL,
   },
 };
 const client = new Client(options);
import { Intents } from "discord.js";
import { Client } from "discord.js";
const options = {
    ws: {
        intents: Intents.ALL,
    },
};
const client = new Client(options);
  • main.ts (6,26): Property 'ALL' does not exist on type 'typeof Intents'.
  • main.ts (9,27): Argument of type '{ ws: { intents: any; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ ws: { intents: any; }; }' but required in type 'ClientOptions'.

 const options = {
   ws: {
     intents: Intents.NON_PRIVILEGED,
   },
 };
 const client = new Client(options);
import { Intents } from "discord.js";
import { Client } from "discord.js";
const options = {
    ws: {
        intents: Intents.NON_PRIVILEGED,
    },
};
const client = new Client(options);
  • main.ts (6,26): Property 'NON_PRIVILEGED' does not exist on type 'typeof Intents'.
  • main.ts (9,27): Argument of type '{ ws: { intents: any; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ ws: { intents: any; }; }' but required in type 'ClientOptions'.

const options = {
  ws: {
    intents: ["GUILDS", "GUILD_MESSAGES"],
  },
};
const client = new Client(options);
import { Client } from "discord.js";
const options = {
    ws: {
        intents: ["GUILDS", "GUILD_MESSAGES"],
    },
};
const client = new Client(options);
  • main.ts (8,27): Argument of type '{ ws: { intents: string[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ ws: { intents: string[]; }; }' but required in type 'ClientOptions'.

const options = {
  ws: {
    intents: Intents.FLAGS.GUILDS | Intents.FLAGS.GUILD_MESSAGES,
  },
};
const client = new Client(options);
import { Intents } from "discord.js";
import { Client } from "discord.js";
const options = {
    ws: {
        intents: Intents.FLAGS.GUILDS | Intents.FLAGS.GUILD_MESSAGES,
    },
};
const client = new Client(options);
  • main.ts (9,27): Argument of type '{ ws: { intents: number; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ ws: { intents: number; }; }' but required in type 'ClientOptions'.

 const options = {
   ws: {
     intents: Intents.ALL&~(Intents.FLAGS.GUILD_MESSAGE_TYPING|Intents.FLAGS.DIRECT_MESSAGE_TYPING),
   },
 };
 const client = new Client(options);
import { Intents } from "discord.js";
import { Client } from "discord.js";
const options = {
    ws: {
        intents: Intents.ALL & ~(Intents.FLAGS.GUILD_MESSAGE_TYPING | Intents.FLAGS.DIRECT_MESSAGE_TYPING),
    },
};
const client = new Client(options);
  • main.ts (6,26): Property 'ALL' does not exist on type 'typeof Intents'.
  • main.ts (9,27): Argument of type '{ ws: { intents: number; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ ws: { intents: number; }; }' but required in type 'ClientOptions'.

const intents = Intents.FLAGS.GUILDS | Intents.FLAGS.GUILD_MESSAGES;
const options = {
  intents,
  ws: {
    intents,
  },
};
const client = new Client(options);
import { Intents } from "discord.js";
import { Client } from "discord.js";
const intents = Intents.FLAGS.GUILDS | Intents.FLAGS.GUILD_MESSAGES;
const options = {
    intents,
    ws: {
        intents,
    },
};
const client = new Client(options);
  • main.ts (11,27): Argument of type '{ intents: number; ws: { intents: number; }; }' is not assignable to parameter of type 'ClientOptions'. Types of property 'ws' are incompatible. Type '{ intents: number; }' has no properties in common with type 'WebSocketOptions'.

Intents
import { Intents } from "discord.js";
Intents;

テキストチャンネルで一番最初に送信されたメッセージを取得する

テキストチャンネルで一番最初に送信されたメッセージを取得する

message.channel.messages.fetch({ after: '0', limit: 1 }) // メッセージが送信されたチャンネルで一番最初に送信されたメッセージを取得する
  .then(messages => messages.first()) // コレクションからメッセージが送信されたチャンネルで一番最初に送信されたメッセージを取り出す
  .then(m => console.log(m.url)) // コンソールへメッセージが送信されたチャンネルで一番最初に送信されたメッセージのURLをコンソールへ表示
  .catch(console.error)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.messages.fetch({ after: "0", limit: 1 }) // メッセージが送信されたチャンネルで一番最初に送信されたメッセージを取得する
    .then(messages => messages.first()) // コレクションからメッセージが送信されたチャンネルで一番最初に送信されたメッセージを取り出す
    .then(m => console.log(m.url)) // コンソールへメッセージが送信されたチャンネルで一番最初に送信されたメッセージのURLをコンソールへ表示
    .catch(console.error);
  • test.ts (6,28): Object is possibly 'undefined'.

MessageManager#fetch({ after: '0', limit: 1 })
MessageManager;
#fetch({ after: "0", limit: 1 });
  • test.ts (2,1): Cannot find name 'MessageManager'.
  • test.ts (3,1): Cannot find name '#fetch'. Did you mean 'fetch'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Promise<Collection<Snowflake, Message>>
Promise<Collection<Snowflake, Message>>();
  • test.ts (2,1): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?
  • test.ts (2,9): Cannot find name 'Collection'.
  • test.ts (2,20): Cannot find name 'Snowflake'.
  • test.ts (2,31): Cannot find name 'Message'.

対象のメッセージの上にあるメッセージを取得する

対象のメッセージの上にあるメッセージを取得する

client.on('message', async message => {
  const beforeMessage = await message.channel.messages.fetch({ before: message.id, limit: 1 })
    .then(messages => messages.first())
    .catch(console.error)

  return beforeMessage.reply('Hey') // 一つ上のメッセージを送信したユーザーにメンション付きで「Hey」と送信
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    const beforeMessage = await message.channel.messages.fetch({ before: message.id, limit: 1 })
        .then(messages => messages.first())
        .catch(console.error);
    return beforeMessage.reply("Hey"); // 一つ上のメッセージを送信したユーザーにメンション付きで「Hey」と送信
});
  • test.ts (4,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message, TResult2 = never>(onfulfilled?: ((value: Message) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (8,12): Object is possibly 'undefined'.
  • used message Event

messages
messages;
  • test.ts (2,1): Cannot find name 'messages'. Did you mean 'onmessage'?

fetch
fetch;

before
before;
  • test.ts (2,1): Cannot find name 'before'.

before
before;
  • test.ts (2,1): Cannot find name 'before'.

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

1
1;

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

1
1;

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

1
1;

.first()
first();
  • test.ts (2,1): Cannot find name 'first'.

.last()
last();
  • test.ts (2,1): Cannot find name 'last'.

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

catch
try { }
catch { }

customId ( と value )になるべく長いバイト列を入れたい

customId ( と value )になるべく長いバイト列を入れたい

function chunk(arr, size) {
   return arr.reduce(
     (newarr, _, i) => (i % size ? newarr : [...newarr, arr.slice(i, i + size)]),
     []
   );
 }
function encode_helper([a,b = 0,c = 0,d = 0,e = 0]) {
  return [(a<<12)|(b<<4)|((c&0xF0)>>4),((c&0x0F)<<16)|(d<<8)|e];
}
function encode(arr) {
  return String.fromCodePoint(...chunk(arr,5).flatMap(encode_helper));
}
function parse_helper([a,b]) {
  return [a>>12,(a>>4)&0xFF,(a&0x0F)<<4|(b>>16),(b>>8)&0xFF,b&0xFF];
}
function parse(str) {
  return chunk([...str].map(e=>e.codePointAt(0)),2).flatMap(parse_helper);
}
function chunk(arr, size) {
    return arr.reduce((newarr, _, i) => (i % size ? newarr : [...newarr, arr.slice(i, i + size)]), []);
}
function encode_helper([a, b = 0, c = 0, d = 0, e = 0]) {
    return [(a << 12) | (b << 4) | ((c & 240) >> 4), ((c & 15) << 16) | (d << 8) | e];
}
function encode(arr) {
    return String.fromCodePoint(...chunk(arr, 5).flatMap(encode_helper));
}
function parse_helper([a, b]) {
    return [a >> 12, (a >> 4) & 255, (a & 15) << 4 | (b >> 16), (b >> 8) & 255, b & 255];
}
function parse(str) {
    return chunk([...str].map(e => e.codePointAt(0)), 2).flatMap(parse_helper);
}
  • test.ts (2,16): Parameter 'arr' implicitly has an 'any' type.
  • test.ts (2,21): Parameter 'size' implicitly has an 'any' type.
  • test.ts (3,24): Parameter 'newarr' implicitly has an 'any' type.
  • test.ts (3,32): Parameter '_' implicitly has an 'any' type.
  • test.ts (3,35): Parameter 'i' implicitly has an 'any' type.
  • test.ts (5,25): Binding element 'a' implicitly has an 'any' type.
  • test.ts (8,17): Parameter 'arr' implicitly has an 'any' type.
  • test.ts (11,24): Binding element 'a' implicitly has an 'any' type.
  • test.ts (11,27): Binding element 'b' implicitly has an 'any' type.
  • test.ts (14,16): Parameter 'str' implicitly has an 'any' type.

> parse(encode([0xFF,0xFF,0xFF,0xFF,0xFF]))
[ 255, 255, 255, 255, 255 ]
> parse(encode([0xFF,0xFF,0xFF,0xFF,0x00]))
[ 255, 255, 255, 255, 0 ]
> parse(encode([0xFF,0xFF,0xFF,0xFF]))
[ 255, 255, 255, 255, 0 ]
> parse(encode([0xFF,0xFF,0xFF]))
[ 255, 255, 255, 0, 0 ]
> parse(encode([0xFF,0xFF]))
[ 255, 255, 0, 0, 0 ]
> parse(encode([0xFF]))
[ 255, 0, 0, 0, 0 ]
> parse(encode([]))
[]
> encoded = encode([...Buffer.from("a".repeat(250)).values()])
> [...encoded].length
100
> /a{250}/.test(Buffer.from(parse(encoded)).toString())
true
    > parse(encode([255, 255, 255, 255, 255]))[255, 255, 255, 255, 255]
    > parse(encode([255, 255, 255, 255, 0]))[255, 255, 255, 255, 0]
    > parse(encode([255, 255, 255, 255]))[255, 255, 255, 255, 0]
    > parse(encode([255, 255, 255]))[255, 255, 255, 0, 0]
    > parse(encode([255, 255]))[255, 255, 0, 0, 0]
    > parse(encode([255]))[255, 0, 0, 0, 0]
    > parse(encode([]))[]
    > encoded;
encode([...Buffer.from("a".repeat(250)).values()])
    > [...encoded].length;
100
    > /a{250}/.test(Buffer.from(parse(encoded)).toString());
true;
  • test.ts (2,2): Expression expected.
  • test.ts (2,4): Cannot find name 'parse'.
  • test.ts (2,10): Cannot find name 'encode'. Did you mean 'Node'?
  • test.ts (2,45): Left side of comma operator is unused and has no side effects.
  • test.ts (2,45): Left side of comma operator is unused and has no side effects.
  • test.ts (2,45): Left side of comma operator is unused and has no side effects.
  • test.ts (2,45): Left side of comma operator is unused and has no side effects.
  • test.ts (3,7): Cannot find name 'parse'.
  • test.ts (3,13): Cannot find name 'encode'. Did you mean 'Node'?
  • test.ts (3,46): Left side of comma operator is unused and has no side effects.
  • test.ts (3,46): Left side of comma operator is unused and has no side effects.
  • test.ts (3,46): Left side of comma operator is unused and has no side effects.
  • test.ts (3,46): Left side of comma operator is unused and has no side effects.
  • test.ts (4,7): Cannot find name 'parse'.
  • test.ts (4,13): Cannot find name 'encode'. Did you mean 'Node'?
  • test.ts (4,43): Left side of comma operator is unused and has no side effects.
  • test.ts (4,43): Left side of comma operator is unused and has no side effects.
  • test.ts (4,43): Left side of comma operator is unused and has no side effects.
  • test.ts (4,43): Left side of comma operator is unused and has no side effects.
  • test.ts (5,7): Cannot find name 'parse'.
  • test.ts (5,13): Cannot find name 'encode'. Did you mean 'Node'?
  • test.ts (5,38): Left side of comma operator is unused and has no side effects.
  • test.ts (5,38): Left side of comma operator is unused and has no side effects.
  • test.ts (5,38): Left side of comma operator is unused and has no side effects.
  • test.ts (5,38): Left side of comma operator is unused and has no side effects.
  • test.ts (6,7): Cannot find name 'parse'.
  • test.ts (6,13): Cannot find name 'encode'. Did you mean 'Node'?
  • test.ts (6,33): Left side of comma operator is unused and has no side effects.
  • test.ts (6,33): Left side of comma operator is unused and has no side effects.
  • test.ts (6,33): Left side of comma operator is unused and has no side effects.
  • test.ts (6,33): Left side of comma operator is unused and has no side effects.
  • test.ts (7,7): Cannot find name 'parse'.
  • test.ts (7,13): Cannot find name 'encode'.
  • test.ts (7,28): Left side of comma operator is unused and has no side effects.
  • test.ts (7,28): Left side of comma operator is unused and has no side effects.
  • test.ts (7,28): Left side of comma operator is unused and has no side effects.
  • test.ts (7,28): Left side of comma operator is unused and has no side effects.
  • test.ts (8,7): Cannot find name 'parse'.
  • test.ts (8,13): Cannot find name 'encode'.
  • test.ts (8,25): An element access expression should take an argument.
  • test.ts (9,7): Cannot find name 'encoded'.
  • test.ts (10,1): Cannot find name 'encode'.
  • test.ts (11,11): Cannot find name 'encoded'.
  • test.ts (12,1): Operator '>' cannot be applied to types 'number' and 'boolean'.
  • test.ts (13,33): Cannot find name 'parse'.
  • test.ts (13,39): Cannot find name 'encoded'.

メンバーが参加するのに使用した招待コードを検知するサンプル

メンバーが参加するのに使用した招待コードを検知するサンプル

// 招待コードを記憶しておくためのオブジェクトを定義
const allInvites = {}

client.on('ready', () => {
  // ボット起動時に全サーバーの招待コードを読み込んで記録する
  client.guilds.cache.forEach(guild => {
    guild.fetchInvites().then(invites => {
      allInvites[guild.id] = invites
    }).catch(console.error);
  })
})

client.on('guildMemberAdd', member => {
  // メンバーが参加したサーバーの招待コードを全て取得する
  member.guild.fetchInvites().then(invites => {
    // 以前に取得したサーバーの招待コードを変数に入れて保持する
    const oldInvites = allInvites[member.guild.id]
    // 新たに取得した招待コードに置き換え
    allInvites[member.guild.id] = invites
    // 以前に取得した招待コードと新たに取得したので、使用回数が増えたものを探す
    const invite = invites.find(i => oldInvites.get(i.code).uses < i.uses)
    // ログに出す
    console.log(`${member.user.tag}${invite.code} を使ってサーバーに参加しました`)
  }).catch(console.error);
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
// 招待コードを記憶しておくためのオブジェクトを定義
const allInvites = {};
client.on("ready", () => {
    // ボット起動時に全サーバーの招待コードを読み込んで記録する
    client.guilds.cache.forEach(guild => {
        guild.fetchInvites().then(invites => {
            allInvites[guild.id] = invites;
        }).catch(console.error);
    });
});
client.on("guildMemberAdd", member => {
    // メンバーが参加したサーバーの招待コードを全て取得する
    member.guild.fetchInvites().then(invites => {
        // 以前に取得したサーバーの招待コードを変数に入れて保持する
        const oldInvites = allInvites[member.guild.id];
        // 新たに取得した招待コードに置き換え
        allInvites[member.guild.id] = invites;
        // 以前に取得した招待コードと新たに取得したので、使用回数が増えたものを探す
        const invite = invites.find(i => oldInvites.get(i.code).uses < i.uses);
        // ログに出す
        console.log(`${member.user.tag}${invite.code} を使ってサーバーに参加しました`);
    }).catch(console.error);
});
  • test.ts (10,15): Property 'fetchInvites' does not exist on type 'Guild'.
  • test.ts (10,35): Parameter 'invites' implicitly has an 'any' type.
  • test.ts (11,13): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (17,18): Property 'fetchInvites' does not exist on type 'Guild'.
  • test.ts (17,38): Parameter 'invites' implicitly has an 'any' type.
  • test.ts (19,28): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (21,9): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (23,37): Parameter 'i' implicitly has an 'any' type.

トークンに紐付いているアプリケーションの情報を取得する

トークンに紐付いているアプリケーションの情報を取得する

const app = await client.fetchApplication();
console.log(app);
declare var client: import("discord.js").Client;
const app = await client.fetchApplication();
console.log(app);
  • test.ts (3,13): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (3,13): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (3,26): Property 'fetchApplication' does not exist on type 'Client'.

client.application = client.application || new ClientApplication(client, {});
const app = await client.application.fetch();
console.log(app);
declare var client: import("discord.js").Client;
client.application = client.application || new ClientApplication(client, {});
const app = await client.application.fetch();
console.log(app);
  • test.ts (3,48): Cannot find name 'ClientApplication'.
  • test.ts (4,13): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (4,13): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (4,19): Object is possibly 'null'.

ChannelManager.add(channel,guild,cache = true) の動作メモ

ChannelManager.add(channel,guild,cache = true) の動作メモ

add(data, guild, cache = true) {
  const existing = this.cache.get(data.id);
  if (existing) {
    if (existing._patch && cache) existing._patch(data);
    if (guild) guild.channels.add(existing);
    return existing;
  }
  const channel = Channel.create(this.client, data, guild);
  if (!channel) {
    this.client.emit(Events.DEBUG, `Failed to find guild, or unknown type for channel ${data.id} ${data.type}`);
    return null;
  }
  if (cache) this.cache.set(channel.id, channel);
  return channel;
}
declare var guild: import("discord.js").Guild;
declare var client: import("discord.js").Client;
add(data, guild, cache = true);
{
    const existing = this.cache.get(data.id);
    if (existing) {
        if (existing._patch && cache)
            existing._patch(data);
        if (guild)
            guild.channels.add(existing);
        return existing;
    }
    const channel = Channel.create(this.client, data, guild);
    if (!channel) {
        this.client.emit(Events.DEBUG, `Failed to find guild, or unknown type for channel ${data.id} ${data.type}`);
        return null;
    }
    if (cache)
        this.cache.set(channel.id, channel);
    return channel;
}
  • test.ts (4,1): Cannot find name 'add'.
  • test.ts (4,5): Cannot find name 'data'.
  • test.ts (4,18): Cannot find name 'cache'. Did you mean 'Cache'?
  • test.ts (6,27): Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
  • test.ts (6,37): Cannot find name 'data'.
  • test.ts (8,32): Cannot find name 'cache'. Did you mean 'Cache'?
  • test.ts (9,29): Cannot find name 'data'.
  • test.ts (11,28): Property 'add' does not exist on type 'GuildChannelManager'.
  • test.ts (12,9): A 'return' statement can only be used within a function body.
  • test.ts (14,21): Cannot find name 'Channel'. Did you mean 'channel'?
  • test.ts (14,49): Cannot find name 'data'.
  • test.ts (16,26): Cannot find name 'Events'. Did you mean 'Event'?
  • test.ts (16,93): Cannot find name 'data'.
  • test.ts (16,104): Cannot find name 'data'.
  • test.ts (17,9): A 'return' statement can only be used within a function body.
  • test.ts (19,9): Cannot find name 'cache'.
  • test.ts (20,14): Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
  • test.ts (21,5): A 'return' statement can only be used within a function body.

channelManager.add(channel,guild,cache = true)
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var guild: import("discord.js").Guild;
channelManager.add(channel, guild, cache = true);
  • test.ts (4,1): Cannot find name 'channelManager'.
  • test.ts (4,36): Cannot find name 'cache'. Did you mean 'Cache'?

guildChannelManager.add()
guildChannelManager.add();
  • test.ts (2,1): Cannot find name 'guildChannelManager'.

Channel.create(this.client, data, guild);
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
Channel.create(this.client, data, guild);
  • test.ts (4,1): Cannot find name 'Channel'.
  • test.ts (4,29): Cannot find name 'data'.

guildChannelManager.add()
guildChannelManager.add();
  • test.ts (2,1): Cannot find name 'guildChannelManager'.

Channel.create()
Channel.create();
  • test.ts (2,1): Cannot find name 'Channel'.

GuildChannel._patch()
GuildChannel._patch();
  • test.ts (2,1): Cannot find name 'GuildChannel'.

super._patch()
super._patch();
  • test.ts (2,1): 'super' can only be referenced in members of derived classes or object literal expressions.

embedの内容を抽出する

embedの内容を抽出する

const Discord = require('discord.js')
const client = new Discord.Client()
 
client.on('message', async message => {
	if (message.embeds[0]) {
		message.channel.send(`埋め込みのタイトルは${message.embeds[0].title}です`);
	}
});
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", async (message) => {
    if (message.embeds[0]) {
        message.channel.send(`埋め込みのタイトルは${message.embeds[0].title}です`);
    }
});
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • used message Event

SQL Injection

SQL Injection

const Database = require('better-sqlite3');
const { Client, MessageEmbed } = require("discord.js");
const db = new Database('sqli.db', { verbose: console.log });
const client = new Client({
  allowedMentions: {
    parse: []
  }
});
const prefix = "!";
const token = process.env.DISCORD_TOKEN;
db.exec("CREATE TABLE IF NOT EXISTS memos(guild integer,id integer,value text,PRIMARY KEY(id,guild))");
async function onMessage(message) {
  if (!message.guild) {
    return;
  }
  const [l1, ...lines] = message.content.split("\n");
  if (l1 === prefix + "set") {
    const value = lines.join("\n").trim();
    if (value.length == 0 ){
      //よくないけどDiscordの気が狂わない限り大丈夫
      db.exec(`DELETE FROM memos WHERE guild = ${message.guild.id} AND id = ${message.author.id}`);
      await message.channel.send("メモを削除しました。");
      return;
    }
    //よくない
    db.exec(`INSERT OR REPLACE INTO memos VALUES (${message.guild.id},${message.author.id},'${value}')`);
    await message.channel.send("メモを設定しました。");
    return;
  }
  const [cmd, ...args] = l1.split(" ");
  if (cmd === prefix + "get") {
    //よくない
    const memo = db.prepare(`SELECT value FROM memos WHERE guild = ${message.guild.id} AND id = ${args[0] ?? message.author.id}`).get();
    if (memo) {
      await message.channel.send(memo.value);
    } else {
      await message.channel.send(new MessageEmbed().setDescription("該当のユーザーのメモは見つかりませんでした。"));
    }
  }
}
client.on("message", (message) => {
   onMessage(message).catch((err) => console.error(err));
});
client.login(token);
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import * as Database from "better-sqlite3";
import { Client, MessageEmbed } from "discord.js";
const db = new Database("sqli.db", { verbose: console.log });
const client = new Client({
    allowedMentions: {
        parse: []
    }
});
const prefix = "!";
const token = process.env.DISCORD_TOKEN;
db.exec("CREATE TABLE IF NOT EXISTS memos(guild integer,id integer,value text,PRIMARY KEY(id,guild))");
async function onMessage(message) {
    if (!message.guild) {
        return;
    }
    const [l1, ...lines] = message.content.split("\n");
    if (l1 === prefix + "set") {
        const value = lines.join("\n").trim();
        if (value.length == 0) {
            //よくないけどDiscordの気が狂わない限り大丈夫
            db.exec(`DELETE FROM memos WHERE guild = ${message.guild.id} AND id = ${message.author.id}`);
            await message.channel.send("\u30E1\u30E2\u3092\u524A\u9664\u3057\u307E\u3057\u305F\u3002");
            return;
        }
        //よくない
        db.exec(`INSERT OR REPLACE INTO memos VALUES (${message.guild.id},${message.author.id},'${value}')`);
        await message.channel.send("\u30E1\u30E2\u3092\u8A2D\u5B9A\u3057\u307E\u3057\u305F\u3002");
        return;
    }
    const [cmd, ...args] = l1.split(" ");
    if (cmd === prefix + "get") {
        //よくない
        const memo = db.prepare(`SELECT value FROM memos WHERE guild = ${message.guild.id} AND id = ${args[0] ?? message.author.id}`).get();
        if (memo) {
            await message.channel.send(memo.value);
        }
        else {
            await message.channel.send(new MessageEmbed().setDescription("\u8A72\u5F53\u306E\u30E6\u30FC\u30B6\u30FC\u306E\u30E1\u30E2\u306F\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002"));
        }
    }
}
client.on("message", (message) => {
    onMessage(message).catch((err) => console.error(err));
});
client.login(token);
  • bot.ts (4,27): Cannot find module 'better-sqlite3' or its corresponding type declarations.
  • bot.ts (7,27): Argument of type '{ allowedMentions: { parse: never[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ allowedMentions: { parse: never[]; }; }' but required in type 'ClientOptions'.
  • bot.ts (15,26): Parameter 'message' implicitly has an 'any' type.
  • used message Event

fetch("https://discord.com/api/v8/channels/<Channel Id>/messages", {
  "headers": {
    "accept": "*/*",
    "accept-language": "en-GB",
    "authorization": "<TOKEN>",
    "content-type": "application/json",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin"
  },
  "body": "{\"content\":\"!get 0\\tOR\\tTRUE\\tORDER\\tBY\\tguild,id\\tLIMIT\\t1\\tOFFSET\\t1\"}",
  "method": "POST",
  "mode": "cors"
});
fetch("https://discord.com/api/v8/channels/<Channel Id>/messages", {
    "headers": {
        "accept": "*/*",
        "accept-language": "en-GB",
        "authorization": "<TOKEN>",
        "content-type": "application/json",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin"
    },
    "body": "{\"content\":\"!get 0\\tOR\\tTRUE\\tORDER\\tBY\\tguild,id\\tLIMIT\\t1\\tOFFSET\\t1\"}",
    "method": "POST",
    "mode": "cors"
});

async function onMessage(message) {
  const [l1, ...lines] = message.content.split("\n");
  if (!message.guild) {
    return;
  }
  if (l1 === prefix + "set") {
    const value = lines.join("\n").trim();
    if (value.length == 0) {
      //改善した
      db.prepare(`DELETE FROM memos WHERE guild = ? AND id = ?`).run(message.guild.id, message.author.id);
      await message.channel.send("メモを削除しました。");
      return;
    }
    //改善した
    db.prepare(`INSERT OR REPLACE INTO memos VALUES (?,?,?)`).run(message.guild.id, message.author.id, value);
    await message.channel.send("メモを設定しました。");
    return;
  }
  const [cmd, ...args] = l1.split(" ");
  if (cmd === prefix + "get") {
    //改善した
    const memo = db.prepare(`SELECT value FROM memos WHERE guild = ? AND id = ?`).get(message.guild.id, args[0] ?? message.author.id);
    if (memo) {
      await message.channel.send(memo.value);
    } else {
      await message.channel.send(new MessageEmbed().setDescription("該当のユーザーのメモは見つかりませんでした。"));
    }
  }
}
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
async function onMessage(message) {
    const [l1, ...lines] = message.content.split("\n");
    if (!message.guild) {
        return;
    }
    if (l1 === prefix + "set") {
        const value = lines.join("\n").trim();
        if (value.length == 0) {
            //改善した
            db.prepare(`DELETE FROM memos WHERE guild = ? AND id = ?`).run(message.guild.id, message.author.id);
            await message.channel.send("\u30E1\u30E2\u3092\u524A\u9664\u3057\u307E\u3057\u305F\u3002");
            return;
        }
        //改善した
        db.prepare(`INSERT OR REPLACE INTO memos VALUES (?,?,?)`).run(message.guild.id, message.author.id, value);
        await message.channel.send("\u30E1\u30E2\u3092\u8A2D\u5B9A\u3057\u307E\u3057\u305F\u3002");
        return;
    }
    const [cmd, ...args] = l1.split(" ");
    if (cmd === prefix + "get") {
        //改善した
        const memo = db.prepare(`SELECT value FROM memos WHERE guild = ? AND id = ?`).get(message.guild.id, args[0] ?? message.author.id);
        if (memo) {
            await message.channel.send(memo.value);
        }
        else {
            await message.channel.send(new MessageEmbed().setDescription("\u8A72\u5F53\u306E\u30E6\u30FC\u30B6\u30FC\u306E\u30E1\u30E2\u306F\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002"));
        }
    }
}
  • sqli.ts (4,26): Parameter 'message' implicitly has an 'any' type.
  • sqli.ts (9,16): Cannot find name 'prefix'.
  • sqli.ts (13,13): Cannot find name 'db'.
  • sqli.ts (18,9): Cannot find name 'db'.
  • sqli.ts (23,17): Cannot find name 'prefix'.
  • sqli.ts (25,22): Cannot find name 'db'.
  • sqli.ts (30,44): Cannot find name 'MessageEmbed'.

function search(searchText) {
	return db.prepare(`SELECT name,exp FROM users WHERE ${searchText.split(" ").join(" AND ")}`).all();
}
function search(searchText) {
    return db.prepare(`SELECT name,exp FROM users WHERE ${searchText.split(" ").join(" AND ")}`).all();
}
  • search.ts (2,17): Parameter 'searchText' implicitly has an 'any' type.
  • search.ts (3,12): Cannot find name 'db'.

const allowedColumn = new Set(["id","name"]);
function search(searchText) {
	const kv = searchText.split(" ")
		.map(e => e.split("="))
		.filter(([k, v]) => allowedColumn.has(k));
	if (kv.length === 0) {
		throw new Error("invalid searchText");
	}
 	return db.prepare(`SELECT id,name,exp FROM users WHERE ${kv.map(([k, v]) => k + "=?").join(" AND ")}  LIMIT 100`).all(kv.map(([k, v]) => v));
}
const allowedColumn = new Set(["id", "name"]);
function search(searchText) {
    const kv = searchText.split(" ")
        .map(e => e.split("="))
        .filter(([k, v]) => allowedColumn.has(k));
    if (kv.length === 0) {
        throw new Error("invalid searchText");
    }
    return db.prepare(`SELECT id,name,exp FROM users WHERE ${kv.map(([k, v]) => k + "=?").join(" AND ")}  LIMIT 100`).all(kv.map(([k, v]) => v));
}
  • search.ts (3,17): Parameter 'searchText' implicitly has an 'any' type.
  • search.ts (5,14): Parameter 'e' implicitly has an 'any' type.
  • search.ts (6,19): Binding element 'k' implicitly has an 'any' type.
  • search.ts (6,22): Binding element 'v' implicitly has an 'any' type.
  • search.ts (10,12): Cannot find name 'db'.
  • search.ts (10,71): Binding element 'k' implicitly has an 'any' type.
  • search.ts (10,74): Binding element 'v' implicitly has an 'any' type.
  • search.ts (10,132): Binding element 'k' implicitly has an 'any' type.
  • search.ts (10,135): Binding element 'v' implicitly has an 'any' type.

fetch
fetch;

JavaScript Injection

JavaScript Injection

const { Client } = require("discord.js");
const client = new Client({
  allowedMentions: {
    parse: []
  }
});
const prefix = "!";
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
  const [l1, ...lines] = message.content.split("\n");
  if (!message.guild) {
    return;
  }
  if (l1 === prefix + "calc") {
    const result = eval(lines.join("\n"));
    await message.channel.send(String(result));
  }
}
client.on("message", (message) => {
  onMessage(message).catch((err) => console.error(err));
});
client.login(token);
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { Client } from "discord.js";
const client = new Client({
    allowedMentions: {
        parse: []
    }
});
const prefix = "!";
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
    const [l1, ...lines] = message.content.split("\n");
    if (!message.guild) {
        return;
    }
    if (l1 === prefix + "calc") {
        const result = eval(lines.join("\n"));
        await message.channel.send(String(result));
    }
}
client.on("message", (message) => {
    onMessage(message).catch((err) => console.error(err));
});
client.login(token);
  • calc.ts (5,27): Argument of type '{ allowedMentions: { parse: never[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ allowedMentions: { parse: never[]; }; }' but required in type 'ClientOptions'.
  • calc.ts (12,26): Parameter 'message' implicitly has an 'any' type.
  • used message Event

DoS

DoS

const { Client } = require("discord.js");
const client = new Client({
  allowedMentions: {
    parse: []
  }
});
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
  const arr = message.content.split("d");
  if (arr.length != 2) {
    return;
  }
  const [num, max] = arr.map(e => Number.parseInt(e, 10));
  if (Number.isNaN(num) && Number.isNaN(max)) {
    return;
  }
  const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
  const sum = roll_result.reduce((acc, cur) => acc + cur);
  await message.channel.send(num > 24 ? `合計:${String(sum)}` : `合計:${String(sum)}\n${roll_result.join(",")}`);
}
client.on("message", (message) => {
  onMessage(message).catch((err) => console.error(err));
});
client.login(token);
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { Client } from "discord.js";
const client = new Client({
    allowedMentions: {
        parse: []
    }
});
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
    const arr = message.content.split("d");
    if (arr.length != 2) {
        return;
    }
    const [num, max] = arr.map(e => Number.parseInt(e, 10));
    if (Number.isNaN(num) && Number.isNaN(max)) {
        return;
    }
    const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
    const sum = roll_result.reduce((acc, cur) => acc + cur);
    await message.channel.send(num > 24 ? `合計:${String(sum)}` : `合計:${String(sum)}\n${roll_result.join(",")}`);
}
client.on("message", (message) => {
    onMessage(message).catch((err) => console.error(err));
});
client.login(token);
  • dice-bot.ts (4,27): Argument of type '{ allowedMentions: { parse: never[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ allowedMentions: { parse: never[]; }; }' but required in type 'ClientOptions'.
  • dice-bot.ts (10,26): Parameter 'message' implicitly has an 'any' type.
  • dice-bot.ts (15,32): Parameter 'e' implicitly has an 'any' type.
  • used message Event

const { Client } = require("discord.js");
const client = new Client({
  allowedMentions: {
    parse: []
  }
});
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
  const arr = message.content.split("d");
  if (arr.length != 2) {
    return;
  }
  const [num, max] = arr.map(e => Number.parseInt(e, 10));
  if (Number.isNaN(num) && Number.isNaN(max)) {
    return;
  }
  //追加
  if (num >= 10000) {
    await message.channel.send("サイコロの個数は10000個以下とする必要があります。");
    return;
  }
  const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
  const sum = roll_result.reduce((acc, cur) => acc + cur);
  await message.channel.send(num > 24 ? `合計:${String(sum)}` : `合計:${String(sum)}\n${roll_result.join(",")}`);
}
client.on("message", (message) => {
  onMessage(message).catch((err) => console.error(err));
});
client.login(token);
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { Client } from "discord.js";
const client = new Client({
    allowedMentions: {
        parse: []
    }
});
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
    const arr = message.content.split("d");
    if (arr.length != 2) {
        return;
    }
    const [num, max] = arr.map(e => Number.parseInt(e, 10));
    if (Number.isNaN(num) && Number.isNaN(max)) {
        return;
    }
    //追加
    if (num >= 10000) {
        await message.channel.send("\u30B5\u30A4\u30B3\u30ED\u306E\u500B\u6570\u306F10000\u500B\u4EE5\u4E0B\u3068\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002");
        return;
    }
    const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
    const sum = roll_result.reduce((acc, cur) => acc + cur);
    await message.channel.send(num > 24 ? `合計:${String(sum)}` : `合計:${String(sum)}\n${roll_result.join(",")}`);
}
client.on("message", (message) => {
    onMessage(message).catch((err) => console.error(err));
});
client.login(token);
  • dice-bot.ts (4,27): Argument of type '{ allowedMentions: { parse: never[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ allowedMentions: { parse: never[]; }; }' but required in type 'ClientOptions'.
  • dice-bot.ts (10,26): Parameter 'message' implicitly has an 'any' type.
  • dice-bot.ts (15,32): Parameter 'e' implicitly has an 'any' type.
  • used message Event

 const { Client } = require("discord.js");
 const client = new Client({
   allowedMentions: {
     parse: []
   }
 });
 function rnorm() {
   return Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
 }
 function calc_V(mean, max) {
   return -(max * (max + 1) * (max + 2) / 6 - mean * max * (max + 1) + max * mean * mean) / max;
 }
 function dice2(num, max) {
   const max_result = num * max;
   if (!Number.isSafeInteger(max_result)) {
     throw new TypeError("too large input!");
   }
   const mean = (max + 1) / 2;
   const v = calc_V(mean, max);
   const sigma = Math.sqrt(v / num);
   while (true) {
     const result = Math.round((sigma * rnorm() + mean) * num);
     if (num <= result && result <= max_result) {
       return result;
     }
   }
 }
 const token = process.env.DISCORD_TOKEN;
 async function onMessage(message) {
   const arr = message.content.split("d");
   if (arr.length != 2) {
     return;
   }
   const [num, max] = arr.map(e => Number.parseInt(e, 10));
   if (Number.isNaN(num) && Number.isNaN(max)) {
     return;
   }
   //追加
   if (num >= 10000) {
     await message.channel.send(`合計:${String(dice2(num, max))}`);
     return;
   }
   const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
   const sum = roll_result.reduce((acc, cur) => acc + cur);
   await message.channel.send(num > 24 ? `合計:${String(sum)}` : `合計:${String(sum)}\n${roll_result.join(",")}`);
 }
 client.on("message", (message) => {
   onMessage(message).catch((err) => console.error(err));
 });
 client.login(token);
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { Client } from "discord.js";
const client = new Client({
    allowedMentions: {
        parse: []
    }
});
function rnorm() {
    return Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
}
function calc_V(mean, max) {
    return -(max * (max + 1) * (max + 2) / 6 - mean * max * (max + 1) + max * mean * mean) / max;
}
function dice2(num, max) {
    const max_result = num * max;
    if (!Number.isSafeInteger(max_result)) {
        throw new TypeError("too large input!");
    }
    const mean = (max + 1) / 2;
    const v = calc_V(mean, max);
    const sigma = Math.sqrt(v / num);
    while (true) {
        const result = Math.round((sigma * rnorm() + mean) * num);
        if (num <= result && result <= max_result) {
            return result;
        }
    }
}
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
    const arr = message.content.split("d");
    if (arr.length != 2) {
        return;
    }
    const [num, max] = arr.map(e => Number.parseInt(e, 10));
    if (Number.isNaN(num) && Number.isNaN(max)) {
        return;
    }
    //追加
    if (num >= 10000) {
        await message.channel.send(`合計:${String(dice2(num, max))}`);
        return;
    }
    const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
    const sum = roll_result.reduce((acc, cur) => acc + cur);
    await message.channel.send(num > 24 ? `合計:${String(sum)}` : `合計:${String(sum)}\n${roll_result.join(",")}`);
}
client.on("message", (message) => {
    onMessage(message).catch((err) => console.error(err));
});
client.login(token);
  • dice-bot.ts (4,27): Argument of type '{ allowedMentions: { parse: never[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ allowedMentions: { parse: never[]; }; }' but required in type 'ClientOptions'.
  • dice-bot.ts (12,17): Parameter 'mean' implicitly has an 'any' type.
  • dice-bot.ts (12,23): Parameter 'max' implicitly has an 'any' type.
  • dice-bot.ts (15,16): Parameter 'num' implicitly has an 'any' type.
  • dice-bot.ts (15,21): Parameter 'max' implicitly has an 'any' type.
  • dice-bot.ts (31,26): Parameter 'message' implicitly has an 'any' type.
  • dice-bot.ts (36,32): Parameter 'e' implicitly has an 'any' type.
  • used message Event

メンションの昇格

メンションの昇格

const { Client } = require("discord.js");
const client = new Client();
const prefix = "!";
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
  const [l1, ...lines] = message.content.split("\n");
  if (!message.guild) {
    return;
  }
  if (l1 === prefix + "say") {
    await message.channel.send(lines.join("\n"));
  }
}
client.on("message", (message) => {
  onMessage(message).catch((err) => console.error(err));
});
client.login(token);
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { Client } from "discord.js";
const client = new Client();
const prefix = "!";
const token = process.env.DISCORD_TOKEN;
async function onMessage(message) {
    const [l1, ...lines] = message.content.split("\n");
    if (!message.guild) {
        return;
    }
    if (l1 === prefix + "say") {
        await message.channel.send(lines.join("\n"));
    }
}
client.on("message", (message) => {
    onMessage(message).catch((err) => console.error(err));
});
client.login(token);
  • parrot.ts (5,16): Expected 1 arguments, but got 0.
  • parrot.ts (8,26): Parameter 'message' implicitly has an 'any' type.
  • used message Event

// 推奨: 指定のないメッセージではメンションを無効化し、個別に許可する
const client = new Client({
  allowedMentions: {
    parse: []
  }
});
import { Client } from "discord.js";
// 推奨: 指定のないメッセージではメンションを無効化し、個別に許可する
const client = new Client({
    allowedMentions: {
        parse: []
    }
});
  • parrot2.ts (4,27): Argument of type '{ allowedMentions: { parse: never[]; }; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ allowedMentions: { parse: never[]; }; }' but required in type 'ClientOptions'.

   const allowedMentions = message.member.permissions.has("MENTION_EVERYONE") ? {} : {
       parse: []
   };
  // 個別にメンションを無効化することもできる
   await message.channel.send(lines.join("\n"), {
     allowedMentions
   });
declare var message: import("discord.js").Message;
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const allowedMentions = message.member.permissions.has("MENTION_EVERYONE") ? {} : {
    parse: []
};
// 個別にメンションを無効化することもできる
await message.channel.send(lines.join("\n"), {
    allowedMentions
});
  • parrot3.ts (5,25): Object is possibly 'null'.
  • parrot3.ts (9,1): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • parrot3.ts (9,1): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • parrot3.ts (9,28): Cannot find name 'lines'.
  • parrot3.ts (9,46): Expected 1 arguments, but got 2.

if (!message.member.permissions.has("MENTION_EVERYONE")) {
	await message.channel.send("あなたはメンションを送信する権限を持っていません");
	return;
}
declare var message: import("discord.js").Message;
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
if (!message.member.permissions.has("MENTION_EVERYONE")) {
    await message.channel.send("\u3042\u306A\u305F\u306F\u30E1\u30F3\u30B7\u30E7\u30F3\u3092\u9001\u4FE1\u3059\u308B\u6A29\u9650\u3092\u6301\u3063\u3066\u3044\u307E\u305B\u3093");
    return;
}
  • parrot4.ts (5,6): Object is possibly 'null'.
  • parrot4.ts (6,5): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • parrot4.ts (6,5): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • parrot4.ts (7,5): A 'return' statement can only be used within a function body.

yuto0214w

yuto0214w

import '/api/code/yuto0214w/yuto0214w/script.js'
import "/api/code/yuto0214w/yuto0214w/script.js";

権限を持つ人だけが実行できるBANコマンドのサンプル

権限を持つ人だけが実行できるBANコマンドのサンプル

client.on('message', async message => {
  if (message.content.startsWith('!ban') && message.guild) {
  	if (!message.member.permissions.has("BAN_MEMBERS")) return message.channel.send('あなたにはユーザーをBANする権限がありません');
    if (message.mentions.members.size !== 1) return message.channel.send('BANするメンバーを1人指定してください');
    const member = message.mentions.members.first();
    if (!member.bannable) return message.channel.send('botがこのユーザーをBANすることができません');
         
    await member.ban();
         
    await message.channel.send(`${member.user.tag} をBANしました`);
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    if (message.content.startsWith("!ban") && message.guild) {
        if (!message.member.permissions.has("BAN_MEMBERS"))
            return message.channel.send("\u3042\u306A\u305F\u306B\u306F\u30E6\u30FC\u30B6\u30FC\u3092BAN\u3059\u308B\u6A29\u9650\u304C\u3042\u308A\u307E\u305B\u3093");
        if (message.mentions.members.size !== 1)
            return message.channel.send("BAN\u3059\u308B\u30E1\u30F3\u30D0\u30FC\u30921\u4EBA\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
        const member = message.mentions.members.first();
        if (!member.bannable)
            return message.channel.send("bot\u304C\u3053\u306E\u30E6\u30FC\u30B6\u30FC\u3092BAN\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093");
        await member.ban();
        await message.channel.send(`${member.user.tag} をBANしました`);
    }
});
  • test.ts (7,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (9,14): Object is possibly 'null'.
  • test.ts (11,13): Object is possibly 'null'.
  • test.ts (13,24): Object is possibly 'null'.
  • test.ts (14,14): Object is possibly 'undefined'.
  • test.ts (16,15): Object is possibly 'undefined'.
  • test.ts (17,39): Object is possibly 'undefined'.
  • used message Event

音声を受け取る

音声を受け取る

const fs = require('fs');

const audio = connection.receiver.createStream(user, { mode: 'pcm' });

audio.pipe(fs.createWriteStream('user_audio'));
declare var user: import("discord.js").User;
import * as fs from "fs";
const audio = connection.receiver.createStream(user, { mode: "pcm" });
audio.pipe(fs.createWriteStream("user_audio"));
  • test.ts (4,15): Cannot find name 'connection'.

ユーザーに聞き返す処理のサンプル

ユーザーに聞き返す処理のサンプル

client.on('message', async message => {
  if (message.content === '!prompt') {
    message.channel.send('yes か no を送信してください')
    const filter = msg => msg.author.id === message.author.id
    const collected = await message.channel.awaitMessages(filter, { max: 1, time: 10000 })
    const response = collected.first()
    if (!response) return message.channel.send('タイムアウト')
    if (!['yes', 'no'].includes(response.content)) return message.channel.send('正しくありません')
    message.channel.send(`${response.content} が送信されました`)
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    if (message.content === "!prompt") {
        message.channel.send("yes \u304B no \u3092\u9001\u4FE1\u3057\u3066\u304F\u3060\u3055\u3044");
        const filter = msg => msg.author.id === message.author.id;
        const collected = await message.channel.awaitMessages(filter, { max: 1, time: 10000 });
        const response = collected.first();
        if (!response)
            return message.channel.send("\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8");
        if (!["yes", "no"].includes(response.content))
            return message.channel.send("\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093");
        message.channel.send(`${response.content} が送信されました`);
    }
});
  • test.ts (4,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (7,24): Parameter 'msg' implicitly has an 'any' type.
  • test.ts (8,71): Expected 0-1 arguments, but got 2.
  • used message Event

!prompt
!prompt;

タイムアウト
タイムアウト;
  • test.ts (2,1): Cannot find name 'タイムアウト'.

共通のサーバーを取得するサンプル

共通のサーバーを取得するサンプル

const Discord = require("discord.js");
/**
 * cacheを利用して共通のサーバーのメンバーオブジェクトを取得する
 * @param {import("@discordjs/collection").Collection<Discord.Snowflake,Discord.Guild>} guilds 
 * @param {Discord.UserResolvable} user
 * @returns {Discord.GuildMember[]}
 */
function getMutualGuilds(guilds, user) {
  return guilds.map(guild => guild.members.resolve(user)).filter(e => !!e);
}
import * as Discord from "discord.js";
/**
 * cacheを利用して共通のサーバーのメンバーオブジェクトを取得する
 * @param {import("@discordjs/collection").Collection<Discord.Snowflake,Discord.Guild>} guilds
 * @param {Discord.UserResolvable} user
 * @returns {Discord.GuildMember[]}
 */
function getMutualGuilds(guilds, user) {
    return guilds.map(guild => guild.members.resolve(user)).filter(e => !!e);
}
  • test.ts (9,26): Parameter 'guilds' implicitly has an 'any' type.
  • test.ts (9,34): Parameter 'user' implicitly has an 'any' type.
  • test.ts (10,23): Parameter 'guild' implicitly has an 'any' type.
  • test.ts (10,68): Parameter 'e' implicitly has an 'any' type.

const members = getMutualGuilds(client.guilds.cache, "408939071289688064");
members.forEach(member => console.log(member));
declare var client: import("discord.js").Client;
const members = getMutualGuilds(client.guilds.cache, "408939071289688064");
members.forEach(member => console.log(member));
  • test.ts (3,17): Cannot find name 'getMutualGuilds'.
  • test.ts (4,17): Parameter 'member' implicitly has an 'any' type.

 const Discord = require("discord.js");
 /** 
  * Discord Opcodes and Status Codes
  * {@link https://discord.com/developers/docs/topics/opcodes-and-status-codes#json}
  */
 const DISCORD_JSON_ERROR_CODE_UNKNOWN_MEMBER = 10007;
 function handleError(error) {
    if (!(error instanceof Discord.DiscordAPIError) || error.code !== DISCORD_JSON_ERROR_CODE_UNKNOWN_MEMBER) {
      throw error;
    }
    return null;
  }
/**
 * APIへアクセスして共通のサーバーのメンバーオブジェクトを取得する
 * @param {import("@discordjs/collection").Collection<Discord.Snowflake,Discord.Guild>} guilds 
 * @param {Discord.UserResolvable} user 
 * @param {Omit<Discord.FetchMemberOptions,"user">} options
 * @returns {Promise<Discord.GuildMember[]>}
 */
async function fetchMutualGuilds(guilds, user, options = {}) {
  return (await Promise.all(guilds.map(guild => guild.members.fetch({ user, ...options }).catch(handleError)))).filter(e => !!e);
}
import * as Discord from "discord.js";
/**
 * Discord Opcodes and Status Codes
 * {@link https://discord.com/developers/docs/topics/opcodes-and-status-codes#json}
 */
const DISCORD_JSON_ERROR_CODE_UNKNOWN_MEMBER = 10007;
function handleError(error) {
    if (!(error instanceof Discord.DiscordAPIError) || error.code !== DISCORD_JSON_ERROR_CODE_UNKNOWN_MEMBER) {
        throw error;
    }
    return null;
}
/**
 * APIへアクセスして共通のサーバーのメンバーオブジェクトを取得する
 * @param {import("@discordjs/collection").Collection<Discord.Snowflake,Discord.Guild>} guilds
 * @param {Discord.UserResolvable} user
 * @param {Omit<Discord.FetchMemberOptions,"user">} options
 * @returns {Promise<Discord.GuildMember[]>}
 */
async function fetchMutualGuilds(guilds, user, options = {}) {
    return (await Promise.all(guilds.map(guild => guild.members.fetch({ user, ...options }).catch(handleError)))).filter(e => !!e);
}
  • test.ts (8,22): Parameter 'error' implicitly has an 'any' type.
  • test.ts (21,34): Parameter 'guilds' implicitly has an 'any' type.
  • test.ts (21,42): Parameter 'user' implicitly has an 'any' type.
  • test.ts (22,42): Parameter 'guild' implicitly has an 'any' type.

const members = await fetchMutualGuilds(client.guilds.cache, "408939071289688064");
members.forEach(member => console.log(member));
declare var client: import("discord.js").Client;
const members = await fetchMutualGuilds(client.guilds.cache, "408939071289688064");
members.forEach(member => console.log(member));
  • test.ts (3,17): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (3,17): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (3,23): Cannot find name 'fetchMutualGuilds'.
  • test.ts (4,17): Parameter 'member' implicitly has an 'any' type.

guilds.size
guilds.size;
  • test.ts (2,1): Cannot find name 'guilds'.

Discord.jsを使用してSnowflakeを生成、解析する

Discord.jsを使用してSnowflakeを生成、解析する

const { SnowflakeUtil } = require('discord.js')

// 生成
console.log(SnowflakeUtil.generate())

// 解析
console.log(SnowflakeUtil.deconstruct('391390986770710528'))
import { SnowflakeUtil } from "discord.js";
// 生成
console.log(SnowflakeUtil.generate());
// 解析
console.log(SnowflakeUtil.deconstruct("391390986770710528"));

generate
generate;
  • test.ts (2,1): Cannot find name 'generate'.

Date
Date;

number
number;
  • test.ts (2,1): 'number' only refers to a type, but is being used as a value here.

deconstruct
deconstruct;
  • test.ts (2,1): Cannot find name 'deconstruct'.

timestamp
timestamp;
  • test.ts (2,1): Cannot find name 'timestamp'.

workerId
workerId;
  • test.ts (2,1): Cannot find name 'workerId'. Did you mean 'Worker'?

processId
processId;
  • test.ts (2,1): Cannot find name 'processId'. Did you mean 'process'?

increment
increment;
  • test.ts (2,1): Cannot find name 'increment'.

binary
binary;
  • test.ts (2,1): Cannot find name 'binary'.

なぜ型定義で実際に返される型のUnion Typeになっていないのか

なぜ型定義で実際に返される型のUnion Typeになっていないのか

const isTextChannel = (channel: Discord.Channel): channel is Discord.TextChannel => channel.type === 'text'
import * as Discord from "discord.js";
import { TextChannel } from "discord.js";
const isTextChannel = (channel: Discord.Channel): channel is Discord.TextChannel => channel.type === "text";
  • test.ts (4,85): This condition will always return 'false' since the types '"GUILD_CATEGORY" | "GUILD_TEXT" | "DM" | "GUILD_VOICE" | "GROUP_DM" | "GUILD_NEWS" | "GUILD_STORE" | "UNKNOWN" | "GUILD_NEWS_THREAD" | "GUILD_PUBLIC_THREAD" | "GUILD_PRIVATE_THREAD" | "GUILD_STAGE_VOICE"' and '"text"' have no overlap.

client.channels.get(id)
declare var client: import("discord.js").Client;
client.channels.get(id);
  • test.ts (3,17): Property 'get' does not exist on type 'ChannelManager'.
  • test.ts (3,21): Cannot find name 'id'.

TextChannel
import { TextChannel } from "discord.js";
TextChannel;

DMChannel
import { DMChannel } from "discord.js";
DMChannel;

Channel
Channel;
  • test.ts (2,1): Cannot find name 'Channel'.

TextChannel
import { TextChannel } from "discord.js";
TextChannel;

Channel
Channel;
  • test.ts (2,1): Cannot find name 'Channel'.

as
as;
  • test.ts (2,1): Cannot find name 'as'.

Channel
Channel;
  • test.ts (2,1): Cannot find name 'Channel'.

discordjs/discord.js#69d69f2
import * as discord from "discord.js";
discordjs / discord.js;
#;
69;
d69f2;
  • test.ts (3,1): Cannot find name 'discordjs'. Did you mean 'discord'?
  • test.ts (3,21): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.
  • test.ts (4,1): Cannot find name '#'.
  • test.ts (4,1): Private identifiers are not allowed outside class bodies.
  • test.ts (4,2): Invalid character.
  • test.ts (6,1): Cannot find name 'd69f2'.

TextChannel | VoiceChannel
import { TextChannel } from "discord.js";
import { VoiceChannel } from "discord.js";
TextChannel | VoiceChannel;
  • test.ts (4,1): The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (4,15): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

Promise<TextChannel> | Promise<VoiceChannel>
import { TextChannel } from "discord.js";
import { VoiceChannel } from "discord.js";
Promise<TextChannel>( | Promise<VoiceChannel>());
  • test.ts (4,1): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?
  • test.ts (4,23): Expression expected.
  • test.ts (4,25): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?

as
as;
  • test.ts (2,1): Cannot find name 'as'.

as
as;
  • test.ts (2,1): Cannot find name 'as'.

channel.type
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.type;
  • test.ts (3,9): Property 'type' does not exist on type 'Omit<TextChannel, "type"> & Omit<VoiceChannel, "type">'.

リアクションを使って簡単にページネーションを作成する Discord.js 専用のパッケージ

リアクションを使って簡単にページネーションを作成する Discord.js 専用のパッケージ

const { Client, MessageEmbed } = require('discord.js')
const { ReactionController } = require('discord.js-reaction-controller')
const { getBasicInfo } = require('ytdl-core')

const client = new Client()

const fetchYouTubeVideoInfo = videoUrl => async () => {
  const { videoDetails } = await getBasicInfo(videoUrl)

  return new MessageEmbed()
    .setColor('RED')
    .setTitle(videoDetails.title)
    .setURL(videoDetails.video_url)
    .setImage(videoDetails.thumbnails[videoDetails.thumbnails.length - 1].url)
    .setTimestamp(Date.parse(videoDetails.publishDate))
    .setFooter('Uploaded on')
    .setAuthor(videoDetails.author.name, videoDetails.author.thumbnails[0].url, videoDetails.author.channel_url)
}


const videos = [
  'https://youtu.be/sWbD5q769Ms',
  'https://youtu.be/0-zJNiSvz8Q',
  'https://youtu.be/1x2izJEN9p0',
  'https://youtu.be/gNp4VNr44hg',
  'https://youtu.be/Vi_asBY5UX8',
  'https://youtu.be/plqoPcKQnyE',
  'https://youtu.be/308I91ljCWg'
]

client.on('message', message => {
  if (message.content.startsWith('>pagination')) {
    const controller = new ReactionController(client)

    controller
      .addReactionHandler('🤔', (reaction) => {
        reaction.message.channel.send('thinking')
          .catch(console.error)
      })

    controller.addPages(videos.map(url => fetchYouTubeVideoInfo(url)))

    controller.sendTo(message.channel, message.author)
      .catch(console.error)
  }
})

client.login()
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import { Client, MessageEmbed } from "discord.js";
import { ReactionController } from "discord.js-reaction-controller";
import { getBasicInfo } from "ytdl-core";
const client = new Client();
const fetchYouTubeVideoInfo = videoUrl => async () => {
    const { videoDetails } = await getBasicInfo(videoUrl);
    return new MessageEmbed()
        .setColor("RED")
        .setTitle(videoDetails.title)
        .setURL(videoDetails.video_url)
        .setImage(videoDetails.thumbnails[videoDetails.thumbnails.length - 1].url)
        .setTimestamp(Date.parse(videoDetails.publishDate))
        .setFooter("Uploaded on")
        .setAuthor(videoDetails.author.name, videoDetails.author.thumbnails[0].url, videoDetails.author.channel_url);
};
const videos = [
    "https://youtu.be/sWbD5q769Ms",
    "https://youtu.be/0-zJNiSvz8Q",
    "https://youtu.be/1x2izJEN9p0",
    "https://youtu.be/gNp4VNr44hg",
    "https://youtu.be/Vi_asBY5UX8",
    "https://youtu.be/plqoPcKQnyE",
    "https://youtu.be/308I91ljCWg"
];
client.on("message", message => {
    if (message.content.startsWith(">pagination")) {
        const controller = new ReactionController(client);
        controller
            .addReactionHandler("\uD83E\uDD14", (reaction) => {
            reaction.message.channel.send("thinking")
                .catch(console.error);
        });
        controller.addPages(videos.map(url => fetchYouTubeVideoInfo(url)));
        controller.sendTo(message.channel, message.author)
            .catch(console.error);
    }
});
client.login();
  • test.ts (5,36): Cannot find module 'discord.js-reaction-controller' or its corresponding type declarations.
  • test.ts (6,30): Cannot find module 'ytdl-core' or its corresponding type declarations.
  • test.ts (7,16): Expected 1 arguments, but got 0.
  • test.ts (8,31): Parameter 'videoUrl' implicitly has an 'any' type.
  • test.ts (32,50): Parameter 'reaction' implicitly has an 'any' type.
  • used message Event

npm i discord.js-reaction-controller
import * as discord from "discord.js";
npm;
i;
discord.js - reaction - controller;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.
  • test.ts (5,14): Cannot find name 'reaction'.
  • test.ts (5,25): Cannot find name 'controller'.

yarn add discord.js-reaction-controller
import * as discord from "discord.js";
yarn;
add;
discord.js - reaction - controller;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'add'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.
  • test.ts (5,14): Cannot find name 'reaction'.
  • test.ts (5,25): Cannot find name 'controller'.

nextPage
nextPage;
  • test.ts (2,1): Cannot find name 'nextPage'.

prevPage
prevPage;
  • test.ts (2,1): Cannot find name 'prevPage'.

sendTo
sendTo;
  • test.ts (2,1): Cannot find name 'sendTo'.

currentPage
currentPage;
  • test.ts (2,1): Cannot find name 'currentPage'.

send
send;
  • test.ts (2,1): Cannot find name 'send'.

0
0;

sendTo
sendTo;
  • test.ts (2,1): Cannot find name 'sendTo'.

sendTo
sendTo;
  • test.ts (2,1): Cannot find name 'sendTo'.

this.sendTo(message.channel, message.author)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
this.sendTo(message.channel, message.author);
  • test.ts (4,6): Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.

Promise<MessageEmbed>
Promise<MessageEmbed>();
  • test.ts (2,1): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?
  • test.ts (2,9): Cannot find name 'MessageEmbed'.

addPages
addPages;
  • test.ts (2,1): Cannot find name 'addPages'.

addPage
addPage;
  • test.ts (2,1): Cannot find name 'addPage'.

Promise<MessageEmbed>
Promise<MessageEmbed>();
  • test.ts (2,1): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?
  • test.ts (2,9): Cannot find name 'MessageEmbed'.

undefined
undefined;

addPage
addPage;
  • test.ts (2,1): Cannot find name 'addPage'.

addPages
addPages;
  • test.ts (2,1): Cannot find name 'addPages'.

Collection<number, MessageEmbed>
Collection<number, MessageEmbed>();
  • test.ts (2,1): Cannot find name 'Collection'.
  • test.ts (2,20): Cannot find name 'MessageEmbed'.

addReactionHandler
addReactionHandler;
  • test.ts (2,1): Cannot find name 'addReactionHandler'.

Collection<string, ReactionHandlerFunction>
Collection<string, ReactionHandlerFunction>();
  • test.ts (2,1): Cannot find name 'Collection'.
  • test.ts (2,20): Cannot find name 'ReactionHandlerFunction'.

Promise<Array<MessageReaction | undefined>>
Promise<Array<MessageReaction | undefined>>();
  • test.ts (2,1): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?
  • test.ts (2,15): Cannot find name 'MessageReaction'.

addPage
addPage;
  • test.ts (2,1): Cannot find name 'addPage'.

addPages
addPages;
  • test.ts (2,1): Cannot find name 'addPages'.

addReactionHandler(絵文字, (reaction, user) => { /* code */ })
addReactionHandler(絵文字, (reaction, user) => { });
  • test.ts (2,1): Cannot find name 'addReactionHandler'.
  • test.ts (2,20): Cannot find name '絵文字'.
  • test.ts (2,26): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (2,36): Parameter 'user' implicitly has an 'any' type.

reaction
reaction;
  • test.ts (2,1): Cannot find name 'reaction'.

user
declare var user: import("discord.js").User;
user;

管理者権限を持ったユーザーの一覧を返信するサンプル

管理者権限を持ったユーザーの一覧を返信するサンプル

client.on('message', async message => {
  // サーバー内ので'!permission'が送信されたとき
  if (message.content === '!permission' && message.guild) {
    // メッセージが送信されたサーバーにいる全てのメンバーを取得する
    const members = await message.guild.members.fetch()
    // 管理者権限を持ったメンバーのみを絞り込む
    const admins = members.filter(member => member.permissions.has('ADMINISTRATOR'))
    // 絞り込んだメンバーのタグを取得する
    const tags = admins.map(member => member.user.tag)
    // タグの配列を', 'でつなげて返信する
    message.reply(tags.join(', '))
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    // サーバー内ので'!permission'が送信されたとき
    if (message.content === "!permission" && message.guild) {
        // メッセージが送信されたサーバーにいる全てのメンバーを取得する
        const members = await message.guild.members.fetch();
        // 管理者権限を持ったメンバーのみを絞り込む
        const admins = members.filter(member => member.permissions.has("ADMINISTRATOR"));
        // 絞り込んだメンバーのタグを取得する
        const tags = admins.map(member => member.user.tag);
        // タグの配列を', 'でつなげて返信する
        message.reply(tags.join(", "));
    }
});
  • used message Event

!permission
!permission;
  • test.ts (2,2): Cannot find name 'permission'. Did you mean 'Permissions'?

12.5.[12]: BOTがリアクションしたリアクションに対して、他のユーザーがリアクションすると、MessageReaction#meがfalseになってしまう

12.5.[12]: BOTがリアクションしたリアクションに対して、他のユーザーがリアクションすると、MessageReaction#meがfalseになってしまう

const { Client, Intents } = require('discord.js');

const bot = new Client({
  ws: { intents: Intents.NON_PRIVILEGED },
  partials: ['USER', 'CHANNEL', 'GUILD_MEMBER', 'MESSAGE', 'REACTION']
});

bot.on('message', message => {
  message.react('🍎')
    .catch(console.error);
});

bot.on('messageReactionAdd', reaction => {
  reaction.fetch()
    .then(reaction => console.log(reaction.me))
    .catch(console.error);
});

bot.login('YOUR TOKEN')
  .catch(console.error);
import { Client, Intents } from "discord.js";
const bot = new Client({
    ws: { intents: Intents.NON_PRIVILEGED },
    partials: ["USER", "CHANNEL", "GUILD_MEMBER", "MESSAGE", "REACTION"]
});
bot.on("message", message => {
    message.react("\uD83C\uDF4E")
        .catch(console.error);
});
bot.on("messageReactionAdd", reaction => {
    reaction.fetch()
        .then(reaction => console.log(reaction.me))
        .catch(console.error);
});
bot.login("YOUR TOKEN")
    .catch(console.error);
  • test.ts (4,11): Type '{ intents: any; }' is not assignable to type 'WebSocketOptions'. Object literal may only specify known properties, and 'intents' does not exist in type 'WebSocketOptions'.
  • test.ts (4,28): Property 'NON_PRIVILEGED' does not exist on type 'typeof Intents'.
  • used message Event

Promiseを理解する

Promiseを理解する

p.then(
	x => Promise.resolve(onFinally()).then(() => x),
	err => Promise.resolve(onFinally()).then(() => {throw err;})
);
p.then(x => Promise.resolve(onFinally()).then(() => x), err => Promise.resolve(onFinally()).then(() => { throw err; }));
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,8): Parameter 'x' implicitly has an 'any' type.
  • test.ts (2,29): Cannot find name 'onFinally'.
  • test.ts (2,57): Parameter 'err' implicitly has an 'any' type.
  • test.ts (2,80): Cannot find name 'onFinally'.

new Promise((resolve,reject) => {
	 const results = [];
	 let remaining=0;
	 const wrapResolve = ([idx,result])=> {
	 	results[idx] = result;
	 	--remaining;
	 	if(remaining === 0){
	 		resolve(results);
	 	}
	 });
	 for (const entry of iterable){
	 	Promise.resolve(entry).then(result => wrapResolve([remaining,result]),reject);
	 	++remaining;
	 }
	 if(remaining === 0){
	 	resolve(results);
	 }
});
new Promise((resolve, reject) => {
    const results = [];
    let remaining = 0;
    const wrapResolve = ([idx, result]) => {
        results[idx] = result;
        --remaining;
        if (remaining === 0) {
            resolve(results);
        }
    };
});
for (const entry of iterable) {
    Promise.resolve(entry).then(result => wrapResolve([remaining, result]), reject);
    ++remaining;
}
if (remaining === 0) {
    resolve(results);
}
;
  • test.ts (3,11): Variable 'results' implicitly has type 'any[]' in some locations where its type cannot be determined.
  • test.ts (5,27): Binding element 'idx' implicitly has an 'any' type.
  • test.ts (5,32): Binding element 'result' implicitly has an 'any' type.
  • test.ts (9,21): Variable 'results' implicitly has an 'any[]' type.
  • test.ts (13,21): Cannot find name 'iterable'.
  • test.ts (14,43): Cannot find name 'wrapResolve'.
  • test.ts (14,56): Cannot find name 'remaining'.
  • test.ts (14,77): Cannot find name 'reject'.
  • test.ts (15,7): Cannot find name 'remaining'.
  • test.ts (17,5): Cannot find name 'remaining'.
  • test.ts (18,5): Cannot find name 'resolve'.
  • test.ts (18,13): Cannot find name 'results'.

new Promise((resolve,reject) => {
	for(const entry of iterable){
		Promise.resolve(entry).then(resolve,reject):
	}
})
new Promise((resolve, reject) => {
    for (const entry of iterable) {
        Promise.resolve(entry).then(resolve, reject);
    }
});
  • test.ts (3,25): Cannot find name 'iterable'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

catch
try { }
catch { }

finally
try { }
finally { }

then
then;
  • test.ts (2,1): Cannot find name 'then'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

p.then(f,r)
p.then(f, r);
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,8): Cannot find name 'f'.
  • test.ts (2,11): Cannot find name 'r'.

p.then(f,r)
p.then(f, r);
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,8): Cannot find name 'f'.
  • test.ts (2,11): Cannot find name 'r'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

thenable.then(resolve,reject)
thenable.then(resolve, reject);
  • test.ts (2,1): Cannot find name 'thenable'.
  • test.ts (2,15): Cannot find name 'resolve'.
  • test.ts (2,24): Cannot find name 'reject'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

p.then(f,r)
p.then(f, r);
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,8): Cannot find name 'f'.
  • test.ts (2,11): Cannot find name 'r'.

pending
pending;
  • test.ts (2,1): Cannot find name 'pending'.

fulfilled
fulfilled;
  • test.ts (2,1): Cannot find name 'fulfilled'.

rejected
rejected;
  • test.ts (2,1): Cannot find name 'rejected'.

resolve
resolve;
  • test.ts (2,1): Cannot find name 'resolve'.

reject
reject;
  • test.ts (2,1): Cannot find name 'reject'.

p.catch(r)
p.catch(r);
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,9): Cannot find name 'r'.

p.then(undefined,r)
p.then(undefined, r);
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,19): Cannot find name 'r'.

p.finally(onFinally)
p.finally(onFinally);
  • test.ts (2,1): Cannot find name 'p'.
  • test.ts (2,11): Cannot find name 'onFinally'.

Promise.resolve
Promise.resolve;

Promise.resolve(v)
Promise.resolve(v);
  • test.ts (2,17): Cannot find name 'v'.

new Promise(resolve=>resolve(v))
new Promise(resolve => resolve(v));
  • test.ts (2,32): Cannot find name 'v'.

Promise.reject(err)
Promise.reject(err);
  • test.ts (2,16): Cannot find name 'err'.

new Promise((_resolve,reject)=>reject(err))
new Promise((_resolve, reject) => reject(err));
  • test.ts (2,42): Cannot find name 'err'.

Promise.all(iterable)
Promise.all(iterable);
  • test.ts (2,13): Cannot find name 'iterable'.

Promise.race(iterable)
Promise.race(iterable);
  • test.ts (2,14): Cannot find name 'iterable'.

Promise.any(iterable)
Promise.any(iterable);
  • test.ts (2,13): Cannot find name 'iterable'.

Promise.all
Promise.all;

Promise.allSettled
Promise.allSettled;

RichEmbedを使って埋め込みを送信するサンプル

RichEmbedを使って埋め込みを送信するサンプル

 const Discord = require('discord.js')
 const client = new Discord.Client()
 
 client.on('message', message => {
   if (message.content === '!embed') {
     const embed = new Discord.RichEmbed()
       .setTitle('埋め込みのタイトル')
       .setURL('https://google.com')
       .addField('name', 'value')
       .setColor('RANDOM')
       .setTimestamp()
 
     message.channel.send(embed)
   }
 })
 
 client.login('token')
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", message => {
    if (message.content === "!embed") {
        const embed = new Discord.RichEmbed()
            .setTitle("\u57CB\u3081\u8FBC\u307F\u306E\u30BF\u30A4\u30C8\u30EB")
            .setURL("https://google.com")
            .addField("name", "value")
            .setColor("RANDOM")
            .setTimestamp();
        message.channel.send(embed);
    }
});
client.login("token");
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (6,35): Property 'RichEmbed' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.
  • used message Event

ローカルの画像を埋め込みで使用するサンプル

ローカルの画像を埋め込みで使用するサンプル

const buffer = //...
const embed = new Discord.MessageEmbed()
  .attachFiles([new Discord.MessageAttachment(buffer, "thumbnail.jpg")])
  .setThumbnail("attachment://thumbnail.jpg") 
import * as Discord from "discord.js";
const buffer = ; //...
const embed = new Discord.MessageEmbed()
    .attachFiles([new Discord.MessageAttachment(buffer, "thumbnail.jpg")])
    .setThumbnail("attachment://thumbnail.jpg");
  • test.ts (3,16): Expression expected.
  • test.ts (5,6): Property 'attachFiles' does not exist on type 'MessageEmbed'.

attachFiles
attachFiles;
  • test.ts (2,1): Cannot find name 'attachFiles'.

attachment://
attachment: ; //

attachment://<ファイル名>.<拡張子>
attachment: ; //<ファイル名>.<拡張子>

attachFiles
attachFiles;
  • test.ts (2,1): Cannot find name 'attachFiles'.

クラスを使って埋め込みを作る

クラスを使って埋め込みを作る

.setColor('#fff')
setColor("#fff");
  • test.ts (2,1): Cannot find name 'setColor'.

.setColor([255, 255, 255])
setColor([255, 255, 255]);
  • test.ts (2,1): Cannot find name 'setColor'.

.setColor(16777215)
setColor(16777215);
  • test.ts (2,1): Cannot find name 'setColor'.

.setColor('RED') // 赤
.setColor('BLUE') // 青
.setColor('RANDOM') // ランダム
setColor("RED") // 赤
    .setColor("BLUE") // 青
    .setColor("RANDOM"); // ランダム
  • test.ts (2,1): Cannot find name 'setColor'.

.addBlankField(inline?: boolean)
addBlankField(inline ?  : boolean);
  • test.ts (2,1): Cannot find name 'addBlankField'.
  • test.ts (2,15): Cannot find name 'inline'.
  • test.ts (2,25): Expression expected.
  • test.ts (2,27): 'boolean' only refers to a type, but is being used as a value here.

.addField(name, value, true)
addField(name, value, true);
  • test.ts (2,1): Cannot find name 'addField'.
  • test.ts (2,16): Cannot find name 'value'.

inline
inline;
  • test.ts (2,1): Cannot find name 'inline'.

inline
inline;
  • test.ts (2,1): Cannot find name 'inline'.

true
true;

.addField(name: string, value: string, inline?: boolean)
addField(name, string, value, string, inline ?  : boolean);
  • test.ts (2,1): Cannot find name 'addField'.
  • test.ts (2,16): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,24): Cannot find name 'value'.
  • test.ts (2,31): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,39): Cannot find name 'inline'.
  • test.ts (2,49): Expression expected.
  • test.ts (2,51): 'boolean' only refers to a type, but is being used as a value here.

inline
inline;
  • test.ts (2,1): Cannot find name 'inline'.

inline
inline;
  • test.ts (2,1): Cannot find name 'inline'.

true
true;

.addBlankField
addBlankField;
  • test.ts (2,1): Cannot find name 'addBlankField'.

.addFields(fieldData, fieldData)
addFields(fieldData, fieldData);
  • test.ts (2,1): Cannot find name 'addFields'.
  • test.ts (2,11): Cannot find name 'fieldData'.
  • test.ts (2,22): Cannot find name 'fieldData'.

.addFields([fieldData])
addFields([fieldData]);
  • test.ts (2,1): Cannot find name 'addFields'.
  • test.ts (2,12): Cannot find name 'fieldData'.

.addField
addField;
  • test.ts (2,1): Cannot find name 'addField'.

.addFields([{ name: 'name', value: 'value' }, { name: 'name', value: 'value' }])
addFields([{ name: "name", value: "value" }, { name: "name", value: "value" }]);
  • test.ts (2,1): Cannot find name 'addFields'.

.setAuthor(name: string, icon?: string, url?: string)
setAuthor(name, string, icon ?  : string, url ?  : string);
  • test.ts (2,1): Cannot find name 'setAuthor'.
  • test.ts (2,17): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,25): Cannot find name 'icon'.
  • test.ts (2,33): Expression expected.
  • test.ts (2,35): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,43): Cannot find name 'url'. Did you mean 'URL'?
  • test.ts (2,50): Expression expected.
  • test.ts (2,52): 'string' only refers to a type, but is being used as a value here.

icon
icon;
  • test.ts (2,1): Cannot find name 'icon'.

attachFiles
attachFiles;
  • test.ts (2,1): Cannot find name 'attachFiles'.

url
url;
  • test.ts (2,1): Cannot find name 'url'. Did you mean 'URL'?

name
name;

.setColor(color: ColorResolvable)
setColor(color, ColorResolvable);
  • test.ts (2,1): Cannot find name 'setColor'.
  • test.ts (2,10): Cannot find name 'color'.
  • test.ts (2,17): Cannot find name 'ColorResolvable'.

.setDescription(description: string)
setDescription(description, string);
  • test.ts (2,1): Cannot find name 'setDescription'.
  • test.ts (2,16): Cannot find name 'description'.
  • test.ts (2,29): 'string' only refers to a type, but is being used as a value here.

\n
n;
  • test.ts (2,1): Cannot find name 'n'.

.setFooter(text: string, icon?: string)
setFooter(text, string, icon ?  : string);
  • test.ts (2,1): Cannot find name 'setFooter'.
  • test.ts (2,11): Cannot find name 'text'. Did you mean 'Text'?
  • test.ts (2,17): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,25): Cannot find name 'icon'.
  • test.ts (2,33): Expression expected.
  • test.ts (2,35): 'string' only refers to a type, but is being used as a value here.

icon
icon;
  • test.ts (2,1): Cannot find name 'icon'.

attachFiles
attachFiles;
  • test.ts (2,1): Cannot find name 'attachFiles'.

.setImage(url: string)
setImage(url, string);
  • test.ts (2,1): Cannot find name 'setImage'.
  • test.ts (2,10): Cannot find name 'url'. Did you mean 'URL'?
  • test.ts (2,15): 'string' only refers to a type, but is being used as a value here.

url
url;
  • test.ts (2,1): Cannot find name 'url'. Did you mean 'URL'?

attachFiles
attachFiles;
  • test.ts (2,1): Cannot find name 'attachFiles'.

.setThumbnail(url: string)
setThumbnail(url, string);
  • test.ts (2,1): Cannot find name 'setThumbnail'.
  • test.ts (2,14): Cannot find name 'url'. Did you mean 'URL'?
  • test.ts (2,19): 'string' only refers to a type, but is being used as a value here.

url
url;
  • test.ts (2,1): Cannot find name 'url'. Did you mean 'URL'?

attachFiles
attachFiles;
  • test.ts (2,1): Cannot find name 'attachFiles'.

.setTimestamp(date?: Date | number)
setTimestamp(date ?  : Date | number);
  • test.ts (2,1): Cannot find name 'setTimestamp'.
  • test.ts (2,14): Cannot find name 'date'. Did you mean 'Date'?
  • test.ts (2,22): Expression expected.
  • test.ts (2,24): The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (2,31): 'number' only refers to a type, but is being used as a value here.

date
date;
  • test.ts (2,1): Cannot find name 'date'. Did you mean 'Date'?

.setTitle(title: string)
setTitle(title, string);
  • test.ts (2,1): Cannot find name 'setTitle'.
  • test.ts (2,10): Cannot find name 'title'.
  • test.ts (2,17): 'string' only refers to a type, but is being used as a value here.

.setURL(url: string)
setURL(url, string);
  • test.ts (2,1): Cannot find name 'setURL'.
  • test.ts (2,8): Cannot find name 'url'. Did you mean 'URL'?
  • test.ts (2,13): 'string' only refers to a type, but is being used as a value here.

.attachFiles(files: Array<(FileOptions|string|MessageAttachment)>)
attachFiles(files, Array<(FileOptions | string | MessageAttachment)>());
  • test.ts (2,1): Cannot find name 'attachFiles'.
  • test.ts (2,13): Cannot find name 'files'. Did you mean 'File'?
  • test.ts (2,27): Cannot find name 'FileOptions'.
  • test.ts (2,50): Cannot find name 'MessageAttachment'.

files
files;
  • test.ts (2,1): Cannot find name 'files'. Did you mean 'File'?

attachment://<ファイル名>.<拡張子>
attachment: ; //<ファイル名>.<拡張子>

送られた画像ファイルをオウム返しする

送られた画像ファイルをオウム返しする

const Discord = require('discord.js')
const client = new Discord.Client()

client.on('message', message => {
  const file = message.attachments.first()

  if (!file) return // 添付ファイルがなかったらスルー
  if (!file.height && !file.width) return // 画像じゃなかったらスルー

  return message.channel.send({
    embed: {
      image: {
        url: file.url
      }
    }
  })
})

client.login('Your token.')
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", message => {
    const file = message.attachments.first();
    if (!file)
        return; // 添付ファイルがなかったらスルー
    if (!file.height && !file.width)
        return; // 画像じゃなかったらスルー
    return message.channel.send({
        embed: {
            image: {
                url: file.url
            }
        }
    });
});
client.login("Your token.");
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (4,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise | undefined' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise | undefined' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message, TResult2 = never>(onfulfilled?: ((value: Message) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (11,9): Argument of type '{ embed: { image: { url: string; }; }; }' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Object literal may only specify known properties, and 'embed' does not exist in type 'MessagePayload | MessageOptions'.
  • used message Event

message.attachments.first()
declare var message: import("discord.js").Message;
message.attachments.first();

undefined
undefined;

if (!file) return
if (!file)
    return;
  • test.ts (2,6): Cannot find name 'file'. Did you mean 'File'?
  • test.ts (3,5): A 'return' statement can only be used within a function body.

if (!file.height && !file.width) return
if (!file.height && !file.width)
    return;
  • test.ts (2,6): Cannot find name 'file'. Did you mean 'File'?
  • test.ts (2,22): Cannot find name 'file'. Did you mean 'File'?
  • test.ts (3,5): A 'return' statement can only be used within a function body.

height
height;
  • test.ts (2,1): Cannot find name 'height'.

width
width;
  • test.ts (2,1): Cannot find name 'width'.

number
number;
  • test.ts (2,1): 'number' only refers to a type, but is being used as a value here.

height
height;
  • test.ts (2,1): Cannot find name 'height'.

width
width;
  • test.ts (2,1): Cannot find name 'width'.

null
null;

message.channel.send({ embed: { image: file.url } })
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.send({ embed: { image: file.url } });
  • test.ts (4,24): Argument of type '{ embed: { image: any; }; }' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Object literal may only specify known properties, and 'embed' does not exist in type 'MessagePayload | MessageOptions'.
  • test.ts (4,40): Cannot find name 'file'. Did you mean 'File'?

チャンネルのメッセージを AsyncIterator として扱うサンプル

チャンネルのメッセージを AsyncIterator として扱うサンプル

/**
 * @param {discord.TextChannel|discord.NewsChannel|discord.DMChannel} channel
 * @param {{after: string,limit?: number,before?: string}} options 
 */
async function* forwardChannelMessages(channel, options) {
  const fetchOptions = { ...options };
  delete fetchOptions["before"];
  let processedCount = 0;
  while (true) {
    const limit = Math.min(100, (options.limit ?? Infinity) - processedCount);
    fetchOptions.limit = limit;
    const messages = (await channel.messages.fetch(fetchOptions))
      .sort((a, b) => BigInt(a.id) < BigInt(b.id) ? -1 : 1)
      .filter(e => options.before ? BigInt(e.id) < BigInt(options.before) : true);
    processedCount += messages.size;
    fetchOptions.after = messages.last().id;
    yield* messages.values();
    if (messages.size < limit) {
      return;
    }
  }
}
/**
 * @param {discord.TextChannel|discord.NewsChannel|discord.DMChannel} channel
 * @param {{after?: string,limit?: number,before?: string}?} options 
 */
async function* backwardChannelMessages(channel, options = { limit: 100 }) {
  const fetchOptions = { ...options };
  delete fetchOptions["after"];
  let processedCount = 0;
  while (true) {
    const limit = Math.min(100, (options.limit ?? Infinity) - processedCount);
    fetchOptions.limit = limit;
    const messages = (await channel.messages.fetch(fetchOptions))
      .sort((a, b) => BigInt(a.id) > BigInt(b.id) ? -1 : 1)
      .filter(e => options.after ? BigInt(e.id) > BigInt(options.after) : true);
    processedCount += messages.size;
    yield* messages.values();
    fetchOptions.before = messages.last().id;
    if (messages.size < limit) {
      return;
    }
  }
}

exports.forwardChannelMessages = forwardChannelMessages;
exports.backwardChannelMessages = backwardChannelMessages;
/**
 * @param {discord.TextChannel|discord.NewsChannel|discord.DMChannel} channel
 * @param {{after: string,limit?: number,before?: string}} options
 */
async function* forwardChannelMessages(channel, options) {
    const fetchOptions = { ...options };
    delete fetchOptions["before"];
    let processedCount = 0;
    while (true) {
        const limit = Math.min(100, (options.limit ?? Infinity) - processedCount);
        fetchOptions.limit = limit;
        const messages = (await channel.messages.fetch(fetchOptions))
            .sort((a, b) => BigInt(a.id) < BigInt(b.id) ? -1 : 1)
            .filter(e => options.before ? BigInt(e.id) < BigInt(options.before) : true);
        processedCount += messages.size;
        fetchOptions.after = messages.last().id;
        yield* messages.values();
        if (messages.size < limit) {
            return;
        }
    }
}
/**
 * @param {discord.TextChannel|discord.NewsChannel|discord.DMChannel} channel
 * @param {{after?: string,limit?: number,before?: string}?} options
 */
async function* backwardChannelMessages(channel, options = { limit: 100 }) {
    const fetchOptions = { ...options };
    delete fetchOptions["after"];
    let processedCount = 0;
    while (true) {
        const limit = Math.min(100, (options.limit ?? Infinity) - processedCount);
        fetchOptions.limit = limit;
        const messages = (await channel.messages.fetch(fetchOptions))
            .sort((a, b) => BigInt(a.id) > BigInt(b.id) ? -1 : 1)
            .filter(e => options.after ? BigInt(e.id) > BigInt(options.after) : true);
        processedCount += messages.size;
        yield* messages.values();
        fetchOptions.before = messages.last().id;
        if (messages.size < limit) {
            return;
        }
    }
}
exports.forwardChannelMessages = forwardChannelMessages;
exports.backwardChannelMessages = backwardChannelMessages;
  • messageiterator.ts (6,40): Parameter 'channel' implicitly has an 'any' type.
  • messageiterator.ts (6,49): Parameter 'options' implicitly has an 'any' type.
  • messageiterator.ts (14,20): Parameter 'a' implicitly has an 'any' type.
  • messageiterator.ts (14,23): Parameter 'b' implicitly has an 'any' type.
  • messageiterator.ts (15,21): Parameter 'e' implicitly has an 'any' type.
  • messageiterator.ts (28,41): Parameter 'channel' implicitly has an 'any' type.
  • messageiterator.ts (30,12): Element implicitly has an 'any' type because expression of type '"after"' can't be used to index type '{ limit: number; }'. Property 'after' does not exist on type '{ limit: number; }'.
  • messageiterator.ts (36,20): Parameter 'a' implicitly has an 'any' type.
  • messageiterator.ts (36,23): Parameter 'b' implicitly has an 'any' type.
  • messageiterator.ts (37,21): Parameter 'e' implicitly has an 'any' type.
  • messageiterator.ts (37,34): Property 'after' does not exist on type '{ limit: number; }'.
  • messageiterator.ts (37,72): Property 'after' does not exist on type '{ limit: number; }'.
  • messageiterator.ts (40,22): Property 'before' does not exist on type '{ limit: number; }'.

const discord = require("discord.js");

/**
 * 
 * @param {discord.TextChannel|discord.NewsChannel|discord.DMChannel} channel 
 * @param {number} startTime unix time(ms)
 * @param {number} endTime unix time(ms)
 * @returns number of messages in channel
 */
async function getMessageCountInRange(channel, startTime, endTime) {
  let cnt = 0;
  for await (const message of forwardChannelMessages(channel, { after: discord.SnowflakeUtil.generate(startTime) })) {
    if (message.createdTimestamp > endTime) {
      return cnt;
    }
    ++cnt;
  }
  return cnt;
}
import * as discord from "discord.js";
/**
 *
 * @param {discord.TextChannel|discord.NewsChannel|discord.DMChannel} channel
 * @param {number} startTime unix time(ms)
 * @param {number} endTime unix time(ms)
 * @returns number of messages in channel
 */
async function getMessageCountInRange(channel, startTime, endTime) {
    let cnt = 0;
    for await (const message of forwardChannelMessages(channel, { after: discord.SnowflakeUtil.generate(startTime) })) {
        if (message.createdTimestamp > endTime) {
            return cnt;
        }
        ++cnt;
    }
    return cnt;
}
  • test.ts (10,39): Parameter 'channel' implicitly has an 'any' type.
  • test.ts (10,48): Parameter 'startTime' implicitly has an 'any' type.
  • test.ts (10,59): Parameter 'endTime' implicitly has an 'any' type.
  • test.ts (12,33): Cannot find name 'forwardChannelMessages'.

async function*
async function* ();
  • test.ts (2,16): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (2,17): Identifier expected.

yield*
yield * ;
  • test.ts (2,1): Cannot find name 'yield'.
  • test.ts (2,9): Expression expected.

サーバーに居るツールボットの使い方

サーバーに居るツールボットの使い方

logs = []
console.log = log => logs.push(log)

// ここに処理を書く
console.log('Hello world!')

logs
logs = [];
console.log = log => logs.push(log);
// ここに処理を書く
console.log("Hello world!");
logs;
  • test.ts (2,1): Cannot find name 'logs'.
  • test.ts (3,22): Cannot find name 'logs'. Did you mean 'log'?
  • test.ts (6,1): Cannot find name 'logs'.

https://github.com/InkoHX/HARZ/blob/master/heroku.yml#L1
https: ; //github.com/InkoHX/HARZ/blob/master/heroku.yml#L1

@HARZ#4409 docs <検索ワード> [--private|-p] [(--src|-s)=<json url>] [--force|-f]
#;
4409;
docs < 検索ワード > [--private | -p][(--src | -s) = <json>url > ][--force | -f];
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.
  • test.ts (4,1): Cannot find name 'docs'.
  • test.ts (4,8): Cannot find name '検索ワード'.
  • test.ts (4,19): Cannot find name 'private'.
  • test.ts (4,30): Cannot find name 'p'.
  • test.ts (4,33): The left-hand side of an assignment expression must be a variable or a property access.
  • test.ts (4,33): Type 'boolean' cannot be used as an index type.
  • test.ts (4,36): Cannot find name 'src'.
  • test.ts (4,43): Cannot find name 's'.
  • test.ts (4,49): Cannot find name 'json'.
  • test.ts (4,54): Cannot find name 'url'. Did you mean 'URL'?
  • test.ts (4,60): Expression expected.
  • test.ts (4,64): Cannot find name 'force'.
  • test.ts (4,73): Cannot find name 'f'.

--private
--private;
  • test.ts (2,3): Identifier expected. 'private' is a reserved word in strict mode.
  • test.ts (2,3): Cannot find name 'private'.

-p
-p;
  • test.ts (2,2): Cannot find name 'p'.

@HARZ#4409 docs Client --private
import { Client } from "discord.js";
#;
4409;
docs;
Client--;
private;
  • test.ts (3,1): Cannot find name '#'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.
  • test.ts (3,2): Invalid character.
  • test.ts (5,1): Cannot find name 'docs'.
  • test.ts (6,1): Cannot assign to 'Client' because it is an import.
  • test.ts (7,1): Cannot find name 'private'.

(--src|-s)=<JSON URL>
(--src | -s) = <JSON>URL > ;
  • test.ts (2,1): The left-hand side of an assignment expression must be a variable or a property access.
  • test.ts (2,4): Cannot find name 'src'.
  • test.ts (2,11): Cannot find name 's'.
  • test.ts (2,16): Conversion of type '{ new (url: string, base?: string | URL | undefined): URL; prototype: URL; createObjectURL(object: any): string; revokeObjectURL(url: string): void; }' to type 'JSON' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ new (url: string, base?: string | URL | undefined): URL; prototype: URL; createObjectURL(object: any): string; revokeObjectURL(url: string): void; }' is missing the following properties from type 'JSON': parse, stringify, [Symbol.toStringTag]
  • test.ts (2,28): Expression expected.

@HARZ#4409 docs map -s=https://raw.githubusercontent.com/discordjs/collection/docs/master.json
#;
4409;
docs;
map - s;
https: ; //raw.githubusercontent.com/discordjs/collection/docs/master.json
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.
  • test.ts (4,1): Cannot find name 'docs'.
  • test.ts (5,1): Cannot find name 'map'. Did you mean 'Map'?
  • test.ts (5,7): Cannot find name 's'.

--force
--force;
  • test.ts (2,3): Cannot find name 'force'.

-f
-f;
  • test.ts (2,2): Cannot find name 'f'.

@HARZ#4409 docs Client --force
import { Client } from "discord.js";
#;
4409;
docs;
Client--;
force;
  • test.ts (3,1): Cannot find name '#'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.
  • test.ts (3,2): Invalid character.
  • test.ts (5,1): Cannot find name 'docs'.
  • test.ts (6,1): Cannot assign to 'Client' because it is an import.
  • test.ts (7,1): Cannot find name 'force'.

@HARZ#4409 lint [対象のメッセージID|対象のメッセージURL] [--force|-f]
#;
4409;
lint[対象のメッセージID | 対象のメッセージURL][--force | -f];
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.
  • test.ts (4,1): Cannot find name 'lint'.
  • test.ts (4,6): Cannot find name '対象のメッセージID'.
  • test.ts (4,19): Cannot find name '対象のメッセージURL'.
  • test.ts (4,34): Cannot find name 'force'.
  • test.ts (4,43): Cannot find name 'f'.

JavaScript
JavaScript;
  • test.ts (2,1): Cannot find name 'JavaScript'.

TypeScript
TypeScript;
  • test.ts (2,1): Cannot find name 'TypeScript'.

--force
--force;
  • test.ts (2,3): Cannot find name 'force'.

-f
-f;
  • test.ts (2,2): Cannot find name 'f'.

JavaScript or TypeScript
JavaScript;
or;
TypeScript;
  • test.ts (2,1): Cannot find name 'JavaScript'.
  • test.ts (3,1): Cannot find name 'or'.
  • test.ts (4,1): Cannot find name 'TypeScript'.

JavaScript or TypeScript
JavaScript;
or;
TypeScript;
  • test.ts (2,1): Cannot find name 'JavaScript'.
  • test.ts (3,1): Cannot find name 'or'.
  • test.ts (4,1): Cannot find name 'TypeScript'.

@HARZ#4409 hl [対象のメッセージID|対象のメッセージURL]
#;
4409;
hl[対象のメッセージID | 対象のメッセージURL];
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.
  • test.ts (4,1): Cannot find name 'hl'.
  • test.ts (4,4): Cannot find name '対象のメッセージID'.
  • test.ts (4,17): Cannot find name '対象のメッセージURL'.

JavaScript
JavaScript;
  • test.ts (2,1): Cannot find name 'JavaScript'.

TypeScript
TypeScript;
  • test.ts (2,1): Cannot find name 'TypeScript'.

JSON
JSON;

@HARZ#4409 scrapbox [(--project|-p)="Project Name"] [(--sort|-s)=SortTypes] <クエリ>
#;
4409;
scrapbox[(--project | -p) = "Project Name"][(--sort | -s) = SortTypes]<クエリ>();
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.
  • test.ts (4,1): Cannot find name 'scrapbox'.
  • test.ts (4,10): The left-hand side of an assignment expression must be a variable or a property access.
  • test.ts (4,13): Cannot find name 'project'.
  • test.ts (4,24): Cannot find name 'p'.
  • test.ts (4,45): The left-hand side of an assignment expression must be a variable or a property access.
  • test.ts (4,48): Cannot find name 'sort'.
  • test.ts (4,56): Cannot find name 's'.
  • test.ts (4,61): Cannot find name 'SortTypes'.
  • test.ts (4,72): Cannot find name 'クエリ'.

--project
--project;
  • test.ts (2,3): Cannot find name 'project'.

-p
-p;
  • test.ts (2,2): Cannot find name 'p'.

discordjs-japan
discordjs - japan;
  • test.ts (2,1): Cannot find name 'discordjs'.
  • test.ts (2,13): Cannot find name 'japan'.

--sort
--sort;
  • test.ts (2,3): Cannot find name 'sort'.

-s
-s;
  • test.ts (2,2): Cannot find name 's'.

updated
updated;
  • test.ts (2,1): Cannot find name 'updated'.

pageRank
pageRank;
  • test.ts (2,1): Cannot find name 'pageRank'.

setInterval
setInterval;

setTimeout
setTimeout;

process
process;

require
require;

console
console;

js
js;
  • test.ts (2,1): Cannot find name 'js'.

javascript
javascript;
  • test.ts (2,1): Cannot find name 'javascript'.

js
js;
  • test.ts (2,1): Cannot find name 'js'.

javascript
javascript;
  • test.ts (2,1): Cannot find name 'javascript'.

規模がでかくなってきてパフォーマンスが落ちてきたときに少し改善する

規模がでかくなってきてパフォーマンスが落ちてきたときに少し改善する

const { Client } = require('discord.js')
const bot = new Client({
  disabledEvents: ['TYPING_START']
})

bot.login()
import { Client } from "discord.js";
const bot = new Client({
    disabledEvents: ["TYPING_START"]
});
bot.login();
  • index.ts (4,5): Argument of type '{ disabledEvents: string[]; }' is not assignable to parameter of type 'ClientOptions'. Object literal may only specify known properties, and 'disabledEvents' does not exist in type 'ClientOptions'.

disabledEvents
disabledEvents;
  • test.ts (2,1): Cannot find name 'disabledEvents'.

TYPING_START
TYPING_START;
  • test.ts (2,1): Cannot find name 'TYPING_START'.

ユーザーをメンションする

ユーザーをメンションする

client.users.fetch('ユーザーID')
	.then(user => message.channel.send(`Hey! ${user}`))
	.catch(console.error)
declare var client: import("discord.js").Client;
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.users.fetch("\u30E6\u30FC\u30B6\u30FCID")
    .then(user => message.channel.send(`Hey! ${user}`))
    .catch(console.error);
  • test.ts (5,20): Argument of type '"ユーザーID"' is not assignable to parameter of type '${bigint}'.

<@ユーザーID>
<>;
    > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,2): Expression expected.
  • test.ts (3,4): Expression expected.

<@!ユーザーID>
<>;
ユーザーID > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,1): Cannot find name 'ユーザーID'.
  • test.ts (3,10): Expression expected.

message.channel.send(user.toString())
  • Error: Debug Failure. Unhandled SyntaxKind: Unknown. at pipelineEmitWithHintWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104814:22) at pipelineEmitWithHint (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104364:17) at pipelineEmitWithComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107818:13) at pipelineEmit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104304:13) at emit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104277:13) at emitNodeList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107065:25) at emitList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106952:13) at emitSourceFileWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106683:13) at emitBodyWithDetachedComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107934:17) at emitSourceFile (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106604:21)

message.reply('返信内容')
declare var message: import("discord.js").Message;
message.reply("\u8FD4\u4FE1\u5185\u5BB9");

テキストチャンネルをメンションする

テキストチャンネルをメンションする

const channel = message.guild.channels.resolve('テキストチャンネルのID')
message.channel.send(`続きはここで: ${channel}`)
	.catch(console.error)
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const channel = message.guild.channels.resolve("\u30C6\u30AD\u30B9\u30C8\u30C1\u30E3\u30F3\u30CD\u30EB\u306EID");
message.channel.send(`続きはここで: ${channel}`)
    .catch(console.error);
  • test.ts (3,13): Duplicate identifier 'channel'.
  • test.ts (5,7): Duplicate identifier 'channel'.
  • test.ts (5,17): Object is possibly 'null'.
  • test.ts (5,48): No overload matches this call. Overload 1 of 2, '(resolvable: GuildChannel | ThreadChannel): GuildChannel | ThreadChannel', gave the following error. Argument of type 'string' is not assignable to parameter of type 'GuildChannel | ThreadChannel'. Overload 2 of 2, '(resolvable: GuildChannelResolvable): GuildChannel | ThreadChannel | null', gave the following error. Argument of type '"テキストチャンネルのID"' is not assignable to parameter of type 'GuildChannelResolvable'.

<#テキストチャンネルのID>
<#テキストチャンネルのID>;
  • test.ts (2,2): Cannot find name '#テキストチャンネルのID'.
  • test.ts (2,16): Expression expected.

message.channel.send(channel.toString())
  • Error: Debug Failure. Unhandled SyntaxKind: Unknown. at pipelineEmitWithHintWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104814:22) at pipelineEmitWithHint (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104364:17) at pipelineEmitWithComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107818:13) at pipelineEmit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104304:13) at emit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104277:13) at emitNodeList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107065:25) at emitList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106952:13) at emitSourceFileWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106683:13) at emitBodyWithDetachedComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107934:17) at emitSourceFile (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106604:21)

resolve
resolve;
  • test.ts (2,1): Cannot find name 'resolve'.

#チャンネル名
#チャンネル名;
  • test.ts (2,1): Cannot find name '#チャンネル名'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.

役職をメンションする

役職をメンションする

message.guild.roles.fetch('役職のID')
	.then(role => message.channel.send(`Call ${role}`))
	.catch(console.error)
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.guild.roles.fetch("\u5F79\u8077\u306EID")
    .then(role => message.channel.send(`Call ${role}`))
    .catch(console.error);
  • test.ts (5,1): Object is possibly 'null'.
  • test.ts (5,27): No overload matches this call. Overload 1 of 2, '(id: ${bigint}, options?: BaseFetchOptions | undefined): Promise<Role | null>', gave the following error. Argument of type '"役職のID"' is not assignable to parameter of type '${bigint}'. Overload 2 of 2, '(id?: undefined, options?: BaseFetchOptions | undefined): Promise<Collection<${bigint}, Role>>', gave the following error. Argument of type '"役職のID"' is not assignable to parameter of type 'undefined'.

<@&役職のID>
<>;
    & 役職のID > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,2): Expression expected.
  • test.ts (3,4): Cannot find name '役職のID'.
  • test.ts (3,4): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (3,12): Expression expected.

<@&役職のID>
<>;
    & 役職のID > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,2): Expression expected.
  • test.ts (3,4): Cannot find name '役職のID'.
  • test.ts (3,4): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (3,12): Expression expected.

message.channel.send(role.toString())
  • Error: Debug Failure. Unhandled SyntaxKind: Unknown. at pipelineEmitWithHintWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104814:22) at pipelineEmitWithHint (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104364:17) at pipelineEmitWithComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107818:13) at pipelineEmit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104304:13) at emit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104277:13) at emitNodeList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107065:25) at emitList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106952:13) at emitSourceFileWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106683:13) at emitBodyWithDetachedComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107934:17) at emitSourceFile (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106604:21)

Aiueokashi

Aiueokashi

/*
LineId --- 24文字のstring

interface commit.changes {
  _update: LineId; // 更新する行
  lines: {
    origText: string; // 元のテキスト
    text: string;     // 新しいテキスト
  };
} | {
  _insert: LineId | "_end"; // 行を入れる場所の後ろ側の行
  lines: {
    id: LineId;   // 入れる行
    text: string; // 入れるテキスト
  };
} | {
  _delete: LineId; // 消す行
  lines: {
    origText: string; // 消す前にあったテキスト
  };
} | {
  title: string;   // 新しいタイトル
  titleLc: string; // 新しいタイトル(小文字)
} | {
  descriptions: string[]; // 新しいページ説明文
} | {
  links: string[]; // 新しいリンク
}
*/
const CHANGE_TYPE_INSERT = '_insert';
const CHANGE_TYPE_UPDATE = '_update';
const CHANGE_TYPE_DELETE = '_delete';
const CHANGE_TYPE_TITLE = 'title';
const CHANGE_TYPE_DESCRIPTIONS = 'descriptions';
const CHANGE_TYPE_LINKS = 'links';

const getHrefInfo = href => {
  const a = document.createElement('a');
  a.href = href;
  const [__ignore, project, page] = a.pathname.split('/')
  return {
    host: a.host,
    project,
    page,
  };
};

const fetchCommitDataOfHref = href => {
  const { host, project, page } = getHrefInfo(href);
  return fetch(`https://${host}/api/pages/${project}/${page}`)
    .then(res => res.json())
    .then(pageData => {
      const pageId = pageData.id;
      const commitUrl = `https://${host}/api/commits/${project}/${pageId}`;
      return fetch(commitUrl);
    })
    .then(res => res.json());
};

const makeChangeInfo = rawChange => {
  const change = {};

  if (rawChange._insert) {
    change.type = CHANGE_TYPE_INSERT;
    change.targetId = rawChange[change.type];
  } else if (rawChange._update) {
    change.type = CHANGE_TYPE_UPDATE;
    change.targetId = rawChange[change.type];
  } else if (rawChange._delete) {
    change.type = CHANGE_TYPE_DELETE;
    change.targetId = rawChange[change.type];
  } else if (rawChange.title) {
    change.type = CHANGE_TYPE_TITLE;
  } else if (rawChange.descriptions) {
    change.type = CHANGE_TYPE_DESCRIPTIONS;
  } else if (rawChange.links) {
    change.type = CHANGE_TYPE_LINKS;
  } else {
    console.info('unknown type. raw commit change: ', rawChange);
  }

  if (rawChange.lines) {
    change.lines = rawChange.lines;
  }
  return change;
};

const onHistorySliderClick = () => {
  fetchCommitDataOfHref(location.href)
  .then(commitData => {
    // returns all changes of all commits
    return commitData.commits.reduce((all, rawCommit) => {
      return [
        ...all,
        ...rawCommit.changes.map(makeChangeInfo),
      ];
    }, []);
  })
  .then(changes => {
    // 行の文字列のコレクション
    // - すべての履歴それぞれのtextを順に入れておく
    const texts = [];

    // 行ごとの履歴情報を配列にする
    // [{ id: LindeId, updatedAt: [idx1, ... ], deletedAt?: idx }]
    // - 行ごとに id, 更新された履歴連番, 削除された履歴連番を持つ
    // - 出現した行すべてが入るので, ページの行とは対応していないことに注意

    // 1個目の履歴
    let initHistory;
    const [initChange, ...restChanges] = changes;
    console.debug({ initChange, restChanges, changes });

    // 最初のイベントは _insert か _update のはずなのでとにかく履歴をつくる
    if (initChange.type === CHANGE_TYPE_INSERT) {
      // タイトルの次の行に書くとき insert
      // TODO: このときタイトルは title という change に入るので取りこぼしている
      texts.push(initChange.lines.text);
      initHistory = {
        id: initChange.lines.id,
        updatedAt: [0],
      };
    } else if (initChange.type === CHANGE_TYPE_UPDATE) {
      // タイトル行に書くとき
      texts.push(initChange.lines.text);
      initHistory = {
        id: initChange.targetId,
        updatedAt: [0],
      };
    } else {
      console.log('init change neither _insert nor _update');
    }

    const allHistory = restChanges.reduce((history, change, i) => {
      console.debug({ text: change.lines && change.lines.text, texts, history });

      const lineIndex = history.findIndex(h => h.id === change.targetId);

      switch (change.type) {
        case CHANGE_TYPE_INSERT:
          texts.push(change.lines.text);

          const line = {
            id: change.lines.id,
            updatedAt: [texts.length - 1],
          };

          if (change.targetId === '_end') {
            // 最後の行なら単に1行足す
            history.push(line);
          } else {
            // 最後の行じゃないなら入れるべき場所に差し込む
            if (lineIndex === -1) {
              console.info(`_insert: line index not found. commit change (${i}):`, change);
              return history;
            }
            history.splice(lineIndex, 0, line);
          }
          break;
        case CHANGE_TYPE_UPDATE:
          texts.push(change.lines.text);

          if (lineIndex === -1) {
            console.info(`_update: line index not found. commit change (${i}):`, change);
            return history;
          }
          history[lineIndex].updatedAt.push(texts.length - 1);
          break;
        case CHANGE_TYPE_DELETE:
          texts.push(null);

          if (lineIndex === -1) {
            console.info(`_delete: line index not found. commit change (${i}):`, change);
            return history;
          }
          history[lineIndex].deletedAt = texts.length - 1;
          break;
      }
      return history;
    }, [initHistory]);

    console.debug({ allHistory });
    return { texts, allHistory };
  })
  .then(({ texts, allHistory }) => {
    // 履歴連番から履歴を得る
    // - その時点で存在した行の履歴
    const getHistoryByTime = time => {
      return allHistory.reduce((all, history) => {
        // これまでの更新のうち最新の履歴連番
        const updatedAt = history.updatedAt.filter(u => u <= time).pop();
        // もう出現しているかどうか
        const appeared = updatedAt !== undefined;
        // もう消えてるかどうか
        const deleted = history.deletedAt !== undefined && history.deletedAt <= time;
        // まだ出現していない or もう消えてるなら, その行は返さない
        if (!appeared || deleted) {
          return all;
        }
        // 出現している(かつ消えてない)ならその行を返す
        return [...all, { id: history.id, textIndex: updatedAt }];
      }, []);
    };
    // 履歴連番に対応するテキストを得る
    const getTextByTime = time => getHistoryByTime(time).map(history => texts[history.textIndex]).join('\n');

    // 操作系を表示してスライダーで操作できるようにする
    // - 指定された履歴連番からテキストを得て表示する

    const historyContainer = document.createElement('div');
    historyContainer.classList.add('history-container');
    Object.entries({
      'background-color': '#555555',
      position: 'fixed',
      'z-index': '90000',
      top: '5px',
      left: '5px',
      width: 'calc( 100% - 10px )',
      'max-height': '100%',
      border: '3px solid #22cc77',
      overflow: 'scroll',
    }).forEach(([key, value]) => historyContainer.style.setProperty(key, value));
    document.querySelector('body').appendChild(historyContainer);

    const historyCloseButton = document.createElement('button');
    historyCloseButton.classList.add('history-close-button');
    Object.entries({
      'font-size': '30px',
      'line-height': '1em',
      padding: '0',
      position: 'fixed',
      'z-index': '90001',
      top: '10px',
      right: '10px',
      width: '30px',
      height: '30px',
    }).forEach(([key, value]) => historyCloseButton.style.setProperty(key, value));
    historyContainer.appendChild(historyCloseButton);
    historyCloseButton.insertAdjacentText('beforeend', '×');

    const historyBackground = document.createElement('div');
    historyBackground.classList.add('history-background');
    Object.entries({
      position: 'fixed',
      'z-index': '89999',
      top: '0',
      right: '0',
      width: '100%',
      height: '100%',
      'background-color': 'rgba(255, 255, 255, 0.4)',
    }).forEach(([key, value]) => historyBackground.style.setProperty(key, value));
    document.querySelector('body').appendChild(historyBackground);

    const historyPre = document.createElement('pre');
    historyPre.classList.add('history-pre');
    Object.entries({
      width: '100%',
      'max-height': '100%',
    }).forEach(([key, value]) => historyPre.style.setProperty(key, value));
    historyPre.insertAdjacentHTML('beforeend', getTextByTime(texts.length));
    historyContainer.appendChild(historyPre);

    const historySlider = document.createElement('input');
    historySlider.classList.add('history-slider');
    Object.entries({
      position: 'fixed',
      'z-index': '99999',
      top: '10px',
      width: '90%',
    }).forEach(([key, value]) => historySlider.style.setProperty(key, value));
    historySlider.type = 'range';
    historySlider.min = '0';
    historySlider.max = `${texts.length}`;
    historySlider.value = `${texts.length}`;
    historySlider.step = 1;
    historyContainer.appendChild(historySlider);

    const removeHistoryContainer = () => {
      historyContainer.parentNode.removeChild(historyContainer);
      historyBackground.parentNode.removeChild(historyBackground);
    };
    historyCloseButton.addEventListener('click', removeHistoryContainer);
    historyBackground.addEventListener('click', removeHistoryContainer);
    const updateHistory = e => {
      const time = parseInt(e.target.value, 10);
      historyPre.innerHTML = getTextByTime(time);
      console.debug({ time, html: historyPre.innerHTML });
    };
    historySlider.addEventListener('input', updateHistory);
    historySlider.addEventListener('change', updateHistory);
  });
};

scrapbox.PageMenu.addMenu({
  title: '履歴スライダー',
  image: 'https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png',
  onClick: onHistorySliderClick,
});
/*
LineId --- 24文字のstring

interface commit.changes {
  _update: LineId; // 更新する行
  lines: {
    origText: string; // 元のテキスト
    text: string;     // 新しいテキスト
  };
} | {
  _insert: LineId | "_end"; // 行を入れる場所の後ろ側の行
  lines: {
    id: LineId;   // 入れる行
    text: string; // 入れるテキスト
  };
} | {
  _delete: LineId; // 消す行
  lines: {
    origText: string; // 消す前にあったテキスト
  };
} | {
  title: string;   // 新しいタイトル
  titleLc: string; // 新しいタイトル(小文字)
} | {
  descriptions: string[]; // 新しいページ説明文
} | {
  links: string[]; // 新しいリンク
}
*/
const CHANGE_TYPE_INSERT = "_insert";
const CHANGE_TYPE_UPDATE = "_update";
const CHANGE_TYPE_DELETE = "_delete";
const CHANGE_TYPE_TITLE = "title";
const CHANGE_TYPE_DESCRIPTIONS = "descriptions";
const CHANGE_TYPE_LINKS = "links";
const getHrefInfo = href => {
    const a = document.createElement("a");
    a.href = href;
    const [__ignore, project, page] = a.pathname.split("/");
    return {
        host: a.host,
        project,
        page,
    };
};
const fetchCommitDataOfHref = href => {
    const { host, project, page } = getHrefInfo(href);
    return fetch(`https://${host}/api/pages/${project}/${page}`)
        .then(res => res.json())
        .then(pageData => {
        const pageId = pageData.id;
        const commitUrl = `https://${host}/api/commits/${project}/${pageId}`;
        return fetch(commitUrl);
    })
        .then(res => res.json());
};
const makeChangeInfo = rawChange => {
    const change = {};
    if (rawChange._insert) {
        change.type = CHANGE_TYPE_INSERT;
        change.targetId = rawChange[change.type];
    }
    else if (rawChange._update) {
        change.type = CHANGE_TYPE_UPDATE;
        change.targetId = rawChange[change.type];
    }
    else if (rawChange._delete) {
        change.type = CHANGE_TYPE_DELETE;
        change.targetId = rawChange[change.type];
    }
    else if (rawChange.title) {
        change.type = CHANGE_TYPE_TITLE;
    }
    else if (rawChange.descriptions) {
        change.type = CHANGE_TYPE_DESCRIPTIONS;
    }
    else if (rawChange.links) {
        change.type = CHANGE_TYPE_LINKS;
    }
    else {
        console.info("unknown type. raw commit change: ", rawChange);
    }
    if (rawChange.lines) {
        change.lines = rawChange.lines;
    }
    return change;
};
const onHistorySliderClick = () => {
    fetchCommitDataOfHref(location.href)
        .then(commitData => {
        // returns all changes of all commits
        return commitData.commits.reduce((all, rawCommit) => {
            return [
                ...all,
                ...rawCommit.changes.map(makeChangeInfo),
            ];
        }, []);
    })
        .then(changes => {
        // 行の文字列のコレクション
        // - すべての履歴それぞれのtextを順に入れておく
        const texts = [];
        // 行ごとの履歴情報を配列にする
        // [{ id: LindeId, updatedAt: [idx1, ... ], deletedAt?: idx }]
        // - 行ごとに id, 更新された履歴連番, 削除された履歴連番を持つ
        // - 出現した行すべてが入るので, ページの行とは対応していないことに注意
        // 1個目の履歴
        let initHistory;
        const [initChange, ...restChanges] = changes;
        console.debug({ initChange, restChanges, changes });
        // 最初のイベントは _insert か _update のはずなのでとにかく履歴をつくる
        if (initChange.type === CHANGE_TYPE_INSERT) {
            // タイトルの次の行に書くとき insert
            // TODO: このときタイトルは title という change に入るので取りこぼしている
            texts.push(initChange.lines.text);
            initHistory = {
                id: initChange.lines.id,
                updatedAt: [0],
            };
        }
        else if (initChange.type === CHANGE_TYPE_UPDATE) {
            // タイトル行に書くとき
            texts.push(initChange.lines.text);
            initHistory = {
                id: initChange.targetId,
                updatedAt: [0],
            };
        }
        else {
            console.log("init change neither _insert nor _update");
        }
        const allHistory = restChanges.reduce((history, change, i) => {
            console.debug({ text: change.lines && change.lines.text, texts, history });
            const lineIndex = history.findIndex(h => h.id === change.targetId);
            switch (change.type) {
                case CHANGE_TYPE_INSERT:
                    texts.push(change.lines.text);
                    const line = {
                        id: change.lines.id,
                        updatedAt: [texts.length - 1],
                    };
                    if (change.targetId === "_end") {
                        // 最後の行なら単に1行足す
                        history.push(line);
                    }
                    else {
                        // 最後の行じゃないなら入れるべき場所に差し込む
                        if (lineIndex === -1) {
                            console.info(`_insert: line index not found. commit change (${i}):`, change);
                            return history;
                        }
                        history.splice(lineIndex, 0, line);
                    }
                    break;
                case CHANGE_TYPE_UPDATE:
                    texts.push(change.lines.text);
                    if (lineIndex === -1) {
                        console.info(`_update: line index not found. commit change (${i}):`, change);
                        return history;
                    }
                    history[lineIndex].updatedAt.push(texts.length - 1);
                    break;
                case CHANGE_TYPE_DELETE:
                    texts.push(null);
                    if (lineIndex === -1) {
                        console.info(`_delete: line index not found. commit change (${i}):`, change);
                        return history;
                    }
                    history[lineIndex].deletedAt = texts.length - 1;
                    break;
            }
            return history;
        }, [initHistory]);
        console.debug({ allHistory });
        return { texts, allHistory };
    })
        .then(({ texts, allHistory }) => {
        // 履歴連番から履歴を得る
        // - その時点で存在した行の履歴
        const getHistoryByTime = time => {
            return allHistory.reduce((all, history) => {
                // これまでの更新のうち最新の履歴連番
                const updatedAt = history.updatedAt.filter(u => u <= time).pop();
                // もう出現しているかどうか
                const appeared = updatedAt !== undefined;
                // もう消えてるかどうか
                const deleted = history.deletedAt !== undefined && history.deletedAt <= time;
                // まだ出現していない or もう消えてるなら, その行は返さない
                if (!appeared || deleted) {
                    return all;
                }
                // 出現している(かつ消えてない)ならその行を返す
                return [...all, { id: history.id, textIndex: updatedAt }];
            }, []);
        };
        // 履歴連番に対応するテキストを得る
        const getTextByTime = time => getHistoryByTime(time).map(history => texts[history.textIndex]).join("\n");
        // 操作系を表示してスライダーで操作できるようにする
        // - 指定された履歴連番からテキストを得て表示する
        const historyContainer = document.createElement("div");
        historyContainer.classList.add("history-container");
        Object.entries({
            "background-color": "#555555",
            position: "fixed",
            "z-index": "90000",
            top: "5px",
            left: "5px",
            width: "calc( 100% - 10px )",
            "max-height": "100%",
            border: "3px solid #22cc77",
            overflow: "scroll",
        }).forEach(([key, value]) => historyContainer.style.setProperty(key, value));
        document.querySelector("body").appendChild(historyContainer);
        const historyCloseButton = document.createElement("button");
        historyCloseButton.classList.add("history-close-button");
        Object.entries({
            "font-size": "30px",
            "line-height": "1em",
            padding: "0",
            position: "fixed",
            "z-index": "90001",
            top: "10px",
            right: "10px",
            width: "30px",
            height: "30px",
        }).forEach(([key, value]) => historyCloseButton.style.setProperty(key, value));
        historyContainer.appendChild(historyCloseButton);
        historyCloseButton.insertAdjacentText("beforeend", "\u00D7");
        const historyBackground = document.createElement("div");
        historyBackground.classList.add("history-background");
        Object.entries({
            position: "fixed",
            "z-index": "89999",
            top: "0",
            right: "0",
            width: "100%",
            height: "100%",
            "background-color": "rgba(255, 255, 255, 0.4)",
        }).forEach(([key, value]) => historyBackground.style.setProperty(key, value));
        document.querySelector("body").appendChild(historyBackground);
        const historyPre = document.createElement("pre");
        historyPre.classList.add("history-pre");
        Object.entries({
            width: "100%",
            "max-height": "100%",
        }).forEach(([key, value]) => historyPre.style.setProperty(key, value));
        historyPre.insertAdjacentHTML("beforeend", getTextByTime(texts.length));
        historyContainer.appendChild(historyPre);
        const historySlider = document.createElement("input");
        historySlider.classList.add("history-slider");
        Object.entries({
            position: "fixed",
            "z-index": "99999",
            top: "10px",
            width: "90%",
        }).forEach(([key, value]) => historySlider.style.setProperty(key, value));
        historySlider.type = "range";
        historySlider.min = "0";
        historySlider.max = `${texts.length}`;
        historySlider.value = `${texts.length}`;
        historySlider.step = 1;
        historyContainer.appendChild(historySlider);
        const removeHistoryContainer = () => {
            historyContainer.parentNode.removeChild(historyContainer);
            historyBackground.parentNode.removeChild(historyBackground);
        };
        historyCloseButton.addEventListener("click", removeHistoryContainer);
        historyBackground.addEventListener("click", removeHistoryContainer);
        const updateHistory = e => {
            const time = parseInt(e.target.value, 10);
            historyPre.innerHTML = getTextByTime(time);
            console.debug({ time, html: historyPre.innerHTML });
        };
        historySlider.addEventListener("input", updateHistory);
        historySlider.addEventListener("change", updateHistory);
    });
};
scrapbox.PageMenu.addMenu({
    title: "\u5C65\u6B74\u30B9\u30E9\u30A4\u30C0\u30FC",
    image: "https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png",
    onClick: onHistorySliderClick,
});
  • script.ts (37,21): Parameter 'href' implicitly has an 'any' type.
  • script.ts (47,31): Parameter 'href' implicitly has an 'any' type.
  • script.ts (58,24): Parameter 'rawChange' implicitly has an 'any' type.
  • script.ts (61,16): Property 'type' does not exist on type '{}'.
  • script.ts (62,16): Property 'targetId' does not exist on type '{}'.
  • script.ts (62,44): Property 'type' does not exist on type '{}'.
  • script.ts (65,16): Property 'type' does not exist on type '{}'.
  • script.ts (66,16): Property 'targetId' does not exist on type '{}'.
  • script.ts (66,44): Property 'type' does not exist on type '{}'.
  • script.ts (69,16): Property 'type' does not exist on type '{}'.
  • script.ts (70,16): Property 'targetId' does not exist on type '{}'.
  • script.ts (70,44): Property 'type' does not exist on type '{}'.
  • script.ts (73,16): Property 'type' does not exist on type '{}'.
  • script.ts (76,16): Property 'type' does not exist on type '{}'.
  • script.ts (79,16): Property 'type' does not exist on type '{}'.
  • script.ts (85,16): Property 'lines' does not exist on type '{}'.
  • script.ts (93,43): Parameter 'all' implicitly has an 'any' type.
  • script.ts (93,48): Parameter 'rawCommit' implicitly has an 'any' type.
  • script.ts (103,15): Variable 'texts' implicitly has type 'any[]' in some locations where its type cannot be determined.
  • script.ts (133,48): Parameter 'history' implicitly has an 'any' type.
  • script.ts (133,57): Parameter 'change' implicitly has an 'any' type.
  • script.ts (133,65): Parameter 'i' implicitly has an 'any' type.
  • script.ts (134,70): Variable 'texts' implicitly has an 'any[]' type.
  • script.ts (135,49): Parameter 'h' implicitly has an 'any' type.
  • script.ts (181,34): Parameter 'time' implicitly has an 'any' type.
  • script.ts (182,39): Parameter 'all' implicitly has an 'any' type.
  • script.ts (182,44): Parameter 'history' implicitly has an 'any' type.
  • script.ts (184,60): Parameter 'u' implicitly has an 'any' type.
  • script.ts (198,31): Parameter 'time' implicitly has an 'any' type.
  • script.ts (198,66): Parameter 'history' implicitly has an 'any' type.
  • script.ts (214,9): Object is possibly 'null'.
  • script.ts (241,9): Object is possibly 'null'.
  • script.ts (262,9): Type 'number' is not assignable to type 'string'.
  • script.ts (265,13): Object is possibly 'null'.
  • script.ts (266,13): Object is possibly 'null'.
  • script.ts (270,31): Parameter 'e' implicitly has an 'any' type.
  • script.ts (279,1): Cannot find name 'scrapbox'.

MessageEmbedを使って埋め込みを送信するサンプル

MessageEmbedを使って埋め込みを送信するサンプル

const Discord = require('discord.js')
const client = new Discord.Client()

client.on('message', message => {
  if (message.content === '!embed') {
    const embed = new Discord.MessageEmbed()
      .setTitle('埋め込みのタイトル')
      .setURL('https://google.com')
      .addField('name', 'value')
      .setColor('RANDOM')
      .setTimestamp()

    message.channel.send(embed)
  }
})

client.login('token')
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", message => {
    if (message.content === "!embed") {
        const embed = new Discord.MessageEmbed()
            .setTitle("\u57CB\u3081\u8FBC\u307F\u306E\u30BF\u30A4\u30C8\u30EB")
            .setURL("https://google.com")
            .addField("name", "value")
            .setColor("RANDOM")
            .setTimestamp();
        message.channel.send(embed);
    }
});
client.login("token");
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (12,30): Argument of type 'MessageEmbed' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Type 'MessageEmbed' is not assignable to type 'string'.
  • used message Event

const embed = new Discord.MessageEmbed()
.setTitle('埋め込みのタイトル 256字まで')
       .setDescription('埋め込みの説明 2048字まで')
       .setAuthor('著者名 256字','https://discord.js.org/static/logo-square.png')
       .setURL('https://google.com')
       .setThumbnail('https://discord.js.org/static/logo-square.png')
       .setImage('https://p.kindpng.com/picc/s/108-1084174_discord-js-discord-js-logo-png-transparent-png.png')
       .addField('フィールドの名前 256字まで', 'フィールドの値 1024字まで')
       .addField('フィールドは','最大25個まで')
       .addField('インラインフィールド','`,true`をつけることで',true)
       .addField('インラインフィールド','最大3つまで横に並べられる',true)
       .addField('インラインフィールドじゃない','途中で`,true`を取ると元に戻る')
       .addFields({name:'json形式で書けるフィールド',value:'字数制限などは同じ'},{name:'`{name:"name",value:"value"}`で1セット',value:'足りないとエラーが出る'})
       .addFields({name:'もちろん',value:'こっちも',inline:true},{name:'インラインに',value:'できる',inline:true})
       .setColor('#00ff00')
       .setFooter('埋め込みのフッター 2048字まで\n埋め込み全体の文字数は6000字まで\n一つのメッセージで送れる埋め込みは1つだけ\nwebhookを使うと10個まで送れる')
       .setTimestamp()
       
       message.channel.send(embed)
import * as Discord from "discord.js";
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const embed = new Discord.MessageEmbed()
    .setTitle("\u57CB\u3081\u8FBC\u307F\u306E\u30BF\u30A4\u30C8\u30EB 256\u5B57\u307E\u3067")
    .setDescription("\u57CB\u3081\u8FBC\u307F\u306E\u8AAC\u660E 2048\u5B57\u307E\u3067")
    .setAuthor("\u8457\u8005\u540D 256\u5B57", "https://discord.js.org/static/logo-square.png")
    .setURL("https://google.com")
    .setThumbnail("https://discord.js.org/static/logo-square.png")
    .setImage("https://p.kindpng.com/picc/s/108-1084174_discord-js-discord-js-logo-png-transparent-png.png")
    .addField("\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u540D\u524D 256\u5B57\u307E\u3067", "\u30D5\u30A3\u30FC\u30EB\u30C9\u306E\u5024 1024\u5B57\u307E\u3067")
    .addField("\u30D5\u30A3\u30FC\u30EB\u30C9\u306F", "\u6700\u592725\u500B\u307E\u3067")
    .addField("\u30A4\u30F3\u30E9\u30A4\u30F3\u30D5\u30A3\u30FC\u30EB\u30C9", "`,true`\u3092\u3064\u3051\u308B\u3053\u3068\u3067", true)
    .addField("\u30A4\u30F3\u30E9\u30A4\u30F3\u30D5\u30A3\u30FC\u30EB\u30C9", "\u6700\u59273\u3064\u307E\u3067\u6A2A\u306B\u4E26\u3079\u3089\u308C\u308B", true)
    .addField("\u30A4\u30F3\u30E9\u30A4\u30F3\u30D5\u30A3\u30FC\u30EB\u30C9\u3058\u3083\u306A\u3044", "\u9014\u4E2D\u3067`,true`\u3092\u53D6\u308B\u3068\u5143\u306B\u623B\u308B")
    .addFields({ name: "json\u5F62\u5F0F\u3067\u66F8\u3051\u308B\u30D5\u30A3\u30FC\u30EB\u30C9", value: "\u5B57\u6570\u5236\u9650\u306A\u3069\u306F\u540C\u3058" }, { name: "`{name:\"name\",value:\"value\"}`\u30671\u30BB\u30C3\u30C8", value: "\u8DB3\u308A\u306A\u3044\u3068\u30A8\u30E9\u30FC\u304C\u51FA\u308B" })
    .addFields({ name: "\u3082\u3061\u308D\u3093", value: "\u3053\u3063\u3061\u3082", inline: true }, { name: "\u30A4\u30F3\u30E9\u30A4\u30F3\u306B", value: "\u3067\u304D\u308B", inline: true })
    .setColor("#00ff00")
    .setFooter("\u57CB\u3081\u8FBC\u307F\u306E\u30D5\u30C3\u30BF\u30FC 2048\u5B57\u307E\u3067\n\u57CB\u3081\u8FBC\u307F\u5168\u4F53\u306E\u6587\u5B57\u6570\u306F6000\u5B57\u307E\u3067\n\u4E00\u3064\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u3067\u9001\u308C\u308B\u57CB\u3081\u8FBC\u307F\u306F1\u3064\u3060\u3051\nwebhook\u3092\u4F7F\u3046\u306810\u500B\u307E\u3067\u9001\u308C\u308B")
    .setTimestamp();
message.channel.send(embed);
  • embed.ts (22,22): Argument of type 'MessageEmbed' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Type 'MessageEmbed' is not assignable to type 'string'.

jsonファイルを使用してトークンを管理する(安全に)

jsonファイルを使用してトークンを管理する(安全に)

const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
import * as Discord from "discord.js";
import * as config from "./config.json";
const client = new Discord.Client();
  • index.ts (3,25): Cannot find module './config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.
  • index.ts (4,16): Expected 1 arguments, but got 0.

const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
//~~~~
client.login(config.token);
import * as Discord from "discord.js";
import * as config from "./config.json";
const client = new Discord.Client();
//~~~~
client.login(config.token);
  • index.ts (3,25): Cannot find module './config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.
  • index.ts (4,16): Expected 1 arguments, but got 0.

config.json
config.json;
  • test.ts (2,1): Cannot find name 'config'.

index.js
index.js;
  • test.ts (2,1): Cannot find name 'index'.

config.json
config.json;
  • test.ts (2,1): Cannot find name 'config'.

const config = require('./config.json');
import * as config from "./config.json";
  • test.ts (2,25): Cannot find module './config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.

discord.js
import * as discord from "discord.js";
discord.js;
  • test.ts (3,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

config.json
config.json;
  • test.ts (2,1): Cannot find name 'config'.

config.json
config.json;
  • test.ts (2,1): Cannot find name 'config'.

トークン
トークン;
  • test.ts (2,1): Cannot find name 'トークン'.

client.login(config.token);
declare var client: import("discord.js").Client;
client.login(config.token);
  • test.ts (3,14): Cannot find name 'config'.

config.json
config.json;
  • test.ts (2,1): Cannot find name 'config'.

config.json
config.json;
  • test.ts (2,1): Cannot find name 'config'.

discord-rpcを使ってステータスを設定する

discord-rpcを使ってステータスを設定する

const RPC = require('discord-rpc')
const rpc = new RPC.Client({ transport: 'ipc' })

rpc.on('ready', () => {
  rpc.setActivity({
    details: 'details',
    state: 'state',
    startTimestamp: new Date(),
  })
})

rpc.login({ clientId: 'CLIENT ID' })
import { Client } from "discord.js";
import * as RPC from "discord-rpc";
const rpc = new RPC.Client({ transport: "ipc" });
rpc.on("ready", () => {
    rpc.setActivity({
        details: "details",
        state: "state",
        startTimestamp: new Date(),
    });
});
rpc.login({ clientId: "CLIENT ID" });
  • test.ts (3,22): Cannot find module 'discord-rpc' or its corresponding type declarations.

100件以上のメッセージを取得する方法

100件以上のメッセージを取得する方法

const Collection = require("@discordjs/collection");
function array2Collection(messages) {
  return new Collection(messages.sort((a, b) => BigInt(a.id) < BigInt(b.id) ? 1 : -1).map(e => [e.id, e]));
}
module.exports = async function fetchMany(channel, options = { limit: 50 }) {
  if ((options.limit ?? 50) <= 100) {
    return channel.messages.fetch(options);
  }

  if (typeof options.around === "string") {
    const messages = await channel.messages.fetch({ ...options, limit: 100 });
    const limit = Math.floor((options.limit - 100) / 2);
    if (messages.size < 100) {
      return messages;
    }
    const backward = fetchMany(channel, { limit, before: messages.last().id });
    const forward = fetchMany(channel, { limit, after: messages.first().id });
    return array2Collection([messages, ...await Promise.all([backward, forward])].flatMap(
      e => [...e.values()]
    ));
  }
  let temp;
  function buildParameter() {
    const req_cnt = Math.min(options.limit - messages.length, 100);
    if (typeof options.after === "string") {
      const after = temp
        ? temp.first().id : options.after
      return { ...options, limit: req_cnt, after };
    }
    const before = temp
      ? temp.last().id : options.before;
    return { ...options, limit: req_cnt, before };
  }
  const messages = [];
  while (messages.length < options.limit) {
    const param = buildParameter();
    temp = await channel.messages.fetch(param);
    messages.push(...temp.values());
    if (param.limit > temp.size) {
      break;
    }
  }
  return array2Collection(messages);
}
import * as Collection from "@discordjs/collection";
function array2Collection(messages) {
    return new Collection(messages.sort((a, b) => BigInt(a.id) < BigInt(b.id) ? 1 : -1).map(e => [e.id, e]));
}
module.exports = async function fetchMany(channel, options = { limit: 50 }) {
    if ((options.limit ?? 50) <= 100) {
        return channel.messages.fetch(options);
    }
    if (typeof options.around === "string") {
        const messages = await channel.messages.fetch({ ...options, limit: 100 });
        const limit = Math.floor((options.limit - 100) / 2);
        if (messages.size < 100) {
            return messages;
        }
        const backward = fetchMany(channel, { limit, before: messages.last().id });
        const forward = fetchMany(channel, { limit, after: messages.first().id });
        return array2Collection([messages, ...await Promise.all([backward, forward])].flatMap(e => [...e.values()]));
    }
    let temp;
    function buildParameter() {
        const req_cnt = Math.min(options.limit - messages.length, 100);
        if (typeof options.after === "string") {
            const after = temp
                ? temp.first().id : options.after;
            return { ...options, limit: req_cnt, after };
        }
        const before = temp
            ? temp.last().id : options.before;
        return { ...options, limit: req_cnt, before };
    }
    const messages = [];
    while (messages.length < options.limit) {
        const param = buildParameter();
        temp = await channel.messages.fetch(param);
        messages.push(...temp.values());
        if (param.limit > temp.size) {
            break;
        }
    }
    return array2Collection(messages);
};
  • test.ts (3,27): Parameter 'messages' implicitly has an 'any' type.
  • test.ts (4,16): This expression is not constructable. Type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/@discordjs/collection/dist/index")' has no construct signatures.
  • test.ts (4,42): Parameter 'a' implicitly has an 'any' type.
  • test.ts (4,45): Parameter 'b' implicitly has an 'any' type.
  • test.ts (4,93): Parameter 'e' implicitly has an 'any' type.
  • test.ts (6,33): 'fetchMany' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
  • test.ts (6,43): Parameter 'channel' implicitly has an 'any' type.
  • test.ts (10,24): Property 'around' does not exist on type '{ limit: number; }'.
  • test.ts (16,15): 'backward' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
  • test.ts (16,54): Argument of type '{ limit: number; before: any; }' is not assignable to parameter of type '{ limit: number; }'. Object literal may only specify known properties, and 'before' does not exist in type '{ limit: number; }'.
  • test.ts (17,15): 'forward' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
  • test.ts (17,53): Argument of type '{ limit: number; after: any; }' is not assignable to parameter of type '{ limit: number; }'. Object literal may only specify known properties, and 'after' does not exist in type '{ limit: number; }'.
  • test.ts (20,9): Variable 'temp' implicitly has type 'any' in some locations where its type cannot be determined.
  • test.ts (23,28): Property 'after' does not exist on type '{ limit: number; }'.
  • test.ts (24,27): Variable 'temp' implicitly has an 'any' type.
  • test.ts (25,19): Variable 'temp' implicitly has an 'any' type.
  • test.ts (25,45): Property 'after' does not exist on type '{ limit: number; }'.
  • test.ts (28,24): Variable 'temp' implicitly has an 'any' type.
  • test.ts (29,15): Variable 'temp' implicitly has an 'any' type.
  • test.ts (29,40): Property 'before' does not exist on type '{ limit: number; }'.

let messages = []
const fetchedMessages = await fetchMany(channel, {
  limit: 400,
  before: "818529905184604180"
})

fetchedMessages.forEach(msg =>
  messages.push(`${msg.author.username} | ${msg.content}`)
)

console.log(messages.join('\n'))
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
let messages = [];
const fetchedMessages = await fetchMany(channel, {
    limit: 400,
    before: "818529905184604180"
});
fetchedMessages.forEach(msg => messages.push(`${msg.author.username} | ${msg.content}`));
console.log(messages.join("\n"));
  • test.ts (3,5): Variable 'messages' implicitly has type 'any[]' in some locations where its type cannot be determined.
  • test.ts (4,25): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (4,25): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (4,31): Cannot find name 'fetchMany'.
  • test.ts (8,25): Parameter 'msg' implicitly has an 'any' type.
  • test.ts (9,13): Variable 'messages' implicitly has an 'any[]' type.

fetchMany(<TextChannel | DMChannel | NewChannel>, <?ChannelLogsQueryOptions>)
import { TextChannel } from "discord.js";
import { DMChannel } from "discord.js";
fetchMany(<TextChannel | DMChannel | NewChannel>, <?ChannelLogsQueryOptions>);
  • test.ts (4,1): Cannot find name 'fetchMany'.
  • test.ts (4,38): Cannot find name 'NewChannel'.
  • test.ts (4,49): Expression expected.
  • test.ts (4,53): Cannot find name 'ChannelLogsQueryOptions'.
  • test.ts (4,77): Expression expected.

818529905184604180
818529905184604200;

818529905184604180
818529905184604200;

before
before;
  • test.ts (2,1): Cannot find name 'before'.

after
after;
  • test.ts (2,1): Cannot find name 'after'.

around
around;
  • test.ts (2,1): Cannot find name 'around'.

around
around;
  • test.ts (2,1): Cannot find name 'around'.

limit/2
limit / 2;
  • test.ts (2,1): Cannot find name 'limit'.

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

limit+1
limit + 1;
  • test.ts (2,1): Cannot find name 'limit'.

before
before;
  • test.ts (2,1): Cannot find name 'before'.

after
after;
  • test.ts (2,1): Cannot find name 'after'.

before
before;
  • test.ts (2,1): Cannot find name 'before'.

after
after;
  • test.ts (2,1): Cannot find name 'after'.

around
around;
  • test.ts (2,1): Cannot find name 'around'.

around
around;
  • test.ts (2,1): Cannot find name 'around'.

(limit-100)/2
(limit - 100) / 2;
  • test.ts (2,2): Cannot find name 'limit'.

sort
sort;
  • test.ts (2,1): Cannot find name 'sort'.

sort
sort;
  • test.ts (2,1): Cannot find name 'sort'.

fetchMany
fetchMany;
  • test.ts (2,1): Cannot find name 'fetchMany'.

HTTPリクエストを行う

HTTPリクエストを行う

const fetch = require("node-fetch");
const body = { a: 1 };
 
fetch('https://httpbin.org/post', {
        method: 'post',
        body:    JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' },
    })
    .then(res => res.json())
    .then(json => console.log(json));
import * as fetch from "node-fetch";
const body = { a: 1 };
fetch("https://httpbin.org/post", {
    method: "post",
    body: JSON.stringify(body),
    headers: { "Content-Type": "application/json" },
})
    .then(res => res.json())
    .then(json => console.log(json));
  • node-fetch.ts (2,24): Could not find a declaration file for module 'node-fetch'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/node-fetch/lib/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/node-fetch if it exists or add a new declaration (.d.ts) file containing declare module 'node-fetch';
  • node-fetch.ts (9,11): Parameter 'res' implicitly has an 'any' type.
  • node-fetch.ts (10,11): Parameter 'json' implicitly has an 'any' type.

const axios = require('axios');
const body = { a: 1 };

axios.post('https://httpbin.org/post', body)
	.then(res => console.log(res.data));
import * as axios from "axios";
const body = { a: 1 };
axios.post("https://httpbin.org/post", body)
    .then(res => console.log(res.data));
  • axios.ts (4,7): Property 'post' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/axios/index")'.
  • axios.ts (5,11): Parameter 'res' implicitly has an 'any' type.

const superagent = require('superagent');
const superagentJsonapify = require('superagent-jsonapify');
superagentJsonapify(superagent);

const body = { a: 1 };
superagent
  .post('https://httpbin.org/post')
  .send(body)
  .set('Content-Type','application/json')
  .accept('json')
  .then(res => console.log(res.json));
import * as superagent from "superagent";
import * as superagentJsonapify from "superagent-jsonapify";
superagentJsonapify(superagent);
const body = { a: 1 };
superagent
    .post("https://httpbin.org/post")
    .send(body)
    .set("Content-Type", "application/json")
    .accept("json")
    .then(res => console.log(res.json));
  • superagent.ts (2,29): Cannot find module 'superagent' or its corresponding type declarations.
  • superagent.ts (3,38): Cannot find module 'superagent-jsonapify' or its corresponding type declarations.
  • superagent.ts (11,11): Parameter 'res' implicitly has an 'any' type.

const got = require('got');
const body = { a: 1 };

got.post('https://httpbin.org/post', {
	json: body,
	responseType: 'json'
}).then(res => console.log(res.body.json));
import * as got from "got";
const body = { a: 1 };
got.post("https://httpbin.org/post", {
    json: body,
    responseType: "json"
}).then(res => console.log(res.body.json));
  • got.ts (2,22): Cannot find module 'got' or its corresponding type declarations.
  • got.ts (7,9): Parameter 'res' implicitly has an 'any' type.

メンションでメンバーを指定してBANするコマンドのサンプル

メンションでメンバーを指定してBANするコマンドのサンプル

client.on('message', async message => {
  if (message.content.startsWith('!ban') && message.guild) {
  	if (message.mentions.members.size !== 1)
  	 return message.channel.send('BANするメンバーを1人指定してください')
    const member = message.mentions.members.first()
    if (!member.bannable) return message.channel.send('このユーザーをBANすることができません')
    
    await member.ban()
    
    message.channel.send(`${member.user.tag}をBANしました`)
  }
});
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    if (message.content.startsWith("!ban") && message.guild) {
        if (message.mentions.members.size !== 1)
            return message.channel.send("BAN\u3059\u308B\u30E1\u30F3\u30D0\u30FC\u30921\u4EBA\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
        const member = message.mentions.members.first();
        if (!member.bannable)
            return message.channel.send("\u3053\u306E\u30E6\u30FC\u30B6\u30FC\u3092BAN\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093");
        await member.ban();
        message.channel.send(`${member.user.tag}をBANしました`);
    }
});
  • test.ts (6,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (8,13): Object is possibly 'null'.
  • test.ts (10,24): Object is possibly 'null'.
  • test.ts (11,14): Object is possibly 'undefined'.
  • test.ts (13,15): Object is possibly 'undefined'.
  • test.ts (14,33): Object is possibly 'undefined'.
  • used message Event

メンションで指定されたユーザーのメッセージだけを削除するコマンドのサンプル

メンションで指定されたユーザーのメッセージだけを削除するコマンドのサンプル

client.on('message', async message => {
    if (message.content.startsWith('!mmd') && message.guild) {
        // 指定されたメッセージの数を取得
        const how = message.content.split(' ')[1];
        // メンションでユーザーが指定されていなかったら処理を止める
        if (!how || message.mentions.members.size == 0) return;
        // 指定された数のメッセージを取得
        const messages = await message.channel.messages.fetch({ limit: how }) 
        // メンションで指定されたユーザーのIDのみを配列に入れる
        const mentionMembers = await message.mentions.members.map(m => m.user.id)
        // 指定されたユーザーが発言したメッセージのみを抽出
        const mentionFilter =  await messages.filter(msg => mentionMembers.some(userID => userID == msg.author.id))
        // それらのメッセージを一括削除
        message.channel.bulkDelete(mentionFilter)
   }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    if (message.content.startsWith("!mmd") && message.guild) {
        // 指定されたメッセージの数を取得
        const how = message.content.split(" ")[1];
        // メンションでユーザーが指定されていなかったら処理を止める
        if (!how || message.mentions.members.size == 0)
            return;
        // 指定された数のメッセージを取得
        const messages = await message.channel.messages.fetch({ limit: how });
        // メンションで指定されたユーザーのIDのみを配列に入れる
        const mentionMembers = await message.mentions.members.map(m => m.user.id);
        // 指定されたユーザーが発言したメッセージのみを抽出
        const mentionFilter = await messages.filter(msg => mentionMembers.some(userID => userID == msg.author.id));
        // それらのメッセージを一括削除
        message.channel.bulkDelete(mentionFilter);
    }
});
  • test.ts (11,21): Object is possibly 'null'.
  • test.ts (14,32): No overload matches this call. Overload 1 of 2, '(message: ${bigint}, options?: BaseFetchOptions | undefined): Promise', gave the following error. Argument of type '{ limit: string; }' is not assignable to parameter of type '${bigint}'. Overload 2 of 2, '(options?: ChannelLogsQueryOptions | undefined, cacheOptions?: BaseFetchOptions | undefined): Promise<Collection<${bigint}, Message>>', gave the following error. Type 'string' is not assignable to type 'number | undefined'.
  • test.ts (16,38): Object is possibly 'null'.
  • test.ts (20,25): Property 'bulkDelete' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'bulkDelete' does not exist on type 'DMChannel'.
  • used message Event

!mmd 1~100の数字 @mention#0000 @mention#9999 ...
!mmd;
1;
~100;
の数字;
#;
0;
#;
9999;
  • test.ts (2,2): Cannot find name 'mmd'.
  • test.ts (5,1): Cannot find name 'の数字'.
  • test.ts (6,1): Cannot find name '#'.
  • test.ts (6,1): Private identifiers are not allowed outside class bodies.
  • test.ts (6,2): Invalid character.
  • test.ts (8,1): Cannot find name '#'.
  • test.ts (8,1): Private identifiers are not allowed outside class bodies.
  • test.ts (8,2): Invalid character.

allowedMentions

allowedMentions

channel.send("@here Hi there from <@123>, cc <@&124>");
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("@here Hi there from <@123>, cc <@&124>");

channel.send("@everyone hi there, <@&123>",{
  allowedMentions: {
    parse: []
  }
});
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("@everyone hi there, <@&123>", {
    allowedMentions: {
        parse: []
    }
});
  • example2.ts (3,45): Expected 1 arguments, but got 2.

channel.send("@everyone <@123> <@&124>",{
  allowedMentions: {
    parse: ["users", "roles"],
    users: []
  }
});
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("@everyone <@123> <@&124>", {
    allowedMentions: {
        parse: ["users", "roles"],
        users: []
    }
});
  • example3.ts (3,42): Expected 1 arguments, but got 2.

channel.send("@everyone <@123> <@124> <@125> <@&200>",{
  allowedMentions: {
    parse: ["everyone"],
    users: ["123", "124"]
  }
});
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("@everyone <@123> <@124> <@125> <@&200>", {
    allowedMentions: {
        parse: ["everyone"],
        users: ["123", "124"]
    }
});
  • example4.ts (3,56): Expected 1 arguments, but got 2.

 channel.send("@everyone <@123> <@124> <@125> <@&200>",{
   allowedMentions: {
     parse: ["users"],
     users: ["123", "124"]
   }
 });
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("@everyone <@123> <@124> <@125> <@&200>", {
    allowedMentions: {
        parse: ["users"],
        users: ["123", "124"]
    }
});
  • example5.ts (3,56): Expected 1 arguments, but got 2.

 channel.send("<@123> Time for some memes.",{
   allowedMentions: {
     parse: ["users"],
     users: ["123", "125"]
   }
 });
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send("<@123> Time for some memes.", {
    allowedMentions: {
        parse: ["users"],
        users: ["123", "125"]
    }
});
  • example6.ts (3,45): Expected 1 arguments, but got 2.

allowed_mentions
allowed_mentions;
  • test.ts (2,1): Cannot find name 'allowed_mentions'.

近似を用いてサイコロの和を高速かつ省メモリ(O(1))に算出する

近似を用いてサイコロの和を高速かつ省メモリ(O(1))に算出する

function dice1(num, max) {
  const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
  const sum = roll_result.reduce((acc, cur) => acc + cur);
  return sum;
}
function rnorm() {
  return Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
}
function calc_V(mean, max) {
  return -((max + 1) * (max + 2) / 6 - mean * (max + 1) + mean * mean);
}
function dice2(num, max) {
  const max_result = num * max;
  if (!Number.isSafeInteger(max_result)) {
    throw new TypeError("too large input!");
  }
  const mean = (max + 1) / 2;
  const v = calc_V(mean, max);
  const sigma = Math.sqrt(v / num);
  while (true) {
    const result = Math.round((sigma * rnorm() + mean) * num);
    if (num <= result && result <= max_result) {
      return result;
    }
  }
}
const m = new Map();
const m2 = new Map();
const r = new Map();

 const num = 10000;
 const max = 20;
 const N = 100000;
 for (let i = 0; i < N; ++i) {
   const r1 = dice1(num, max);
   m.set(r1, (m.get(r1) ?? 0) + 1);
   const r2 = dice2(num, max);
   m2.set(r2, (m2.get(r2) ?? 0) + 1);
 }
 for (let [k, v] of m) {
   r.set(k, [v, 0]);
 }
 for (let [k, v] of m2) {
   if (r.has(k)) {
     const [v1] = r.get(k);
     r.set(k, [v1, v]);
   } else {
     r.set(k, [0, v]);

    }
  }
  console.log([...r].map(([k, v]) => `${k},${v.join(",")}`).join("\n"))
function dice1(num, max) {
    const roll_result = new Array(num).fill(null).map(() => Math.floor(Math.random() * max) + 1);
    const sum = roll_result.reduce((acc, cur) => acc + cur);
    return sum;
}
function rnorm() {
    return Math.sqrt(-2 * Math.log(1 - Math.random())) * Math.cos(2 * Math.PI * Math.random());
}
function calc_V(mean, max) {
    return -((max + 1) * (max + 2) / 6 - mean * (max + 1) + mean * mean);
}
function dice2(num, max) {
    const max_result = num * max;
    if (!Number.isSafeInteger(max_result)) {
        throw new TypeError("too large input!");
    }
    const mean = (max + 1) / 2;
    const v = calc_V(mean, max);
    const sigma = Math.sqrt(v / num);
    while (true) {
        const result = Math.round((sigma * rnorm() + mean) * num);
        if (num <= result && result <= max_result) {
            return result;
        }
    }
}
const m = new Map();
const m2 = new Map();
const r = new Map();
const num = 10000;
const max = 20;
const N = 100000;
for (let i = 0; i < N; ++i) {
    const r1 = dice1(num, max);
    m.set(r1, (m.get(r1) ?? 0) + 1);
    const r2 = dice2(num, max);
    m2.set(r2, (m2.get(r2) ?? 0) + 1);
}
for (let [k, v] of m) {
    r.set(k, [v, 0]);
}
for (let [k, v] of m2) {
    if (r.has(k)) {
        const [v1] = r.get(k);
        r.set(k, [v1, v]);
    }
    else {
        r.set(k, [0, v]);
    }
}
console.log([...r].map(([k, v]) => `${k},${v.join(",")}`).join("\n"));
  • dice.ts (2,16): Parameter 'num' implicitly has an 'any' type.
  • dice.ts (2,21): Parameter 'max' implicitly has an 'any' type.
  • dice.ts (10,17): Parameter 'mean' implicitly has an 'any' type.
  • dice.ts (10,23): Parameter 'max' implicitly has an 'any' type.
  • dice.ts (13,16): Parameter 'num' implicitly has an 'any' type.
  • dice.ts (13,21): Parameter 'max' implicitly has an 'any' type.

dice2
dice2;
  • test.ts (2,1): Cannot find name 'dice2'.

rnorm
rnorm;
  • test.ts (2,1): Cannot find name 'rnorm'.

yuta0801

yuta0801

 import '/api/code/yuta0801/yuta0801/script.js'
import "/api/code/yuta0801/yuta0801/script.js";

埋め込みを送信する

埋め込みを送信する

const embed = new Discord.MessageEmbed()
  .setTitle('埋め込みのタイトル')
  .setURL('https://google.com')
  .addField('name', 'value')
  .setColor('RANDOM')
  .setTimestamp()
message.channel.send(embed)
import * as Discord from "discord.js";
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const embed = new Discord.MessageEmbed()
    .setTitle("\u57CB\u3081\u8FBC\u307F\u306E\u30BF\u30A4\u30C8\u30EB")
    .setURL("https://google.com")
    .addField("name", "value")
    .setColor("RANDOM")
    .setTimestamp();
message.channel.send(embed);
  • test.ts (11,22): Argument of type 'MessageEmbed' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Type 'MessageEmbed' is not assignable to type 'string'.

message.channel.send({
  embed: {
  	title: '埋め込みのタイトル',
  	url: 'https://google.com',
  	fields: [{ name: 'name', value: 'value' }],
  	color: 4303284,
  	timestamp: new Date()
  }
})
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.send({
    embed: {
        title: "\u57CB\u3081\u8FBC\u307F\u306E\u30BF\u30A4\u30C8\u30EB",
        url: "https://google.com",
        fields: [{ name: "name", value: "value" }],
        color: 4303284,
        timestamp: new Date()
    }
});
  • test.ts (5,5): Argument of type '{ embed: { title: string; url: string; fields: { name: string; value: string; }[]; color: number; timestamp: Date; }; }' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Object literal may only specify known properties, and 'embed' does not exist in type 'MessagePayload | MessageOptions'.

リアクションされるたびに処理を実行する

リアクションされるたびに処理を実行する

client.on('messageReactionAdd', (reaction, user) => {
  console.log(`${reaction.message.guild}${user.tag}${reaction.emoji.name} をリアクションしました`)
})
declare var client: import("discord.js").Client;
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
client.on("messageReactionAdd", (reaction, user) => {
    console.log(`${reaction.message.guild}${user.tag}${reaction.emoji.name} をリアクションしました`);
});

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

メッセージが送信されるのを待ち受けて処理を実行する

メッセージが送信されるのを待ち受けて処理を実行する

message.channel.awaitMessages(() => true, { max: 1, time: 10 * 1000 })
  // Promiseを解決すると、収集できたメッセージのCollectionを得られる
  .then(collected => {
    // 何も収集できなかった場合を弾く(collected.sizeは取得できた個数、つまりこれは0のときを弾く)
    if (!collected.size) return console.log('メッセージが送信されませんでした(タイムアウト)')
    // collected.first()で取得できたメッセージを取得してログに出す
    console.log('メッセージ: ' + collected.first().content)
  })
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.awaitMessages(() => true, { max: 1, time: 10 * 1000 })
    // Promiseを解決すると、収集できたメッセージのCollectionを得られる
    .then(collected => {
    // 何も収集できなかった場合を弾く(collected.sizeは取得できた個数、つまりこれは0のときを弾く)
    if (!collected.size)
        return console.log("\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u9001\u4FE1\u3055\u308C\u307E\u305B\u3093\u3067\u3057\u305F(\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8)");
    // collected.first()で取得できたメッセージを取得してログに出す
    console.log("\u30E1\u30C3\u30BB\u30FC\u30B8: " + collected.first().content);
});
  • test.ts (4,43): Expected 0-1 arguments, but got 2.
  • test.ts (11,54): Object is possibly 'undefined'.

awaitMessages()
awaitMessages();
  • test.ts (2,1): Cannot find name 'awaitMessages'.

time: 1000
time: 1000;

max: 1
max: 1;

簡易的なコマンドハンドラのサンプル

簡易的なコマンドハンドラのサンプル

const Discord = require('discord.js')
const client = new Discord.Client()

const prefix = '!'

client.on('message', async message => {
  if (!message.content.startsWith(prefix)) return
  const [command, ...args] = message.content.slice(prefix.length).split(' ')
  if (command === 'add') {
    const [a, b] = args.map(str => Number(str))
    message.channel.send(`${a} + ${b} = ${a + b}`)
  }
})

client.login()
import * as Discord from "discord.js";
const client = new Discord.Client();
const prefix = "!";
client.on("message", async (message) => {
    if (!message.content.startsWith(prefix))
        return;
    const [command, ...args] = message.content.slice(prefix.length).split(" ");
    if (command === "add") {
        const [a, b] = args.map(str => Number(str));
        message.channel.send(`${a} + ${b} = ${a + b}`);
    }
});
client.login();
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • used message Event

if (command === 'コマンド名') {}
if (command === "\u30B3\u30DE\u30F3\u30C9\u540D") { }
  • test.ts (2,5): Cannot find name 'command'.

!コマンド名
!コマンド名;
  • test.ts (2,2): Cannot find name 'コマンド名'.

!コマンド名 引数1 引数2 引数3
!コマンド名;
引数1;
引数2;
引数3;
  • test.ts (2,2): Cannot find name 'コマンド名'.
  • test.ts (3,1): Cannot find name '引数1'.
  • test.ts (4,1): Cannot find name '引数2'.
  • test.ts (5,1): Cannot find name '引数3'.

v12でvoice-textを使う場合の注意点

v12でvoice-textを使う場合の注意点

 const stream = vt.stream(text.slice(0, 200), {
   speaker: 'haruka', volume: 200
 })
	
 connection.playStream(stream)
const stream = vt.stream(text.slice(0, 200), {
    speaker: "haruka",
    volume: 200
});
connection.playStream(stream);
  • test.ts (2,16): Cannot find name 'vt'.
  • test.ts (2,26): Cannot find name 'text'. Did you mean 'Text'?
  • test.ts (6,1): Cannot find name 'connection'.

const { Readable: ReadableStream } = require('stream')

const stream = vt.stream(text.slice(0, 200), {
  speaker: 'haruka', volume: 200
})

connection.play(new ReadableStream().wrap(stream))
import { Readable as ReadableStream } from "stream";
const stream = vt.stream(text.slice(0, 200), {
    speaker: "haruka",
    volume: 200
});
connection.play(new ReadableStream().wrap(stream));
  • test.ts (3,16): Cannot find name 'vt'.
  • test.ts (3,26): Cannot find name 'text'. Did you mean 'Text'?
  • test.ts (7,1): Cannot find name 'connection'.

リアクションされるのを待ち受けて処理を実行する

リアクションされるのを待ち受けて処理を実行する

const filter = (reaction, user) => user.id === message.author.id && reaction.emoji.name === '👌'
message.awaitReactions(filter, { max: 1, time: 15000, errors: ['time'] })
  .then(() => console.log('リアクションされました'))
  .catch(() => {}) // 時間切れの処理。エラーを防ぐために何もしない場合でも書く必要がある(何かすることもできる)
declare var message: import("discord.js").Message;
const filter = (reaction, user) => user.id === message.author.id && reaction.emoji.name === "\uD83D\uDC4C";
message.awaitReactions(filter, { max: 1, time: 15000, errors: ["time"] })
    .then(() => console.log("\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u3055\u308C\u307E\u3057\u305F"))
    .catch(() => { }); // 時間切れの処理。エラーを防ぐために何もしない場合でも書く必要がある(何かすることもできる)
  • test.ts (3,17): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (3,27): Parameter 'user' implicitly has an 'any' type.
  • test.ts (4,32): Expected 0-1 arguments, but got 2.

message.awaitReactions(reaction => reaction.emoji.name === '👌', { time: 15000 })
  .then(collected => console.log(`リアクションが ${collected.size} 個つけられました`))
declare var message: import("discord.js").Message;
message.awaitReactions(reaction => reaction.emoji.name === "\uD83D\uDC4C", { time: 15000 })
    .then(collected => console.log(`リアクションが ${collected.size} 個つけられました`));
  • test.ts (3,24): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (3,76): Expected 0-1 arguments, but got 2.

message.awaitReactions(reaction => reaction.emoji.name === '👌', { max: 3 })
  .then(collected => console.log(`${collected.first().users.cache.map(user => user.tag).join(', ')} がリアクションを付けました`))
declare var message: import("discord.js").Message;
message.awaitReactions(reaction => reaction.emoji.name === "\uD83D\uDC4C", { max: 3 })
    .then(collected => console.log(`${collected.first().users.cache.map(user => user.tag).join(", ")} がリアクションを付けました`));
  • test.ts (3,24): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (3,76): Expected 0-1 arguments, but got 2.
  • test.ts (4,39): Object is possibly 'undefined'.

time: 1000
time: 1000;

max: 1
max: 1;

固定メッセージへのリアクションに反応して役職を付けるサンプル

固定メッセージへのリアクションに反応して役職を付けるサンプル

const handleReaction = async (channelID, messageID, callback) => {
   const channel = await client.channels.fetch(channelID)
   const message = await channel.messages.fetch(messageID)
   const collector = message.createReactionCollector(() => true)
   collector.on('collect', (reaction, user) => callback(reaction, user))
}

client.on('ready', () => {
  handleReaction('channel id', 'message id', (reaction, user) => {
    if (reaction.emoji.name === '✅') {
      reaction.message.guild.member(user).roles.add('role id')
    }
  })
})
declare var client: import("discord.js").Client;
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
const handleReaction = async (channelID, messageID, callback) => {
    const channel = await client.channels.fetch(channelID);
    const message = await channel.messages.fetch(messageID);
    const collector = message.createReactionCollector(() => true);
    collector.on("collect", (reaction, user) => callback(reaction, user));
};
client.on("ready", () => {
    handleReaction("channel id", "message id", (reaction, user) => {
        if (reaction.emoji.name === "\u2705") {
            reaction.message.guild.member(user).roles.add("role id");
        }
    });
});
  • test.ts (6,31): Parameter 'channelID' implicitly has an 'any' type.
  • test.ts (6,42): Parameter 'messageID' implicitly has an 'any' type.
  • test.ts (6,53): Parameter 'callback' implicitly has an 'any' type.
  • test.ts (8,27): Object is possibly 'null'.
  • test.ts (8,35): Property 'messages' does not exist on type 'Channel'.
  • test.ts (10,30): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (10,40): Parameter 'user' implicitly has an 'any' type.
  • test.ts (13,49): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (13,59): Parameter 'user' implicitly has an 'any' type.

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

3番目にリアクションを付けた人を取得するサンプル

3番目にリアクションを付けた人を取得するサンプル

client.on('message', message => {
  // 3番目のリアクション、つまり3つ目リアクションが付いたときだけに絞り込む
  // 対象の絵文字も絞り込む
  const filter = reaction => reaction.count === 3 && reaction.emoji.name === '👍'
  const collector = message.createReactionCollector(filter)
  collector.on('collect', (reaction, user) => {
    // 使ったcollectorはもう必要ないので止める
    collector.stop()
    console.log(user.tag)
  })
})
declare var client: import("discord.js").Client;
client.on("message", message => {
    // 3番目のリアクション、つまり3つ目リアクションが付いたときだけに絞り込む
    // 対象の絵文字も絞り込む
    const filter = reaction => reaction.count === 3 && reaction.emoji.name === "\uD83D\uDC4D";
    const collector = message.createReactionCollector(filter);
    collector.on("collect", (reaction, user) => {
        // 使ったcollectorはもう必要ないので止める
        collector.stop();
        console.log(user.tag);
    });
});
  • test.ts (6,20): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (7,55): Type '(reaction: any) => boolean' has no properties in common with type 'ReactionCollectorOptions'.
  • used message Event

const events = require('events')

client.on('message', async message => {
  // 3番目のリアクション、つまり3つ目リアクションが付いたときだけに絞り込む
  // 対象の絵文字も絞り込む
  const filter = reaction => reaction.count === 3 && reaction.emoji.name === '👍'
  const collector = message.createReactionCollector(filter)
  const [reaction, user] = await events.once(collector, 'collect')
  // 使ったcollectorはもう必要ないので止める
  collector.stop()
  console.log(user.tag)
})
declare var client: import("discord.js").Client;
import * as events from "events";
client.on("message", async (message) => {
    // 3番目のリアクション、つまり3つ目リアクションが付いたときだけに絞り込む
    // 対象の絵文字も絞り込む
    const filter = reaction => reaction.count === 3 && reaction.emoji.name === "\uD83D\uDC4D";
    const collector = message.createReactionCollector(filter);
    const [reaction, user] = await events.once(collector, "collect");
    // 使ったcollectorはもう必要ないので止める
    collector.stop();
    console.log(user.tag);
});
  • test.ts (7,20): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (8,55): Type '(reaction: any) => boolean' has no properties in common with type 'ReactionCollectorOptions'.
  • used message Event

Discord.jsでEmbedのグローバルチャットを作る

Discord.jsでEmbedのグローバルチャットを作る

const Discord = require('discord.js');
const client = new Discord.Client();

client.login("<Token>");

client.on('message', message =>
{
    if (message.channel.name === 'チャンネル名')
    {
        if (message.author.bot) return;
        if (message.attachments.size <= 0)
        {
            message.delete()
        }
        client.channels.cache.forEach(channel =>
        {
            if (message.attachments.size <= 0)
            {
                const embed = new Discord.MessageEmbed()
                    .setAuthor(message.author.tag, message.author.avatarURL())
                    .setDescription(message.content)
                    .setColor(0x2C2F33)
                    .setFooter(message.guild.name, message.guild.iconURL())
                    .setTimestamp()
                if (channel.name === 'チャンネル名')
                {
                    channel.send(embed)
                    return;
                }
                return;
            }
            if (!message.attachments.forEach(attachment =>
            {
                const embed = new Discord.MessageEmbed()
                    .setAuthor(message.author.tag, message.author.avatarURL())
                    .setImage(attachment.url)
                    .setDescription(attachment.url)
                    .setColor(0x2C2F33)
                    .setFooter(message.guild.name, message.guild.iconURL())
                    .setTimestamp()
                if (channel.name === 'チャンネル名')
                {
                    channel.send(embed)
                    return;
                }
                return;
            }));
            return;
        });
    }
})
import * as Discord from "discord.js";
const client = new Discord.Client();
client.login("<Token>");
client.on("message", message => {
    if (message.channel.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D") {
        if (message.author.bot)
            return;
        if (message.attachments.size <= 0) {
            message.delete();
        }
        client.channels.cache.forEach(channel => {
            if (message.attachments.size <= 0) {
                const embed = new Discord.MessageEmbed()
                    .setAuthor(message.author.tag, message.author.avatarURL())
                    .setDescription(message.content)
                    .setColor(2895667)
                    .setFooter(message.guild.name, message.guild.iconURL())
                    .setTimestamp();
                if (channel.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D") {
                    channel.send(embed);
                    return;
                }
                return;
            }
            if (!message.attachments.forEach(attachment => {
                const embed = new Discord.MessageEmbed()
                    .setAuthor(message.author.tag, message.author.avatarURL())
                    .setImage(attachment.url)
                    .setDescription(attachment.url)
                    .setColor(2895667)
                    .setFooter(message.guild.name, message.guild.iconURL())
                    .setTimestamp();
                if (channel.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D") {
                    channel.send(embed);
                    return;
                }
                return;
            }))
                ;
            return;
        });
    }
});
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (6,25): Property 'name' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'name' does not exist on type 'DMChannel'.
  • test.ts (15,52): Argument of type 'string | null' is not assignable to parameter of type 'string | undefined'. Type 'null' is not assignable to type 'string | undefined'.
  • test.ts (18,32): Object is possibly 'null'.
  • test.ts (18,52): Object is possibly 'null'.
  • test.ts (18,52): Argument of type 'string | null' is not assignable to parameter of type 'string | undefined'.
  • test.ts (20,29): Property 'name' does not exist on type 'Channel'.
  • test.ts (21,29): Property 'send' does not exist on type 'Channel'.
  • test.ts (26,18): An expression of type 'void' cannot be tested for truthiness.
  • test.ts (28,52): Argument of type 'string | null' is not assignable to parameter of type 'string | undefined'.
  • test.ts (32,32): Object is possibly 'null'.
  • test.ts (32,52): Object is possibly 'null'.
  • test.ts (32,52): Argument of type 'string | null' is not assignable to parameter of type 'string | undefined'.
  • test.ts (34,29): Property 'name' does not exist on type 'Channel'.
  • test.ts (35,29): Property 'send' does not exist on type 'Channel'.
  • test.ts (40,17): The body of an 'if' statement cannot be the empty statement.
  • used message Event

node -v
node - v;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (2,8): Cannot find name 'v'.

サーバーからあるユーザー名で始まるメンバーを取得する

サーバーからあるユーザー名で始まるメンバーを取得する

const discord = require("discord.js");

const username = "username";
const client = new discord.Client({
  ws: {
    intents: discord.Intents.FLAGS.GUILDS,
  }
});

client.on("ready", async ()=>{
  const guild = client.guilds.cache.first();
  const members = await guild.members.fetch({
    query: username,
  });
  console.log(members);
});

client.login("token");
import * as discord from "discord.js";
const username = "username";
const client = new discord.Client({
    ws: {
        intents: discord.Intents.FLAGS.GUILDS,
    }
});
client.on("ready", async () => {
    const guild = client.guilds.cache.first();
    const members = await guild.members.fetch({
        query: username,
    });
    console.log(members);
});
client.login("token");
  • test.ts (6,9): Type '{ intents: number; }' is not assignable to type 'WebSocketOptions'. Object literal may only specify known properties, and 'intents' does not exist in type 'WebSocketOptions'.
  • test.ts (11,27): Object is possibly 'undefined'.

固定メッセージへのリアクションに反応して処理をするサンプル

固定メッセージへのリアクションに反応して処理をするサンプル

const handleReaction = async (channelID, messageID, callback) => {
   const channel = await client.channels.fetch(channelID)
   const message = await channel.messages.fetch(messageID)
   const collector = message.createReactionCollector(() => true)
   collector.on('collect', (reaction, user) => callback(reaction, user))
}

client.on('ready', () => {
  handleReaction('channel id', 'message id', (reaction, user) => {
    console.log(`${user.tag}${reaction.emoji.name} をリアクションしました`)
  })
})
declare var client: import("discord.js").Client;
const handleReaction = async (channelID, messageID, callback) => {
    const channel = await client.channels.fetch(channelID);
    const message = await channel.messages.fetch(messageID);
    const collector = message.createReactionCollector(() => true);
    collector.on("collect", (reaction, user) => callback(reaction, user));
};
client.on("ready", () => {
    handleReaction("channel id", "message id", (reaction, user) => {
        console.log(`${user.tag}${reaction.emoji.name} をリアクションしました`);
    });
});
  • test.ts (3,31): Parameter 'channelID' implicitly has an 'any' type.
  • test.ts (3,42): Parameter 'messageID' implicitly has an 'any' type.
  • test.ts (3,53): Parameter 'callback' implicitly has an 'any' type.
  • test.ts (5,27): Object is possibly 'null'.
  • test.ts (5,35): Property 'messages' does not exist on type 'Channel'.
  • test.ts (7,30): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (7,40): Parameter 'user' implicitly has an 'any' type.
  • test.ts (10,49): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (10,59): Parameter 'user' implicitly has an 'any' type.

ファイルをオウム返しするサンプル

ファイルをオウム返しするサンプル

client.on('message', message => {
  // メッセージにファイルが添付されていて、送信したのがボットじゃないときだけ(無限ループを避けるため)実行する
  if (message.attachments.size && !message.author.bot) {
    // 添付された全ての画像(ファイル)のURLを取得する
    const files = message.attachments.map(attachment => attachment.url)
    // ファイルを指定してメッセージを送信する
    message.channel.send({ files })
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", message => {
    // メッセージにファイルが添付されていて、送信したのがボットじゃないときだけ(無限ループを避けるため)実行する
    if (message.attachments.size && !message.author.bot) {
        // 添付された全ての画像(ファイル)のURLを取得する
        const files = message.attachments.map(attachment => attachment.url);
        // ファイルを指定してメッセージを送信する
        message.channel.send({ files });
    }
});
  • used message Event

Possible EventEmitter memory leak detected. が出たとき

Possible EventEmitter memory leak detected. が出たとき

client.on('message', () => { ... })
client.on('message', () => { ... })
client.on('message', () => { ... })
declare var client: import("discord.js").Client;
client.on("message", () => { }, ...);
client.on("message", () => { }, ...);
client.on("message", () => { }, ...);
  • test.ts (3,33): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,36): Expression expected.
  • test.ts (4,33): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (4,36): Expression expected.
  • test.ts (5,33): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (5,36): Expression expected.
  • used message Event

client.on('message', () => {
  client.on('message', () => { ... })
})
declare var client: import("discord.js").Client;
client.on("message", () => {
    client.on("message", () => { }, ...);
});
  • test.ts (4,37): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (4,40): Expression expected.
  • used message Event

client.on('message', ...)
declare var client: import("discord.js").Client;
client.on("message", ...);
  • test.ts (3,22): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,25): Expression expected.
  • used message Event

foo.on()
foo.on();
  • test.ts (2,1): Cannot find name 'foo'.

client.on('message', ...)
declare var client: import("discord.js").Client;
client.on("message", ...);
  • test.ts (3,22): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,25): Expression expected.
  • used message Event

スパム対策をするサンプル

スパム対策をするサンプル

const lastSendTime = {}
const prefix = '!'

client.on('message', msg => {
  if (msg.author.bot || !msg.content.startsWith(prefix)) return
  if (lastSendTime[msg.channel.id]) {
    if (Date.now() - lastSendTime[msg.channel.id][msg.author.id] <= 1000 /* ms */)
      return msg.reply('スパムしないでください!')
    lastSendTime[msg.channel.id][msg.author.id] = Date.now()
  } else {
    lastSendTime[msg.channel.id] = {}
    lastSendTime[msg.channel.id][msg.author.id] = Date.now()
  }
  // ここにコード書いてく
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const lastSendTime = {};
const prefix = "!";
client.on("message", msg => {
    if (msg.author.bot || !msg.content.startsWith(prefix))
        return;
    if (lastSendTime[msg.channel.id]) {
        if (Date.now() - lastSendTime[msg.channel.id][msg.author.id] <= 1000 /* ms */)
            return msg.reply("\u30B9\u30D1\u30E0\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044\uFF01");
        lastSendTime[msg.channel.id][msg.author.id] = Date.now();
    }
    else {
        lastSendTime[msg.channel.id] = {};
        lastSendTime[msg.channel.id][msg.author.id] = Date.now();
    }
    // ここにコード書いてく
});
  • test.ts (6,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(msg: Message) => Promise | undefined' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise | undefined' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message, TResult2 = never>(onfulfilled?: ((value: Message) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (9,9): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (10,26): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (12,9): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (15,9): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • test.ts (16,9): Element implicitly has an 'any' type because expression of type '${bigint}' can't be used to index type '{}'.
  • used message Event

Date.now()
Date.now();

Date.now()
Date.now();

Date.now() - メッセージが送られた時の時間
Date.now() - メッセージが送られた時の時間;
  • test.ts (2,14): Cannot find name 'メッセージが送られた時の時間'.

ms
ms;
  • test.ts (2,1): Cannot find name 'ms'.

メンバー数をチャンネル名として表示するサンプル

メンバー数をチャンネル名として表示するサンプル

const Discord = require('discord.js')
const client = new Discord.Client()

const GUILD = '...' // 動作させるサーバーのID
const CHANNEL = '...' // 名前を変更するチャンネルのID

// ボットがオフラインのときの変更は出来ないから、起動時に辻褄を合わせる
client.on('ready', () => {
  const guild = client.guilds.cache.get(GUILD)
  const channel = guild.channels.cache.get(CHANNEL)
  channel.setName('メンバー数: ' + guild.memberCount)
})

// メンバーが参加したらチャンネル名を更新する
client.on('guildMemberAdd', member => {
  // 指定したサーバーでのみ実行する
  if (member.guild.id === GUILD) {
    // チャンネルを取得して、名前を更新する
    const channel = member.guild.channels.cache.get(CHANNEL)
    channel.setName('メンバー数: ' + member.guild.memberCount)
  }
})

// メンバーが退出したらチャンネル名を更新する(処理は上と同じ)
client.on('guildMemberRemove', member => {
  if (member.guild.id === GUILD) {
    const channel = member.guild.channels.cache.get(CHANNEL)
    channel.setName('メンバー数: ' + member.guild.memberCount)
  }
})

client.login()
import * as Discord from "discord.js";
const client = new Discord.Client();
const GUILD = "..."; // 動作させるサーバーのID
const CHANNEL = "..."; // 名前を変更するチャンネルのID
// ボットがオフラインのときの変更は出来ないから、起動時に辻褄を合わせる
client.on("ready", () => {
    const guild = client.guilds.cache.get(GUILD);
    const channel = guild.channels.cache.get(CHANNEL);
    channel.setName("\u30E1\u30F3\u30D0\u30FC\u6570: " + guild.memberCount);
});
// メンバーが参加したらチャンネル名を更新する
client.on("guildMemberAdd", member => {
    // 指定したサーバーでのみ実行する
    if (member.guild.id === GUILD) {
        // チャンネルを取得して、名前を更新する
        const channel = member.guild.channels.cache.get(CHANNEL);
        channel.setName("\u30E1\u30F3\u30D0\u30FC\u6570: " + member.guild.memberCount);
    }
});
// メンバーが退出したらチャンネル名を更新する(処理は上と同じ)
client.on("guildMemberRemove", member => {
    if (member.guild.id === GUILD) {
        const channel = member.guild.channels.cache.get(CHANNEL);
        channel.setName("\u30E1\u30F3\u30D0\u30FC\u6570: " + member.guild.memberCount);
    }
});
client.login();
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (8,43): Argument of type '"..."' is not assignable to parameter of type '${bigint}'.
  • test.ts (9,21): Object is possibly 'undefined'.
  • test.ts (9,46): Argument of type '"..."' is not assignable to parameter of type '${bigint}'.
  • test.ts (10,5): Object is possibly 'undefined'.
  • test.ts (10,58): Object is possibly 'undefined'.
  • test.ts (17,57): Argument of type '"..."' is not assignable to parameter of type '${bigint}'.
  • test.ts (18,9): Object is possibly 'undefined'.
  • test.ts (24,57): Argument of type '"..."' is not assignable to parameter of type '${bigint}'.
  • test.ts (25,9): Object is possibly 'undefined'.

ytdl-core を使用して YouTube の音源を配信するサンプル

ytdl-core を使用して YouTube の音源を配信するサンプル

const ytdl = require('ytdl-core')

client.on('message', async message => {
  // メッセージが "!yt" からはじまっていてサーバー内だったら実行する
  if (message.content.startsWith('!yt') && message.guild) {
    // メッセージから動画URLだけを取り出す
    const url = message.content.split(' ')[1]
    // まず動画が見つからなければ処理を止める
    if (!ytdl.validateURL(url)) return message.reply('動画が存在しません!')
    // コマンドを実行したメンバーがいるボイスチャンネルを取得
    const channel = message.member.voice.channel
    // コマンドを実行したメンバーがボイスチャンネルに入ってなければ処理を止める
    if (!channel) return message.reply('先にボイスチャンネルに参加してください!')
    // チャンネルに参加
    const connection = await channel.join()
    // 動画の音源を取得
    const stream = ytdl(ytdl.getURLVideoID(url), { filter: 'audioonly' })
    // 再生
    const dispatcher = connection.play(stream)
    
    // 再生が終了したら抜ける
    dispatcher.once('finish', () => {
      channel.leave()
    })
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import * as ytdl from "ytdl-core";
client.on("message", async (message) => {
    // メッセージが "!yt" からはじまっていてサーバー内だったら実行する
    if (message.content.startsWith("!yt") && message.guild) {
        // メッセージから動画URLだけを取り出す
        const url = message.content.split(" ")[1];
        // まず動画が見つからなければ処理を止める
        if (!ytdl.validateURL(url))
            return message.reply("\u52D5\u753B\u304C\u5B58\u5728\u3057\u307E\u305B\u3093\uFF01");
        // コマンドを実行したメンバーがいるボイスチャンネルを取得
        const channel = message.member.voice.channel;
        // コマンドを実行したメンバーがボイスチャンネルに入ってなければ処理を止める
        if (!channel)
            return message.reply("\u5148\u306B\u30DC\u30A4\u30B9\u30C1\u30E3\u30F3\u30CD\u30EB\u306B\u53C2\u52A0\u3057\u3066\u304F\u3060\u3055\u3044\uFF01");
        // チャンネルに参加
        const connection = await channel.join();
        // 動画の音源を取得
        const stream = ytdl(ytdl.getURLVideoID(url), { filter: "audioonly" });
        // 再生
        const dispatcher = connection.play(stream);
        // 再生が終了したら抜ける
        dispatcher.once("finish", () => {
            channel.leave();
        });
    }
});
  • test.ts (6,23): Cannot find module 'ytdl-core' or its corresponding type declarations.
  • test.ts (7,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (16,25): Object is possibly 'null'.
  • test.ts (21,42): Property 'join' does not exist on type 'VoiceChannel | StageChannel'. Property 'join' does not exist on type 'VoiceChannel'.
  • test.ts (28,21): Property 'leave' does not exist on type 'VoiceChannel | StageChannel'. Property 'leave' does not exist on type 'VoiceChannel'.
  • used message Event

ytdl-core
ytdl - core;
  • test.ts (2,1): Cannot find name 'ytdl'.
  • test.ts (2,8): Cannot find name 'core'.

@discordjs/opus
/opus;;
  • test.ts (2,2): Unterminated regular expression literal.

ffmpeg-static
ffmpeg - static;
  • test.ts (2,1): Cannot find name 'ffmpeg'.
  • test.ts (2,10): Identifier expected. 'static' is a reserved word in strict mode.
  • test.ts (2,10): Cannot find name 'static'.

msg.member.voice.channel
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
msg.member.voice.channel;
  • test.ts (4,1): Cannot find name 'msg'.

msg.member.voiceChannel
declare var member: import("discord.js").GuildMember;
msg.member.voiceChannel;
  • test.ts (3,1): Cannot find name 'msg'.

connection.play
connection.play;
  • test.ts (2,1): Cannot find name 'connection'.

connection.playStream
connection.playStream;
  • test.ts (2,1): Cannot find name 'connection'.

dispatcher.once('finish', ...)
dispatcher.once("finish", ...);
  • test.ts (2,1): Cannot find name 'dispatcher'.
  • test.ts (2,30): Expression expected.

dispatcher.on('end', ...)
dispatcher.on("end", ...);
  • test.ts (2,1): Cannot find name 'dispatcher'.
  • test.ts (2,25): Expression expected.

!yt YouTube の動画URL
!yt;
YouTube;
の動画URL;
  • test.ts (2,2): Cannot find name 'yt'.
  • test.ts (3,1): Cannot find name 'YouTube'.
  • test.ts (4,1): Cannot find name 'の動画URL'.

discord-rpcを使うサンプル

discord-rpcを使うサンプル

const RPC = require('discord-rpc') 
const clientId = 'CLIENT ID';
const scopes = ['rpc', 'messages.read'];
 
const client = new RPC.Client({ transport: 'ipc' });
 
client.on('ready', () => {
  console.log('Logged in as', client.application.name);
  console.log('Authed for user', client.user.username);
 
  client.selectVoiceChannel('81384788862181376');
});
 
// Log in to RPC with client id
client.login({ clientId, scopes });
import { Client } from "discord.js";
declare var user: import("discord.js").User;
import * as RPC from "discord-rpc";
const clientId = "CLIENT ID";
const scopes = ["rpc", "messages.read"];
const client = new RPC.Client({ transport: "ipc" });
client.on("ready", () => {
    console.log("Logged in as", client.application.name);
    console.log("Authed for user", client.user.username);
    client.selectVoiceChannel("81384788862181376");
});
// Log in to RPC with client id
client.login({ clientId, scopes });
  • test.ts (4,22): Cannot find module 'discord-rpc' or its corresponding type declarations.

discord-rpc
import * as discord from "discord.js";
discord - rpc;
  • test.ts (3,1): The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (3,11): Cannot find name 'rpc'.

'rpc.api'
"rpc.api";

ipc
ipc;
  • test.ts (2,1): Cannot find name 'ipc'.

'rpc.api'
"rpc.api";

'rpc.api'
"rpc.api";

Unknown Error
Unknown;
Error;
  • test.ts (2,1): Cannot find name 'Unknown'.

文字列を翻訳して返すサンプル

文字列を翻訳して返すサンプル

const fetch = require('node-fetch')

client.on('message', async (message) => {
  const args = message.content.split(' ').slice(1)

  if (message.content.startsWith('!translate ')) {
    const source = encodeURIComponent(args.shift())
    const target = encodeURIComponent(args.shift())
    const text = encodeURIComponent(args.join(' '))

    const content = await fetch(`https://script.google.com/macros/s/AKfycbweJFfBqKUs5gGNnkV2xwTZtZPptI6ebEhcCU2_JvOmHwM2TCk/exec?text=${text}&source=${source}&target=${target}`).then(res => res.text())
    message.channel.send(content)
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
import * as fetch from "node-fetch";
client.on("message", async (message) => {
    const args = message.content.split(" ").slice(1);
    if (message.content.startsWith("!translate ")) {
        const source = encodeURIComponent(args.shift());
        const target = encodeURIComponent(args.shift());
        const text = encodeURIComponent(args.join(" "));
        const content = await fetch(`https://script.google.com/macros/s/AKfycbweJFfBqKUs5gGNnkV2xwTZtZPptI6ebEhcCU2_JvOmHwM2TCk/exec?text=${text}&source=${source}&target=${target}`).then(res => res.text());
        message.channel.send(content);
    }
});
  • test.ts (4,24): Could not find a declaration file for module 'node-fetch'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/node-fetch/lib/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/node-fetch if it exists or add a new declaration (.d.ts) file containing declare module 'node-fetch';
  • test.ts (8,43): Argument of type 'string | undefined' is not assignable to parameter of type 'string | number | boolean'. Type 'undefined' is not assignable to type 'string | number | boolean'.
  • test.ts (9,43): Argument of type 'string | undefined' is not assignable to parameter of type 'string | number | boolean'.
  • test.ts (11,188): Parameter 'res' implicitly has an 'any' type.
  • used message Event

!translate 元の言語 翻訳先の言語 翻訳するテキスト
!translate;
元の言語;
翻訳先の言語;
翻訳するテキスト;
  • test.ts (2,2): Cannot find name 'translate'.
  • test.ts (3,1): Cannot find name '元の言語'.
  • test.ts (4,1): Cannot find name '翻訳先の言語'.
  • test.ts (5,1): Cannot find name '翻訳するテキスト'.

メッセージを削除したユーザーを取得するサンプル

メッセージを削除したユーザーを取得するサンプル

client.on('messageDelete', async message => {
  if (!message.guild) return // メッセージが送信された場所がサーバーでなければ処理しない。

  const log = (await message.guild.fetchAuditLogs({ type: 'MESSAGE_DELETE' })).entries.first() // サーバーの監査ログからメッセージが削除されたものだけを取得して、最新のものを取得する。
  if (!log) return // メッセージが削除されたログが無ければ処理しない。

  const executor = log.executor // これがメッセージを削除したユーザーのオブジェクトです。

  return message.channel.send(`${executor.tag}${message.author.tag}のメッセージを削除しました。`) // 削除されたメッセージがあったチャンネルにメッセージを削除したユーザーのタグとメッセージを送ったユーザのタグを送信
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("messageDelete", async (message) => {
    if (!message.guild)
        return; // メッセージが送信された場所がサーバーでなければ処理しない。
    const log = (await message.guild.fetchAuditLogs({ type: "MESSAGE_DELETE" })).entries.first(); // サーバーの監査ログからメッセージが削除されたものだけを取得して、最新のものを取得する。
    if (!log)
        return; // メッセージが削除されたログが無ければ処理しない。
    const executor = log.executor; // これがメッセージを削除したユーザーのオブジェクトです。
    return message.channel.send(`${executor.tag}${message.author.tag}のメッセージを削除しました。`); // 削除されたメッセージがあったチャンネルにメッセージを削除したユーザーのタグとメッセージを送ったユーザのタグを送信
});
  • test.ts (5,1): No overload matches this call. Overload 1 of 2, '(event: "messageDelete", listener: (message: Message | PartialMessage) => Awaited): Client', gave the following error. Argument of type '(message: Message | PartialMessage) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message | PartialMessage) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (12,36): Object is possibly 'null'.
  • test.ts (12,52): Object is possibly 'null'.

.target
target;
  • test.ts (2,1): Cannot find name 'target'.

Discord 上でドロップされたファイルの中身を取り出すサンプル

Discord 上でドロップされたファイルの中身を取り出すサンプル

const Discord = require("discord.js");
const client = new Discord.Client();
const fetch = require("node-fetch");

client.on("message", async message => {
  if (message.content.startsWith("!file")) {
    if (message.attachments.size) {
      const fileURL = message.attachments.first().url;
      const responce = await fetch(fileURL);
      const body = await responce.text();
      message.channel.send(body);
    } else {
      message.reply("ファイルをドロップしてね!");
    }
  }
});
import * as Discord from "discord.js";
const client = new Discord.Client();
import * as fetch from "node-fetch";
client.on("message", async (message) => {
    if (message.content.startsWith("!file")) {
        if (message.attachments.size) {
            const fileURL = message.attachments.first().url;
            const responce = await fetch(fileURL);
            const body = await responce.text();
            message.channel.send(body);
        }
        else {
            message.reply("\u30D5\u30A1\u30A4\u30EB\u3092\u30C9\u30ED\u30C3\u30D7\u3057\u3066\u306D\uFF01");
        }
    }
});
  • sample.ts (3,16): Expected 1 arguments, but got 0.
  • sample.ts (4,24): Could not find a declaration file for module 'node-fetch'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/node-fetch/lib/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/node-fetch if it exists or add a new declaration (.d.ts) file containing declare module 'node-fetch';
  • sample.ts (8,29): Object is possibly 'undefined'.
  • used message Event

await
await;
  • test.ts (2,1): Cannot find name 'await'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

メンションでメンバーを指定してキックするコマンドのサンプル

メンションでメンバーを指定してキックするコマンドのサンプル

client.on('message', async message => {
  if (message.content.startsWith('!kick') && message.guild) {
  	if (message.mentions.members.size !== 1)
  	 return message.channel.send('キックするメンバーを1人指定してください')
    const member = message.mentions.members.first()
    if (!member.kickable) return message.channel.send('このユーザーをキックすることができません')
    
    await member.kick()
    
    message.channel.send(`${member.user.tag}をキックしました`)
  }
}
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    if (message.content.startsWith("!kick") && message.guild) {
        if (message.mentions.members.size !== 1)
            return message.channel.send("\u30AD\u30C3\u30AF\u3059\u308B\u30E1\u30F3\u30D0\u30FC\u30921\u4EBA\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
        const member = message.mentions.members.first();
        if (!member.kickable)
            return message.channel.send("\u3053\u306E\u30E6\u30FC\u30B6\u30FC\u3092\u30AD\u30C3\u30AF\u3059\u308B\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093");
        await member.kick();
        message.channel.send(`${member.user.tag}をキックしました`);
    }
});
  • test.ts (6,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (8,13): Object is possibly 'null'.
  • test.ts (10,24): Object is possibly 'null'.
  • test.ts (11,14): Object is possibly 'undefined'.
  • test.ts (13,15): Object is possibly 'undefined'.
  • test.ts (14,33): Object is possibly 'undefined'.
  • used message Event

メンバーに役職を追加、削除したい

メンバーに役職を追加、削除したい

const role = message.guild.roles.cache.find(role => role.name === 'メンバー')
message.member.roles.add(role)
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
const role = message.guild.roles.cache.find(role => role.name === "\u30E1\u30F3\u30D0\u30FC");
message.member.roles.add(role);
  • test.ts (5,14): Object is possibly 'null'.
  • test.ts (6,1): Object is possibly 'null'.
  • test.ts (6,26): Argument of type 'Role | undefined' is not assignable to parameter of type 'Collection<${bigint}, Role> | RoleResolvable | readonly RoleResolvable[]'. Type 'undefined' is not assignable to type 'Collection<${bigint}, Role> | RoleResolvable | readonly RoleResolvable[]'.

message.member.roles.add('690791160024924191')
declare var message: import("discord.js").Message;
declare var member: import("discord.js").GuildMember;
message.member.roles.add("690791160024924191");
  • test.ts (4,1): Object is possibly 'null'.

member.roles.add(role)
declare var member: import("discord.js").GuildMember;
member.roles.add(role);
  • test.ts (3,18): Cannot find name 'role'.

member.roles.remove(role)
declare var member: import("discord.js").GuildMember;
member.roles.remove(role);
  • test.ts (3,21): Cannot find name 'role'.

roles
roles;
  • test.ts (2,1): Cannot find name 'roles'.

add
add;
  • test.ts (2,1): Cannot find name 'add'.

remove
remove;
  • test.ts (2,1): Cannot find name 'remove'.

member.addRole()
declare var member: import("discord.js").GuildMember;
member.addRole();
  • test.ts (3,8): Property 'addRole' does not exist on type 'GuildMember'.

member.addRoles()
declare var member: import("discord.js").GuildMember;
member.addRoles();
  • test.ts (3,8): Property 'addRoles' does not exist on type 'GuildMember'.

member.removeRole()
declare var member: import("discord.js").GuildMember;
member.removeRole();
  • test.ts (3,8): Property 'removeRole' does not exist on type 'GuildMember'.

member.removeRoles()
declare var member: import("discord.js").GuildMember;
member.removeRoles();
  • test.ts (3,8): Property 'removeRoles' does not exist on type 'GuildMember'.

サーバーのアイコンを取得する

サーバーのアイコンを取得する

guild.iconURL()
declare var guild: import("discord.js").Guild;
guild.iconURL();

字数制限を超えないように文字列を複数に分割する

字数制限を超えないように文字列を複数に分割する

const Discord = require('discord.js')

console.log(Discord.Util.splitMessage('長い文字列'))
import * as Discord from "discord.js";
console.log(Discord.Util.splitMessage("\u9577\u3044\u6587\u5B57\u5217"));

split: true
split: true;

字数制限を超えないように分けてメッセージを送信する

字数制限を超えないように分けてメッセージを送信する

message.channel.send('2000字を超える文字列', { split: true })
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.send("2000\u5B57\u3092\u8D85\u3048\u308B\u6587\u5B57\u5217", { split: true });
  • test.ts (4,78): Expected 1 arguments, but got 2.

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

split
split;
  • test.ts (2,1): Cannot find name 'split'.

char: ''
char: "";

channel.send(text, { split: { char: '' } })
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.send(text, { split: { char: "" } });
  • test.ts (3,14): Cannot find name 'text'. Did you mean 'Text'?
  • test.ts (3,20): Expected 1 arguments, but got 2.

prepend
prepend;
  • test.ts (2,1): Cannot find name 'prepend'.

append
append;
  • test.ts (2,1): Cannot find name 'append'.

maxLength
maxLength;
  • test.ts (2,1): Cannot find name 'maxLength'.

なぜ配列やオブジェクトじゃなくて、Collectionが必要なのか

なぜ配列やオブジェクトじゃなくて、Collectionが必要なのか

[{ id: 'a' }, { id: 'b' }, { id: 'c' }]
[{ id: "a" }, { id: "b" }, { id: "c" }];

{ a: {}, b: {}, c: {} }
{
    a: { }
    b: { }
    c: { }
}

// 配列の場合
[{ id: 'a' }, { id: 'b' }, { id: 'c' }].filter(e => e.id !== 'b')
// オブジェクトの場合
Object.fromEntries(Object.entries({ a: {}, b: {}, c: {} }).filter(e => e[0] !== 'b'))
// 配列の場合
[{ id: "a" }, { id: "b" }, { id: "c" }].filter(e => e.id !== "b");
// オブジェクトの場合
Object.fromEntries(Object.entries({ a: {}, b: {}, c: {} }).filter(e => e[0] !== "b"));

obj.a
obj.a;
  • test.ts (2,1): Cannot find name 'obj'.

b
b;
  • test.ts (2,1): Cannot find name 'b'.

a
a;
  • test.ts (2,1): Cannot find name 'a'.

c
c;
  • test.ts (2,1): Cannot find name 'c'.

指定した時刻ごとに処理を実行したい

指定した時刻ごとに処理を実行したい

const cron = require('node-cron')

cron.schedule('0 * * * *', () => {
  console.log('0分だよ')
})
import * as cron from "node-cron";
cron.schedule("0 * * * *", () => {
    console.log("0\u5206\u3060\u3088");
});
  • test.ts (2,23): Cannot find module 'node-cron' or its corresponding type declarations.

node-cron
node - cron;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (2,8): Cannot find name 'cron'.

npm install node-cron
npm;
install;
node - cron;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'install'.
  • test.ts (4,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (4,8): Cannot find name 'cron'.

yarn add node-cron
yarn;
add;
node - cron;
  • test.ts (2,1): Cannot find name 'yarn'.
  • test.ts (3,1): Cannot find name 'add'.
  • test.ts (4,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (4,8): Cannot find name 'cron'.

* * * * *
    *  *  *  *  * ;
  • test.ts (2,2): Expression expected.
  • test.ts (2,5): Expression expected.
  • test.ts (2,8): Expression expected.
  • test.ts (2,11): Expression expected.
  • test.ts (2,14): Expression expected.
  • test.ts (2,16): Expression expected.

30 * * * * *
30 *  *  *  *  * ;
  • test.ts (2,7): Expression expected.
  • test.ts (2,10): Expression expected.
  • test.ts (2,13): Expression expected.
  • test.ts (2,16): Expression expected.
  • test.ts (2,18): Expression expected.

0,30
0, 30;
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.

*
    * ;
  • test.ts (2,2): Expression expected.
  • test.ts (2,4): Expression expected.

リアクションされたら役職を付与するサンプル

リアクションされたら役職を付与するサンプル

client.on('messageReactionAdd', async (reaction, user) => {
  const message = reaction.message
  const member = message.guild.member(user)
  if (reaction.emoji.name === '✅') {
    const role = message.guild.roles.cache.find(role => role.name === 'member')
    member.roles.add(role)
  }
})
declare var client: import("discord.js").Client;
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
client.on("messageReactionAdd", async (reaction, user) => {
    const message = reaction.message;
    const member = message.guild.member(user);
    if (reaction.emoji.name === "\u2705") {
        const role = message.guild.roles.cache.find(role => role.name === "member");
        member.roles.add(role);
    }
});
  • test.ts (8,20): Object is possibly 'null'.
  • test.ts (8,34): Property 'member' does not exist on type 'Guild'. Did you mean 'members'?
  • test.ts (10,22): Object is possibly 'null'.

サーバーに居るメンバー全員に特定の役職を与えるサンプル

サーバーに居るメンバー全員に特定の役職を与えるサンプル

const { Client } = require('discord.js')
const client = new Client()

client.on('message', message => {
  if (!message.guild) return // サーバーでない場合は無視
  
  if (message.content === '!add-role-all-members') { // メッセージの内容が「!add-role-all-members」だったら
    message.guild.members.fetch() // メンバーを全員取得
      .then(members => Promise.all(members.map(member => member.roles.add('役職ID')))) // 全員に同じ役職を与える
      .catch(console.error)
  }
})
import { Client } from "discord.js";
const client = new Client();
client.on("message", message => {
    if (!message.guild)
        return; // サーバーでない場合は無視
    if (message.content === "!add-role-all-members") { // メッセージの内容が「!add-role-all-members」だったら
        message.guild.members.fetch() // メンバーを全員取得
            .then(members => Promise.all(members.map(member => member.roles.add("\u5F79\u8077ID")))) // 全員に同じ役職を与える
            .catch(console.error);
    }
});
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (9,81): Argument of type '"役職ID"' is not assignable to parameter of type 'Collection<${bigint}, Role> | RoleResolvable | readonly RoleResolvable[]'.
  • used message Event

guild.members.fetch()
declare var guild: import("discord.js").Guild;
guild.members.fetch();

Promise<Collection<Snowflake, GuildMember>>
Promise<Collection<Snowflake, GuildMember>>();
  • test.ts (2,1): Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?
  • test.ts (2,9): Cannot find name 'Collection'.
  • test.ts (2,20): Cannot find name 'Snowflake'.
  • test.ts (2,31): Cannot find name 'GuildMember'.

member.roles.add(/* 役職のID または Role オブジェクト */)
declare var member: import("discord.js").GuildMember;
member.roles.add( /* 役職のID または Role オブジェクト */);
  • test.ts (3,14): Expected 1-2 arguments, but got 0.

リアクションを付ける速度を少し上げる

リアクションを付ける速度を少し上げる

const { Client } = require("discord.js")
const client = new Client({
  restTimeOffset: 100
})
import { Client } from "discord.js";
const client = new Client({
    restTimeOffset: 100
});
  • test.ts (3,27): Argument of type '{ restTimeOffset: number; }' is not assignable to parameter of type 'ClientOptions'. Property 'intents' is missing in type '{ restTimeOffset: number; }' but required in type 'ClientOptions'.

restTimeOffset
restTimeOffset;
  • test.ts (2,1): Cannot find name 'restTimeOffset'.

GUILD_UPDATE イベントが起きたときに起きることメモ

GUILD_UPDATE イベントが起きたときに起きることメモ

_clone() {
  return Object.assign(Object.create(this), this);
}

// _patch は Guild でオーバーライドされていることに注意されたい
_patch(data) {
  return data;
}

_update(data) {
  const clone = this._clone();
  this._patch(data);
  return clone;
}
_clone();
{
    return Object.assign(Object.create(this), this);
}
// _patch は Guild でオーバーライドされていることに注意されたい
_patch(data);
{
    return data;
}
_update(data);
{
    const clone = this._clone();
    this._patch(data);
    return clone;
}
  • test.ts (2,1): Cannot find name '_clone'.
  • test.ts (4,5): A 'return' statement can only be used within a function body.
  • test.ts (7,1): Cannot find name '_patch'.
  • test.ts (7,8): Cannot find name 'data'.
  • test.ts (9,5): A 'return' statement can only be used within a function body.
  • test.ts (11,1): Cannot find name '_update'.
  • test.ts (11,9): Cannot find name 'data'.
  • test.ts (13,24): Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
  • test.ts (14,10): Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
  • test.ts (14,17): Cannot find name 'data'.
  • test.ts (15,5): A 'return' statement can only be used within a function body.

.partial
partial;
  • test.ts (2,1): Cannot find name 'partial'.

guild._patch()
declare var guild: import("discord.js").Guild;
guild._patch();
  • test.ts (3,7): Property '_patch' does not exist on type 'Guild'.

keyvでデータを保存するサンプル

keyvでデータを保存するサンプル

const Keyv = require('keyv')

// 保存したいデータごとにtableを変えて作る
const levels = new Keyv('sqlite://db.sqlite', { table: 'levels' })
const prefixes = new Keyv('sqlite://db.sqlite', { table: 'prefixes' })

levels.on('error', err => console.error('Keyv connection error:', err))

!(async () => {
  await levels.set('1234', { point: 5, level: 1 })
  await prefixes.set('1234', '!')

  const level = await levels.get('1234')
  console.log(level) // { point: 5, level: 1 }

  const prefix = await prefixes.get('1234')
  console.log(prefix) // '!'
})()
import * as Keyv from "keyv";
// 保存したいデータごとにtableを変えて作る
const levels = new Keyv("sqlite://db.sqlite", { table: "levels" });
const prefixes = new Keyv("sqlite://db.sqlite", { table: "prefixes" });
levels.on("error", err => console.error("Keyv connection error:", err));
!(async () => {
    await levels.set("1234", { point: 5, level: 1 });
    await prefixes.set("1234", "!");
    const level = await levels.get("1234");
    console.log(level); // { point: 5, level: 1 }
    const prefix = await prefixes.get("1234");
    console.log(prefix); // '!'
})();
  • test.ts (2,23): Cannot find module 'keyv' or its corresponding type declarations.
  • test.ts (6,20): Parameter 'err' implicitly has an 'any' type.

npm install keyv @keyv/sqlite
npm;
install;
keyv;
/sqlite;;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'install'.
  • test.ts (4,1): Cannot find name 'keyv'.
  • test.ts (5,2): Unterminated regular expression literal.

指定したユーザーにメッセージ (DM) を送信する

指定したユーザーにメッセージ (DM) を送信する

client.users.cache.get('ユーザーのID').send('メッセージ')
declare var client: import("discord.js").Client;
client.users.cache.get("\u30E6\u30FC\u30B6\u30FC\u306EID").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,24): Argument of type '"ユーザーのID"' is not assignable to parameter of type '${bigint}'.

client.users.get('ユーザーのID').send('メッセージ')
declare var client: import("discord.js").Client;
client.users.get("\u30E6\u30FC\u30B6\u30FC\u306EID").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,14): Property 'get' does not exist on type 'UserManager'.

client.users.cache
declare var client: import("discord.js").Client;
client.users.cache;

.get('ユーザーのID')
get("\u30E6\u30FC\u30B6\u30FC\u306EID");
  • test.ts (2,1): Cannot find name 'get'.

.get('ユーザーのID')
get("\u30E6\u30FC\u30B6\u30FC\u306EID");
  • test.ts (2,1): Cannot find name 'get'.

undefined
undefined;

TypeError: Cannot read property 'send' of undefined
TypeError: Cannot;
read;
property;
"send";
of;
undefined;
  • test.ts (2,12): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'read'.
  • test.ts (4,1): Cannot find name 'property'.
  • test.ts (6,1): Cannot find name 'of'.

ミリ秒をもっと楽に分かりやすく書く

ミリ秒をもっと楽に分かりやすく書く

const ms = require('ms')

// ミリ秒で数値が返ってくる。
// 出力: 1000
console.log(ms('1s'))

// 10秒後に実行
setInterval(() => console.log('10秒後やぞ'), ms('10s'))

// 3分後に実行
setInterval(() => console.log('3分後やぞ'), ms('3m'))

// 1時間後に実行
setInterval(() => console.log('1時間後やぞ'), ms('1h'))
import * as ms from "ms";
// ミリ秒で数値が返ってくる。
// 出力: 1000
console.log(ms("1s"));
// 10秒後に実行
setInterval(() => console.log("10\u79D2\u5F8C\u3084\u305E"), ms("10s"));
// 3分後に実行
setInterval(() => console.log("3\u5206\u5F8C\u3084\u305E"), ms("3m"));
// 1時間後に実行
setInterval(() => console.log("1\u6642\u9593\u5F8C\u3084\u305E"), ms("1h"));
  • test.ts (2,21): Could not find a declaration file for module 'ms'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/ms/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/ms if it exists or add a new declaration (.d.ts) file containing declare module 'ms';

const ms = require('ms')

// 出力: 1s
console.log(ms(1000))

// もっと分かりやすくしたい場合は long オプションを使おう!
// 出力: 1 second
console.log(ms(1000, { long: true }))
import * as ms from "ms";
// 出力: 1s
console.log(ms(1000));
// もっと分かりやすくしたい場合は long オプションを使おう!
// 出力: 1 second
console.log(ms(1000, { long: true }));
  • test.ts (2,21): Could not find a declaration file for module 'ms'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/ms/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/ms if it exists or add a new declaration (.d.ts) file containing declare module 'ms';

const ms = require('ms')

const threeMins = 3

// 出力: 60000
console.log(ms(threeMins + 'm'))

// ここでは m だが s や h と書き換えると一時間後に実行できたり一秒後に実行できる。
setTimeout(() => console.log('3分後!'), ms(threeMins + 'm'))
import * as ms from "ms";
const threeMins = 3;
// 出力: 60000
console.log(ms(threeMins + "m"));
// ここでは m だが s や h と書き換えると一時間後に実行できたり一秒後に実行できる。
setTimeout(() => console.log("3\u5206\u5F8C!"), ms(threeMins + "m"));
  • test.ts (2,21): Could not find a declaration file for module 'ms'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/ms/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/ms if it exists or add a new declaration (.d.ts) file containing declare module 'ms';

const ms = require('ms')

// 10分(秒単位)
const tenMins = 600

// 出力: 10m
console.log(ms(ms(tenMins + 's')))
import * as ms from "ms";
// 10分(秒単位)
const tenMins = 600;
// 出力: 10m
console.log(ms(ms(tenMins + "s")));
  • test.ts (2,21): Could not find a declaration file for module 'ms'. 'D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/ms/index.js' implicitly has an 'any' type. Try npm i --save-dev @types/ms if it exists or add a new declaration (.d.ts) file containing declare module 'ms';

1y
1;
y;
  • test.ts (3,1): Cannot find name 'y'.

1d
1;
d;
  • test.ts (3,1): Cannot find name 'd'.

1w
1;
w;
  • test.ts (3,1): Cannot find name 'w'.

1.3m
1.3;
m;
  • test.ts (3,1): Cannot find name 'm'.

1.3m
1.3;
m;
  • test.ts (3,1): Cannot find name 'm'.

1m
1;
m;
  • test.ts (3,1): Cannot find name 'm'.

3
3;

メッセージを選択して一括削除するサンプル

メッセージを選択して一括削除するサンプル

client.on('message', async message => {
  // !purge コマンドが実行されたら
  if (message.content === '!purge') {
    // コマンドが送信されたチャンネルから直近100件(上限)メッセージを取得する
    const messages = await message.channel.messages.fetch({ limit: 100 })
    // ボット以外が送信したメッセージを抽出
    const filtered = messages.filter(message => !message.author.bot)
    // それらのメッセージを一括削除
    message.channel.bulkDelete(filtered)
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    // !purge コマンドが実行されたら
    if (message.content === "!purge") {
        // コマンドが送信されたチャンネルから直近100件(上限)メッセージを取得する
        const messages = await message.channel.messages.fetch({ limit: 100 });
        // ボット以外が送信したメッセージを抽出
        const filtered = messages.filter(message => !message.author.bot);
        // それらのメッセージを一括削除
        message.channel.bulkDelete(filtered);
    }
});
  • test.ts (12,25): Property 'bulkDelete' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'bulkDelete' does not exist on type 'DMChannel'.
  • used message Event

サーバーからBANされたユーザーの一覧を表示するサンプル

サーバーからBANされたユーザーの一覧を表示するサンプル

client.on('message', async message => {
  if (message.content === '!bans' && message.guild) {
    const bans = await message.guild.fetchBans()
    message.channel.send(bans.map(ban => ban.user.tag).join(', ') || 'none')
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    if (message.content === "!bans" && message.guild) {
        const bans = await message.guild.fetchBans();
        message.channel.send(bans.map(ban => ban.user.tag).join(", ") || "none");
    }
});
  • test.ts (8,42): Property 'fetchBans' does not exist on type 'Guild'.
  • test.ts (9,39): Parameter 'ban' implicitly has an 'any' type.
  • used message Event

「令和〇〇年〇〇月〇〇日」というメッセージを送信する

「令和〇〇年〇〇月〇〇日」というメッセージを送信する

client.on('message', message => {
  if (message.content === 'now') {
    // 現在時刻をフォーマット
    const date = Intl.DataTimeFormat('ja-JP-u-ca-japanese', { era: 'long' }).format(Date.now())

    message.reply(date)
  }
})
declare var client: import("discord.js").Client;
client.on("message", message => {
    if (message.content === "now") {
        // 現在時刻をフォーマット
        const date = Intl.DataTimeFormat("ja-JP-u-ca-japanese", { era: "long" }).format(Date.now());
        message.reply(date);
    }
});
  • test.ts (6,27): Property 'DataTimeFormat' does not exist on type 'typeof Intl'. Did you mean 'DateTimeFormat'?
  • used message Event

Intl
Intl;

DateTimeFormat
DateTimeFormat;
  • test.ts (2,1): Cannot find name 'DateTimeFormat'.

Date
Date;

Number
Number;

元号-〇〇年〇〇月〇〇日
元号 - 〇〇年〇〇月〇〇日;
  • test.ts (2,1): Cannot find name '元号'.
  • test.ts (2,6): Cannot find name '〇〇年〇〇月〇〇日'.

サーバーからアクティブではないメンバーを全てキックする

サーバーからアクティブではないメンバーを全てキックする

message.guild.members.prune()
  .then(pruned => console.log(`This will prune ${pruned} people!`))
  .catch(console.error);
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.members.prune()
    .then(pruned => console.log(`This will prune ${pruned} people!`))
    .catch(console.error);
  • test.ts (4,1): Object is possibly 'null'.

days
days;
  • test.ts (2,1): Cannot find name 'days'.

dry: ture
dry: ture;
  • test.ts (2,6): Cannot find name 'ture'.

今日の曜日が取得したい

今日の曜日が取得したい

  const week = ['日', '月', '火', '水', '木', '金', '土']
  const date = new Date()
  const day = date.getDay()
  
  console.log('きょうは ' + week[day] + ' ようび')
const week = ["\u65E5", "\u6708", "\u706B", "\u6C34", "\u6728", "\u91D1", "\u571F"];
const date = new Date();
const day = date.getDay();
console.log("\u304D\u3087\u3046\u306F\u3000" + week[day] + "\u3000\u3088\u3046\u3073");

week
week;
  • test.ts (2,1): Cannot find name 'week'.

new Date()
new Date();

new Date().getDay()
new Date().getDay();

week[day]
week[day];
  • test.ts (2,1): Cannot find name 'week'.
  • test.ts (2,6): Cannot find name 'day'.

サーバーの招待を全て取得する

サーバーの招待を全て取得する

const Discord = require('discord.js')
const client = new Discord.Client()

client.on('message', async message => {
  if (message.content === '!invites') {
    const invites = await message.guild.fetchInvites()
    console.log(invites.map(invite => invite.url))
  }
})
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", async (message) => {
    if (message.content === "!invites") {
        const invites = await message.guild.fetchInvites();
        console.log(invites.map(invite => invite.url));
    }
});
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (6,31): Object is possibly 'null'.
  • test.ts (6,45): Property 'fetchInvites' does not exist on type 'Guild'.
  • test.ts (7,33): Parameter 'invite' implicitly has an 'any' type.
  • used message Event

招待を作成する

招待を作成する

const invite = await message.channel.createInvite()
message.channel.send(invite.url)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const invite = await message.channel.createInvite();
message.channel.send(invite.url);
  • test.ts (4,16): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (4,16): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (4,38): Property 'createInvite' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'createInvite' does not exist on type 'DMChannel'.

.createInvite()
createInvite();
  • test.ts (2,1): Cannot find name 'createInvite'.

状態を記憶する

状態を記憶する

let foo = 0
foo += 1
console.log(foo) // 1
let foo = 0;
foo += 1;
console.log(foo); // 1

client.on('message', message => {
  let count = 0
  count += 1
})
declare var client: import("discord.js").Client;
client.on("message", message => {
    let count = 0;
    count += 1;
});
  • used message Event

let count = 0

client.on('message', message => {
  count += 1
})
declare var client: import("discord.js").Client;
let count = 0;
client.on("message", message => {
    count += 1;
});
  • used message Event

let const
let;
const ;
  • test.ts (2,1): Identifier expected. 'let' is a reserved word in strict mode.
  • test.ts (2,1): Cannot find name 'let'.
  • test.ts (3,6): Variable declaration list cannot be empty.

コマンドでping値を返信するサンプル

コマンドでping値を返信するサンプル

client.on('message', message => {
  if (message.content === '!ping') {
    message.reply(client.ws.ping)
  }
})
declare var client: import("discord.js").Client;
client.on("message", message => {
    if (message.content === "!ping") {
        message.reply(client.ws.ping);
    }
});
  • test.ts (5,23): Argument of type 'number' is not assignable to parameter of type 'string | MessagePayload | ReplyMessageOptions'.
  • used message Event

Mapを活用する

Mapを活用する

const data = new Map()

// setでキーと値を指定して保存する
data.set('foo', 1)
// オブジェクトや配列など、任意の値を入れることができる
data.set('bar', { baz: 1 })

// getでキーを元に保存した値を取得する
console.log(data.get('foo')) // 1
console.log(data.get('bar')) // { baz: 1 }

// deleteでキーを元に値を削除できる
data.delete('foo')
console.log(data.get('foo')) // undefined
const data = new Map();
// setでキーと値を指定して保存する
data.set("foo", 1);
// オブジェクトや配列など、任意の値を入れることができる
data.set("bar", { baz: 1 });
// getでキーを元に保存した値を取得する
console.log(data.get("foo")); // 1
console.log(data.get("bar")); // { baz: 1 }
// deleteでキーを元に値を削除できる
data.delete("foo");
console.log(data.get("foo")); // undefined

// JSONからデータを読み込む(jsonは保存したもの)
const data = new Map(JSON.parse(json))

// Mapからデータを抽出(これを保存する)
JSON.stringify([...data])
// JSONからデータを読み込む(jsonは保存したもの)
const data = new Map(JSON.parse(json));
// Mapからデータを抽出(これを保存する)
JSON.stringify([...data]);
  • test.ts (3,33): Cannot find name 'json'. Did you mean 'JSON'?

.set()
set();
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

.delete()
delete ();
  • test.ts (2,9): The operand of a 'delete' operator must be a property reference.
  • test.ts (2,9): Expression expected.

タイピング表示が出たら、ボット自身もタイピング表示を出すサンプル

タイピング表示が出たら、ボット自身もタイピング表示を出すサンプル

client.on('typingStart', channel => {
  if (channel.id !== 'タイピング表示を検知するチャンネルID') return
  const target = client.channels.cache.get('タイピング表示を出すチャンネルID')
  target.startTyping()
  setTimeout(() => target.stopTyping(), 9 * 1000)
})
declare var client: import("discord.js").Client;
client.on("typingStart", channel => {
    if (channel.id !== "\u30BF\u30A4\u30D4\u30F3\u30B0\u8868\u793A\u3092\u691C\u77E5\u3059\u308B\u30C1\u30E3\u30F3\u30CD\u30EBID")
        return;
    const target = client.channels.cache.get("\u30BF\u30A4\u30D4\u30F3\u30B0\u8868\u793A\u3092\u51FA\u3059\u30C1\u30E3\u30F3\u30CD\u30EBID");
    target.startTyping();
    setTimeout(() => target.stopTyping(), 9 * 1000);
});
  • test.ts (6,46): Argument of type '"タイピング表示を出すチャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (7,5): Object is possibly 'undefined'.
  • test.ts (7,12): Property 'startTyping' does not exist on type 'Channel'.
  • test.ts (8,22): Object is possibly 'undefined'.
  • test.ts (8,29): Property 'stopTyping' does not exist on type 'Channel'.

typingStop
typingStop;
  • test.ts (2,1): Cannot find name 'typingStop'.

タイマーコマンドのサンプル

タイマーコマンドのサンプル

const prefix = '!'

client.on('message', message => {
  if (!message.content.startsWith(prefix)) return
  const [command, ...args] = message.content.slice(prefix.length).split(' ')

  if (command === 'timer') {
    // 引数から待ち時間を取り出す
    const seconds = Number(args[0])
    message.channel.send(`タイマーを${seconds}秒に設定しました。`)
    setTimeout(() => {
      message.reply(`${seconds}秒経ちました`)
    }, seconds * 1000) // setTimeoutに指定するのはミリ秒なので秒数に1000を掛ける
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const prefix = "!";
client.on("message", message => {
    if (!message.content.startsWith(prefix))
        return;
    const [command, ...args] = message.content.slice(prefix.length).split(" ");
    if (command === "timer") {
        // 引数から待ち時間を取り出す
        const seconds = Number(args[0]);
        message.channel.send(`タイマーを${seconds}秒に設定しました。`);
        setTimeout(() => {
            message.reply(`${seconds}秒経ちました`);
        }, seconds * 1000); // setTimeoutに指定するのはミリ秒なので秒数に1000を掛ける
    }
});
  • used message Event

!timer 10
!timer;
10;
  • test.ts (2,2): Cannot find name 'timer'.

特定の役職を持っているメンバーを取得する

特定の役職を持っているメンバーを取得する

const role = message.guild.roles.cache.get('役職ID')
message.channel.send(`役職 ${role.name} を持っているメンバー数: ${role.members.size}`)
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const role = message.guild.roles.cache.get("\u5F79\u8077ID");
message.channel.send(`役職 ${role.name} を持っているメンバー数: ${role.members.size}`);
  • test.ts (5,14): Object is possibly 'null'.
  • test.ts (5,44): Argument of type '"役職ID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (6,28): Object is possibly 'undefined'.
  • test.ts (6,54): Object is possibly 'undefined'.

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

簡易的なレベルシステムのサンプル

簡易的なレベルシステムのサンプル

const Discord = require('discord.js');
const client = new Discord.Client();
const Keyv = require('keyv');
const levels = new Keyv('sqlite://db.sqlite', { table: 'levels' });

client.on('message', async (message) => {
  // ボットは除外する
  if (message.author.bot) return;

  // ユーザーのレベルを取得する。なければ{ count: 0, level: 0 }にする
  const level = (await levels.get(message.author.id)) || { count: 0, level: 0 };

  // カウントを1増やす
  level.count += 1;
  // カウントが100になったら0にして、レベルを1増やす
  if (level.count >= 100) {
    level.count = 0;
    level.level += 1;
  }

  // ユーザーのレベルを保存する
  levels.set(message.author.id, level);

  // !levelコマンドで現在のレベルを出す
  if (message.content === '!level') {
    message.channel.send(
      `現在のレベルは ${level.level} です。次のレベルまであと ${
        100 - level.count
      } メッセージ`
    );
  }
});

client.login('TOKEN');
import * as Discord from "discord.js";
const client = new Discord.Client();
import * as Keyv from "keyv";
const levels = new Keyv("sqlite://db.sqlite", { table: "levels" });
client.on("message", async (message) => {
    // ボットは除外する
    if (message.author.bot)
        return;
    // ユーザーのレベルを取得する。なければ{ count: 0, level: 0 }にする
    const level = (await levels.get(message.author.id)) || { count: 0, level: 0 };
    // カウントを1増やす
    level.count += 1;
    // カウントが100になったら0にして、レベルを1増やす
    if (level.count >= 100) {
        level.count = 0;
        level.level += 1;
    }
    // ユーザーのレベルを保存する
    levels.set(message.author.id, level);
    // !levelコマンドで現在のレベルを出す
    if (message.content === "!level") {
        message.channel.send(`現在のレベルは ${level.level} です。次のレベルまであと ${100 - level.count} メッセージ`);
    }
});
client.login("TOKEN");
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (4,23): Cannot find module 'keyv' or its corresponding type declarations.
  • used message Event

keyv
keyv;
  • test.ts (2,1): Cannot find name 'keyv'.

@keyv/sqlite
/sqlite;;
  • test.ts (2,2): Unterminated regular expression literal.

カテゴリ内にチャンネルを作成したい

カテゴリ内にチャンネルを作成したい

message.guild.channels.create('チャンネル名', { parent: message.channel.parent })
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.guild.channels.create("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D", { parent: message.channel.parent });
  • test.ts (5,1): Object is possibly 'null'.
  • test.ts (5,97): Property 'parent' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'parent' does not exist on type 'DMChannel'.

guild.createChannel('チャンネル名', { parent: category })
declare var guild: import("discord.js").Guild;
guild.createChannel("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D", { parent: category });
  • test.ts (3,7): Property 'createChannel' does not exist on type 'Guild'.
  • test.ts (3,71): Cannot find name 'category'.

guild.channels.create('チャンネル名', { parent: category })
declare var guild: import("discord.js").Guild;
guild.channels.create("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D", { parent: category });
  • test.ts (3,73): Cannot find name 'category'.

対象のメッセージの下にあるメッセージを取得する

対象のメッセージの下にあるメッセージを取得する

client.once('ready' async () => {
  const channel = await client.channels.fetch('対象のメッセージがあるチャンネルID')
  const afterMessages = await channel.messages.fetch({ after: '対象のメッセージID' })
  
  console.log(afterMessages
    .map(message => message.cleanContent)
    .join('\n'))
})
declare var client: import("discord.js").Client;
client.once("ready", async () => {
    const channel = await client.channels.fetch("\u5BFE\u8C61\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u3042\u308B\u30C1\u30E3\u30F3\u30CD\u30EBID");
    const afterMessages = await channel.messages.fetch({ after: "\u5BFE\u8C61\u306E\u30E1\u30C3\u30BB\u30FC\u30B8ID" });
    console.log(afterMessages
        .map(message => message.cleanContent)
        .join("\n"));
});
  • test.ts (4,49): Argument of type '"対象のメッセージがあるチャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (5,33): Object is possibly 'null'.
  • test.ts (5,41): Property 'messages' does not exist on type 'Channel'.
  • test.ts (7,14): Parameter 'message' implicitly has an 'any' type.

messages
messages;
  • test.ts (2,1): Cannot find name 'messages'. Did you mean 'onmessage'?

fetch
fetch;

after
after;
  • test.ts (2,1): Cannot find name 'after'.

after
after;
  • test.ts (2,1): Cannot find name 'after'.

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

1
1;

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

1
1;

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

1
1;

.first()
first();
  • test.ts (2,1): Cannot find name 'first'.

.last()
last();
  • test.ts (2,1): Cannot find name 'last'.

limit
limit;
  • test.ts (2,1): Cannot find name 'limit'.

catch
try { }
catch { }

ボットに「入力中...」と表示させたい

ボットに「入力中...」と表示させたい

message.channel.startTyping()
setTimeout(() => {
  message.channel.stopTyping()
  // message.reply('Hey!')
}, 1000)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.startTyping();
setTimeout(() => {
    message.channel.stopTyping();
    // message.reply('Hey!')
}, 1000);

const sleep = time => new Promise(resolve => setTimeout(resolve, time))

client.on('message', async message => {
  message.channel.startTyping()
  await sleep(1000)
  message.channel.stopTyping()
  message.reply('Hey!')
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
const sleep = time => new Promise(resolve => setTimeout(resolve, time));
client.on("message", async (message) => {
    message.channel.startTyping();
    await sleep(1000);
    message.channel.stopTyping();
    message.reply("Hey!");
});
  • test.ts (4,15): Parameter 'time' implicitly has an 'any' type.
  • used message Event

message.channel.startTyping()
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.startTyping();

message.channel.stopTyping()
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.stopTyping();

startTyping()
startTyping();
  • test.ts (2,1): Cannot find name 'startTyping'.

stopTyping()
stopTyping();
  • test.ts (2,1): Cannot find name 'stopTyping'.

void
void ;
  • test.ts (2,6): Expression expected.

msg.reply('~')
msg.reply("\uFF5E");
  • test.ts (2,1): Cannot find name 'msg'.

setTimeout()
setTimeout();
  • test.ts (2,1): Expected at least 1 arguments, but got 0.

startTyping()
startTyping();
  • test.ts (2,1): Cannot find name 'startTyping'.

await
await;
  • test.ts (2,1): Cannot find name 'await'.

デフォルトの画像フォーマットをwebpから変更するパッチ

デフォルトの画像フォーマットをwebpから変更するパッチ

const Discord = require('discord.js')
const client = new Discord.Client()

!(original => Discord.Constants.Endpoints.CDN = root => {
  const cdn = original(root)
  ![
    'Avatar', 'Banner', 'Icon', 'AppIcon', 'AppAsset',
    'GDMIcon','Splash', 'DiscoverySplash', 'TeamIcon'
  ].forEach(key => {
    const original = cdn[key]
    cdn[key] = (id, hash, _format, _size, _dynamic) => {
      if (typeof _format === 'object')
        return original(id, hash, { ..._format, format: 'jpg' })
      return original(id, hash, 'jpg', _size, _dynamic)
    }
  })
  return cdn
})(Discord.Constants.Endpoints.CDN)

client.on('ready', () => {
  // .jpgになっているはず
  console.log(client.user.displayAvatarURL())
})

client.login()
import * as Discord from "discord.js";
const client = new Discord.Client();
!(original => Discord.Constants.Endpoints.CDN = root => {
    const cdn = original(root);
    ![
        "Avatar",
        "Banner",
        "Icon",
        "AppIcon",
        "AppAsset",
        "GDMIcon",
        "Splash",
        "DiscoverySplash",
        "TeamIcon"
    ].forEach(key => {
        const original = cdn[key];
        cdn[key] = (id, hash, _format, _size, _dynamic) => {
            if (typeof _format === "object")
                return original(id, hash, { ..._format, format: "jpg" });
            return original(id, hash, "jpg", _size, _dynamic);
        };
    });
    return cdn;
})(Discord.Constants.Endpoints.CDN);
client.on("ready", () => {
    // .jpgになっているはず
    console.log(client.user.displayAvatarURL());
});
client.login();
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (6,6): An expression of type 'void' cannot be tested for truthiness.
  • test.ts (17,26): Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Asset: (name: string) => string; DefaultAvatar: (id: number | ${bigint}) => string; Emoji: (emojiId: ${bigint}, format: "png" | "gif") => string; Avatar: (userId: number | ${bigint}, hash: string, format: "default" | AllowedImageFormat, size: number) => string; ... 7 more ...; TeamIcon: (teamId: number | ${...'. No index signature with a parameter of type 'string' was found on type '{ Asset: (name: string) => string; DefaultAvatar: (id: number | ${bigint}) => string; Emoji: (emojiId: ${bigint}, format: "png" | "gif") => string; Avatar: (userId: number | ${bigint}, hash: string, format: "default" | AllowedImageFormat, size: number) => string; ... 7 more ...; TeamIcon: (teamId: number | ${...'.
  • test.ts (18,9): Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Asset: (name: string) => string; DefaultAvatar: (id: number | ${bigint}) => string; Emoji: (emojiId: ${bigint}, format: "png" | "gif") => string; Avatar: (userId: number | ${bigint}, hash: string, format: "default" | AllowedImageFormat, size: number) => string; ... 7 more ...; TeamIcon: (teamId: number | ${...'. No index signature with a parameter of type 'string' was found on type '{ Asset: (name: string) => string; DefaultAvatar: (id: number | ${bigint}) => string; Emoji: (emojiId: ${bigint}, format: "png" | "gif") => string; Avatar: (userId: number | ${bigint}, hash: string, format: "default" | AllowedImageFormat, size: number) => string; ... 7 more ...; TeamIcon: (teamId: number | ${...'.
  • test.ts (18,21): Parameter 'id' implicitly has an 'any' type.
  • test.ts (18,25): Parameter 'hash' implicitly has an 'any' type.
  • test.ts (18,31): Parameter '_format' implicitly has an 'any' type.
  • test.ts (18,40): Parameter '_size' implicitly has an 'any' type.
  • test.ts (18,47): Parameter '_dynamic' implicitly has an 'any' type.
  • test.ts (28,17): Object is possibly 'null'.

DiscordAPIErrorで完全なスタックトレースを表示するパッチ

DiscordAPIErrorで完全なスタックトレースを表示するパッチ

 DiscordAPIError: Missing Permissions
     at /index.js:16:19
     at processTicksAndRejections (internal/process/task_queues.js:97:5)
     at async command (/index.js:43:3)
     at async handler (/index.js:39:13) {
   method: 'delete',
   path: '/channels/706188750354645073',
   code: 50013,
   httpStatus: 403
 }
DiscordAPIError: Missing;
Permissions;
at / index.js;
16;
19;
at;
processTicksAndRejections(internal / process / task_queues.js, 97, 5);
at;
async;
command(/index.js:43:3), at, async, handler(/index.js, 39, 13);
{
    method, "delete", path, "/channels/706188750354645073", code, 50013, httpStatus, 403;
    ;
}
  • test.ts (2,18): Cannot find name 'Missing'.
  • test.ts (4,1): Cannot find name 'at'.
  • test.ts (4,6): Cannot find name 'index'.
  • test.ts (7,1): Cannot find name 'at'.
  • test.ts (8,1): Cannot find name 'processTicksAndRejections'.
  • test.ts (8,27): Cannot find name 'internal'.
  • test.ts (8,38): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (8,48): Cannot find name 'task_queues'.
  • test.ts (9,1): Cannot find name 'at'.
  • test.ts (10,1): Cannot find name 'async'.
  • test.ts (11,1): Cannot find name 'command'.
  • test.ts (11,52): Property 'js' does not exist on type 'RegExp'.
  • test.ts (11,54): ',' expected.
  • test.ts (11,57): ',' expected.
  • test.ts (11,62): ';' expected.
  • test.ts (11,63): Declaration or statement expected.
  • test.ts (11,65): Cannot find name 'method'.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,65): Left side of comma operator is unused and has no side effects.
  • test.ts (11,83): Cannot find name 'path'.
  • test.ts (11,121): Cannot find name 'code'.
  • test.ts (11,134): Cannot find name 'httpStatus'.
  • test.ts (11,149): ';' expected.
  • test.ts (11,150): Declaration or statement expected.
  • test.ts (12,1): '}' expected.

const Discord = require('discord.js')
const client = new Discord.Client()

// スタックトレースを補完するための処理
{
  const prototype = Object.getPrototypeOf(client.rest)
  const original = Object.getOwnPropertyDescriptor(prototype, 'api').get

  Object.defineProperty(prototype, 'api', {
    get() {
      const builder = original.apply(this)
      return new Proxy(builder, {
        get(target, name) {
          const result = Reflect.get(target, name)
          if (result.inspect) return new Proxy(result, this)
          return (...args) => result(...args).catch(err => {
            Error.captureStackTrace(err)
            throw err
          })
        },
        apply(target, _, args) {
          return new Proxy(Reflect.apply(target, _, args), this)
        }
      })
    }
  })
}

client.on('message', () => {
  // スタックトレースを出すために.catchでエラーを出力する
  handler().catch(err => console.error(err))
})

client.login()

// スタックトレースに表示させるための適当な関数
const handler = async () => {
  // エラーを伝播させるためにawaitする(それか.catchを書いてもいい)
  if (true) await command()
}

const command = async () => {
  // 上と同様のawaitする。試すときは権限エラーになるチャンネルIDに置き換える
  await client.channels.cache.get('706188750354645073').delete()
}
import * as Discord from "discord.js";
const client = new Discord.Client();
// スタックトレースを補完するための処理
{
    const prototype = Object.getPrototypeOf(client.rest);
    const original = Object.getOwnPropertyDescriptor(prototype, "api").get;
    Object.defineProperty(prototype, "api", {
        get() {
            const builder = original.apply(this);
            return new Proxy(builder, {
                get(target, name) {
                    const result = Reflect.get(target, name);
                    if (result.inspect)
                        return new Proxy(result, this);
                    return (...args) => result(...args).catch(err => {
                        Error.captureStackTrace(err);
                        throw err;
                    });
                },
                apply(target, _, args) {
                    return new Proxy(Reflect.apply(target, _, args), this);
                }
            });
        }
    });
}
client.on("message", () => {
    // スタックトレースを出すために.catchでエラーを出力する
    handler().catch(err => console.error(err));
});
client.login();
// スタックトレースに表示させるための適当な関数
const handler = async () => {
    // エラーを伝播させるためにawaitする(それか.catchを書いてもいい)
    if (true)
        await command();
};
const command = async () => {
    // 上と同様のawaitする。試すときは権限エラーになるチャンネルIDに置き換える
    await client.channels.cache.get("706188750354645073").delete();
};
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (6,52): Property 'rest' is private and only accessible within class 'BaseClient'.
  • test.ts (7,22): Object is possibly 'undefined'.
  • test.ts (10,29): Object is possibly 'undefined'.
  • test.ts (10,29): The 'this' context of type '(() => any) | undefined' is not assignable to method's 'this' of type '(this: any) => any'. Type 'undefined' is not assignable to type '(this: any) => any'.
  • test.ts (16,29): Rest parameter 'args' implicitly has an 'any[]' type.
  • test.ts (16,63): Parameter 'err' implicitly has an 'any' type.
  • test.ts (41,11): Object is possibly 'undefined'.
  • used message Event

index.js:16:19
index.js;
16;
19;
  • test.ts (2,1): Cannot find name 'index'.

quickcord

quickcord

const Quickcord = require('quickcord')
const client = new Quickcord.Client('DiscordBotToken', '.')

client.command('ping', (msg, args) => {
  msg.reply('pong')
})
import { Client } from "discord.js";
import * as Quickcord from "quickcord";
const client = new Quickcord.Client("DiscordBotToken", ".");
client.command("ping", (msg, args) => {
    msg.reply("pong");
});
  • test.ts (3,28): Cannot find module 'quickcord' or its corresponding type declarations.
  • test.ts (5,25): Parameter 'msg' implicitly has an 'any' type.
  • test.ts (5,30): Parameter 'args' implicitly has an 'any' type.

マルチスレッドで処理をするサンプル

マルチスレッドで処理をするサンプル

const workerpool = require('workerpool')
const pool = workerpool.pool('./worker.js')

!(async () => {
  // worker側で定義された"fib"関数に46を渡して実行する
  const result = await pool.exec('fib', [46])
    .catch(err => console.error(err))

  console.log('Result:', result)

  // workerを終了させる(ボットで使う場合は基本的に不要)
  pool.terminate()
})()
import * as workerpool from "workerpool";
const pool = workerpool.pool("./worker.js");
!(async () => {
    // worker側で定義された"fib"関数に46を渡して実行する
    const result = await pool.exec("fib", [46])
        .catch(err => console.error(err));
    console.log("Result:", result);
    // workerを終了させる(ボットで使う場合は基本的に不要)
    pool.terminate();
})();
  • main.ts (2,29): Cannot find module 'workerpool' or its corresponding type declarations.
  • main.ts (7,16): Parameter 'err' implicitly has an 'any' type.

const workerpool = require('workerpool')

function fib(n) {
  if (n < 2) return n
  return fib(n - 2) + fib(n - 1)
}

// fib関数を登録
workerpool.worker({ fib })
import * as workerpool from "workerpool";
function fib(n) {
    if (n < 2)
        return n;
    return fib(n - 2) + fib(n - 1);
}
// fib関数を登録
workerpool.worker({ fib });
  • worker.ts (2,29): Cannot find module 'workerpool' or its corresponding type declarations.
  • worker.ts (3,10): 'fib' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
  • worker.ts (3,14): Parameter 'n' implicitly has an 'any' type.

npm i workerpool
npm;
i;
workerpool;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'i'.
  • test.ts (4,1): Cannot find name 'workerpool'.

マルチスレッドで重い処理を実行するサンプル

マルチスレッドで重い処理を実行するサンプル

const workerpool = require('workerpool')
const kuromoji = require('kuromoji')

// 形態素解析をするための辞書を読み込む
kuromoji.builder({
  dicPath: 'node_modules/kuromoji/dict',
}).build((error, tokenizer) => {
  if (error) throw error

  // 文字列を受け取って形態素解析する関数を作成
  const tokenize = text => tokenizer.tokenize(text)

  // 関数を呼び出せるように公開する
  workerpool.worker({ tokenize })
})
import * as workerpool from "workerpool";
import * as kuromoji from "kuromoji";
// 形態素解析をするための辞書を読み込む
kuromoji.builder({
    dicPath: "node_modules/kuromoji/dict",
}).build((error, tokenizer) => {
    if (error)
        throw error;
    // 文字列を受け取って形態素解析する関数を作成
    const tokenize = text => tokenizer.tokenize(text);
    // 関数を呼び出せるように公開する
    workerpool.worker({ tokenize });
});
  • worker.ts (2,29): Cannot find module 'workerpool' or its corresponding type declarations.
  • worker.ts (3,27): Cannot find module 'kuromoji' or its corresponding type declarations.
  • worker.ts (7,11): Parameter 'error' implicitly has an 'any' type.
  • worker.ts (7,18): Parameter 'tokenizer' implicitly has an 'any' type.
  • worker.ts (11,22): Parameter 'text' implicitly has an 'any' type.

const Discord = require('discord.js')
const client = new Discord.Client()

const workerpool = require('workerpool')
// worker.jsを読み込む
const pool = workerpool.pool('./worker.js')

client.on('message', async message => {
  if (message.author.bot) return
  
  // worker.jsで公開したtokenize関数を別スレッドで実行する
  const tokens = await pool.exec('tokenize', [message.content])

  message.channel.send(tokens.map(token => token.surface_form).join(' '))
})

client.login()
import * as Discord from "discord.js";
const client = new Discord.Client();
import * as workerpool from "workerpool";
// worker.jsを読み込む
const pool = workerpool.pool("./worker.js");
client.on("message", async (message) => {
    if (message.author.bot)
        return;
    // worker.jsで公開したtokenize関数を別スレッドで実行する
    const tokens = await pool.exec("tokenize", [message.content]);
    message.channel.send(tokens.map(token => token.surface_form).join(" "));
});
client.login();
  • index.ts (3,16): Expected 1 arguments, but got 0.
  • index.ts (4,29): Cannot find module 'workerpool' or its corresponding type declarations.
  • index.ts (12,37): Parameter 'token' implicitly has an 'any' type.
  • used message Event

一定時間ごとに指定したチャンネルにメッセージを送信するサンプル

一定時間ごとに指定したチャンネルにメッセージを送信するサンプル

client.on('ready', () => {
  // readyより前だとメッセージを送信できないので、この中に書く
  setTimeout(() => {
  	client.channels.cache.get('チャンネルID').send('hi')
  }, 60 * 60 * 1000)
})
declare var client: import("discord.js").Client;
client.on("ready", () => {
    // readyより前だとメッセージを送信できないので、この中に書く
    setTimeout(() => {
        client.channels.cache.get("\u30C1\u30E3\u30F3\u30CD\u30EBID").send("hi");
    }, 60 * 60 * 1000);
});
  • test.ts (6,9): Object is possibly 'undefined'.
  • test.ts (6,35): Argument of type '"チャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (6,71): Property 'send' does not exist on type 'Channel'.

イベント

イベント

client.on('message', message => {
  console.log(message.content)
})
declare var client: import("discord.js").Client;
client.on("message", message => {
    console.log(message.content);
});
  • used message Event

.on('イベント名', (引数) => { 処理 })
on("\u30A4\u30D9\u30F3\u30C8\u540D", (引数) => { 処理; });
  • test.ts (2,1): Cannot find name 'on'.
  • test.ts (2,39): Parameter '引数' implicitly has an 'any' type.
  • test.ts (2,48): Cannot find name '処理'.

Raw Eventsを使って未キャッシュのデータも処理する

Raw Eventsを使って未キャッシュのデータも処理する

client.on('raw', packet => {
    // We don't want this to run on unrelated packets
    if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
    // Grab the channel to check the message from
    const channel = client.channels.get(packet.d.channel_id);
    // There's no need to emit if the message is cached, because the event will fire anyway for that
    if (channel.messages.has(packet.d.message_id)) return;
    // Since we have confirmed the message is not cached, let's fetch it
    channel.fetchMessage(packet.d.message_id).then(message => {
        // Emojis can have identifiers of name:id format, so we have to account for that case as well
        const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
        // This gives us the reaction we need to emit the event properly, in top of the message object
        const reaction = message.reactions.get(emoji);
        // Adds the currently reacting user to the reaction's users collection.
        if (reaction) reaction.users.set(packet.d.user_id, client.users.get(packet.d.user_id));
        // Check which type of event it is before emitting
        if (packet.t === 'MESSAGE_REACTION_ADD') {
            client.emit('messageReactionAdd', reaction, client.users.get(packet.d.user_id));
        }
        if (packet.t === 'MESSAGE_REACTION_REMOVE') {
            client.emit('messageReactionRemove', reaction, client.users.get(packet.d.user_id));
        }
    });
});
declare var client: import("discord.js").Client;
client.on("raw", packet => {
    // We don't want this to run on unrelated packets
    if (!["MESSAGE_REACTION_ADD", "MESSAGE_REACTION_REMOVE"].includes(packet.t))
        return;
    // Grab the channel to check the message from
    const channel = client.channels.get(packet.d.channel_id);
    // There's no need to emit if the message is cached, because the event will fire anyway for that
    if (channel.messages.has(packet.d.message_id))
        return;
    // Since we have confirmed the message is not cached, let's fetch it
    channel.fetchMessage(packet.d.message_id).then(message => {
        // Emojis can have identifiers of name:id format, so we have to account for that case as well
        const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
        // This gives us the reaction we need to emit the event properly, in top of the message object
        const reaction = message.reactions.get(emoji);
        // Adds the currently reacting user to the reaction's users collection.
        if (reaction)
            reaction.users.set(packet.d.user_id, client.users.get(packet.d.user_id));
        // Check which type of event it is before emitting
        if (packet.t === "MESSAGE_REACTION_ADD") {
            client.emit("messageReactionAdd", reaction, client.users.get(packet.d.user_id));
        }
        if (packet.t === "MESSAGE_REACTION_REMOVE") {
            client.emit("messageReactionRemove", reaction, client.users.get(packet.d.user_id));
        }
    });
});
  • test.ts (8,37): Property 'get' does not exist on type 'ChannelManager'.
  • test.ts (13,52): Parameter 'message' implicitly has an 'any' type.
  • test.ts (20,63): Property 'get' does not exist on type 'UserManager'.
  • test.ts (23,70): Property 'get' does not exist on type 'UserManager'.
  • test.ts (26,73): Property 'get' does not exist on type 'UserManager'.

リアクションを付けて消せるメッセージを送信するサンプル

リアクションを付けて消せるメッセージを送信するサンプル

client.on('message', async message => {
  if (message.content === '!deletable') {
    const sent = await message.channel.send('hello')
    // クリックするだけでリアクションできるように自身でリアクションをしておく
    const reaction = await sent.react('❌')
    // ユーザーの❌のみに反応するためのフィルターを定義しておく
    const filter = (reaction, user) => reaction.emoji.name === '❌' && !user.bot
    // リアクションを待ち受けて処理を実行する
    sent.awaitReactions(filter, { max: 1, time: 5000, errors: ['time'] })
      .then(() => sent.delete()) // リアクションされたら送信したメッセージを削除する
      .catch(() => reaction.remove()) // リアクションされなかったら自身で付けたリアクションを消す(必須ではない)
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    if (message.content === "!deletable") {
        const sent = await message.channel.send("hello");
        // クリックするだけでリアクションできるように自身でリアクションをしておく
        const reaction = await sent.react("\u274C");
        // ユーザーの❌のみに反応するためのフィルターを定義しておく
        const filter = (reaction, user) => reaction.emoji.name === "\u274C" && !user.bot;
        // リアクションを待ち受けて処理を実行する
        sent.awaitReactions(filter, { max: 1, time: 5000, errors: ["time"] })
            .then(() => sent.delete()) // リアクションされたら送信したメッセージを削除する
            .catch(() => reaction.remove()); // リアクションされなかったら自身で付けたリアクションを消す(必須ではない)
    }
});
  • test.ts (10,25): Parameter 'reaction' implicitly has an 'any' type.
  • test.ts (10,35): Parameter 'user' implicitly has an 'any' type.
  • test.ts (12,37): Expected 0-1 arguments, but got 2.
  • used message Event

!deletable
!deletable;
  • test.ts (2,2): Cannot find name 'deletable'.

サーバーへの参加、退出ログを出力するサンプル

サーバーへの参加、退出ログを出力するサンプル

client.on('guildCreate', guild => {
  console.log(`ボットが ${guild.name} に参加しました`)
})

client.on('guildDelete', guild => {
  console.log(`ボットが ${guild.name} から退出しました`)
})
declare var client: import("discord.js").Client;
client.on("guildCreate", guild => {
    console.log(`ボットが ${guild.name} に参加しました`);
});
client.on("guildDelete", guild => {
    console.log(`ボットが ${guild.name} から退出しました`);
});

メンションした人と同じボイスチャンネルに参加している人を取得するサンプル

メンションした人と同じボイスチャンネルに参加している人を取得するサンプル

client.on('message', async message => {
  if (message.content.startsWith('!members') && message.guild) {
  	if (message.mentions.members.size !== 1) return message.channel.send('メンバーを1人指定してください')
    const member = message.mentions.members.first()
    if (!member.voice.channel) return message.channel.send('指定したメンバーがボイスチャンネルに参加していません')
    const tags = member.voice.channel.members.map(member => member.user.tag)
    message.channel.send(tags.join('\n'))
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    if (message.content.startsWith("!members") && message.guild) {
        if (message.mentions.members.size !== 1)
            return message.channel.send("\u30E1\u30F3\u30D0\u30FC\u30921\u4EBA\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
        const member = message.mentions.members.first();
        if (!member.voice.channel)
            return message.channel.send("\u6307\u5B9A\u3057\u305F\u30E1\u30F3\u30D0\u30FC\u304C\u30DC\u30A4\u30B9\u30C1\u30E3\u30F3\u30CD\u30EB\u306B\u53C2\u52A0\u3057\u3066\u3044\u307E\u305B\u3093");
        const tags = member.voice.channel.members.map(member => member.user.tag);
        message.channel.send(tags.join("\n"));
    }
});
  • test.ts (6,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (8,13): Object is possibly 'null'.
  • test.ts (10,24): Object is possibly 'null'.
  • test.ts (11,14): Object is possibly 'undefined'.
  • test.ts (13,22): Object is possibly 'undefined'.
  • used message Event

!members @user
!members;
  • test.ts (2,2): Cannot find name 'members'.

全てのメンバーのユーザータグのリストを作るサンプル

全てのメンバーのユーザータグのリストを作るサンプル

client.on('message', async message => {
  // サーバー内で'!members'が送信されたときのみ実行する
  if (message.content === '!members' && message.guild) {
    // サーバー内の全メンバーを取得する
    const members = await message.guild.members.fetch()
    // mapを使って全メンバーのユーザータグの配列を作る
    const tags = members.map(member => member.user.tag)
    // ユーザータグの配列を改行区切りでつなげてログに出す
    console.log(tags.join('\n'))
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
client.on("message", async (message) => {
    // サーバー内で'!members'が送信されたときのみ実行する
    if (message.content === "!members" && message.guild) {
        // サーバー内の全メンバーを取得する
        const members = await message.guild.members.fetch();
        // mapを使って全メンバーのユーザータグの配列を作る
        const tags = members.map(member => member.user.tag);
        // ユーザータグの配列を改行区切りでつなげてログに出す
        console.log(tags.join("\n"));
    }
});
  • used message Event

!members
!members;
  • test.ts (2,2): Cannot find name 'members'.

メンションされたら処理を実行するサンプル

メンションされたら処理を実行するサンプル

client.on('message', message => {
  if (message.mentions.users.has(client.user.id)) {
    message.reply('hi!')
  }
})
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
client.on("message", message => {
    if (message.mentions.users.has(client.user.id)) {
        message.reply("hi!");
    }
});
  • test.ts (5,36): Object is possibly 'null'.
  • used message Event

指定したチャンネルに時報を送信するサンプル

指定したチャンネルに時報を送信するサンプル

const cron = require('node-cron')
const Discord = require('discord.js')
const client = new Discord.Client()

client.on('ready', () => {
  cron.schedule('0 * * * *', () => {
    const channel = client.channels.cache.get('チャンネルID')
    channel.send(`${new Date().getHours()} 時になりました。`)
  })
})

client.login()
import * as cron from "node-cron";
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("ready", () => {
    cron.schedule("0 * * * *", () => {
        const channel = client.channels.cache.get("\u30C1\u30E3\u30F3\u30CD\u30EBID");
        channel.send(`${new Date().getHours()} 時になりました。`);
    });
});
client.login();
  • test.ts (2,23): Cannot find module 'node-cron' or its corresponding type declarations.
  • test.ts (4,16): Expected 1 arguments, but got 0.
  • test.ts (7,51): Argument of type '"チャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (8,9): Object is possibly 'undefined'.
  • test.ts (8,17): Property 'send' does not exist on type 'Channel'.

node-cron
node - cron;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (2,8): Cannot find name 'cron'.

メッセージがピン留めされたらログを出すサンプル

メッセージがピン留めされたらログを出すサンプル

client.on('channelPinsUpdate', channel => {
  // ピン留めが更新されたチャンネルでの、ピン留めされたメッセージを取得する
  const pinned = await channel.messages.fetchPinned()
  // 一番最後にピン留めされたメッセージを取得する
  const message = messages.last()
  console.log(`${channel.name}${message.id}がピン留めされたよ。`)
})
declare var client: import("discord.js").Client;
client.on("channelPinsUpdate", channel => {
    // ピン留めが更新されたチャンネルでの、ピン留めされたメッセージを取得する
    const pinned = await channel.messages.fetchPinned();
    // 一番最後にピン留めされたメッセージを取得する
    const message = messages.last();
    console.log(`${channel.name}${message.id}がピン留めされたよ。`);
});
  • test.ts (5,20): 'await' expressions are only allowed within async functions and at the top levels of modules.
  • test.ts (7,21): Cannot find name 'messages'. Did you mean 'message'?
  • test.ts (8,28): Property 'name' does not exist on type 'TextChannel | DMChannel | NewsChannel | PartialDMChannel'. Property 'name' does not exist on type 'DMChannel'.

簡易的なコマンドを実装するサンプル

簡易的なコマンドを実装するサンプル

 const Discord = require('discord.js')
 const client = new Discord.Client()
 
 client.on('message', message => {
   if (!message.content.startsWith('!')) return
   if (message.content === '!ping') {
     message.channel.send('Pong!')
   } else if (message.content === '!help') {
     // ...
   } else {
     message.channel.send('コマンドが存在しません')
   }
 })
 
 client.login(token)
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", message => {
    if (!message.content.startsWith("!"))
        return;
    if (message.content === "!ping") {
        message.channel.send("Pong!");
    }
    else if (message.content === "!help") {
        // ...
    }
    else {
        message.channel.send("\u30B3\u30DE\u30F3\u30C9\u304C\u5B58\u5728\u3057\u307E\u305B\u3093");
    }
});
client.login(token);
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (17,14): Cannot find name 'token'.
  • used message Event

更新したら自動で保存されるオブジェクトのサンプル

更新したら自動で保存されるオブジェクトのサンプル

!(async () => {
  const data1 = await dataStore('./data1.json')
  data1.foo = 1 // data1.jsonが自動的に更新される
  
  // 第2引数でデフォルト(ファイルが無かったら作成されるデータ)の値を指定する(指定しないと{}になる)
  const data2 = await dataStore('./data2.json', [])
  data2.push(1)
})()
!(async () => {
    const data1 = await dataStore("./data1.json");
    data1.foo = 1; // data1.jsonが自動的に更新される
    // 第2引数でデフォルト(ファイルが無かったら作成されるデータ)の値を指定する(指定しないと{}になる)
    const data2 = await dataStore("./data2.json", []);
    data2.push(1);
})();
  • test.ts (3,25): Cannot find name 'dataStore'.
  • test.ts (6,25): Cannot find name 'dataStore'.

const DeepProxy = require('proxy-deep')
const fs = require('fs').promises
const { dirname } = require('path')
const mkdirp = require('mkdirp')

const dataStore = async (path, _default = {}) => {
  const data = await fs
    .readFile(path)
    .then(file => JSON.parse(file))
    .catch(async () => {
      await mkdirp(dirname(path))
      await fs.writeFile(path, JSON.stringify(_default, null, 2))
      return _default
    })
  const save = debounce(data => fs.writeFile(path, data), 10)

  return new DeepProxy(data, {
    get(target, key, receiver) {
      const val = Reflect.get(target, key, receiver)
      if (typeof val === 'object' && val !== null) {
        return this.nest(val)
      } else {
        return val
      }
    },
    async set(target, key, value, receiver) {
      Reflect.set(target, key, value, receiver)
      save(JSON.stringify(this.rootTarget, null, 2))
      return true
    },
  })
}

const debounce = (fn, interval) => {
  let timerId
  return (...args) => {
    clearTimeout(timerId)
    timerId = setTimeout(() => fn(...args), interval)
  }
}
import * as DeepProxy from "proxy-deep";
const fs = require("fs").promises;
import { dirname } from "path";
import * as mkdirp from "mkdirp";
const dataStore = async (path, _default = {}) => {
    const data = await fs
        .readFile(path)
        .then(file => JSON.parse(file))
        .catch(async () => {
        await mkdirp(dirname(path));
        await fs.writeFile(path, JSON.stringify(_default, null, 2));
        return _default;
    });
    const save = debounce(data => fs.writeFile(path, data), 10);
    return new DeepProxy(data, {
        get(target, key, receiver) {
            const val = Reflect.get(target, key, receiver);
            if (typeof val === "object" && val !== null) {
                return this.nest(val);
            }
            else {
                return val;
            }
        },
        async set(target, key, value, receiver) {
            Reflect.set(target, key, value, receiver);
            save(JSON.stringify(this.rootTarget, null, 2));
            return true;
        },
    });
};
const debounce = (fn, interval) => {
    let timerId;
    return (...args) => {
        clearTimeout(timerId);
        timerId = setTimeout(() => fn(...args), interval);
    };
};
  • test.ts (2,28): Cannot find module 'proxy-deep' or its corresponding type declarations.
  • test.ts (5,25): Cannot find module 'mkdirp' or its corresponding type declarations.
  • test.ts (6,26): Parameter 'path' implicitly has an 'any' type.
  • test.ts (9,15): Parameter 'file' implicitly has an 'any' type.
  • test.ts (15,27): Parameter 'data' implicitly has an 'any' type.
  • test.ts (17,13): Parameter 'target' implicitly has an 'any' type.
  • test.ts (17,21): Parameter 'key' implicitly has an 'any' type.
  • test.ts (17,26): Parameter 'receiver' implicitly has an 'any' type.
  • test.ts (26,19): Parameter 'target' implicitly has an 'any' type.
  • test.ts (26,27): Parameter 'key' implicitly has an 'any' type.
  • test.ts (26,32): Parameter 'value' implicitly has an 'any' type.
  • test.ts (26,39): Parameter 'receiver' implicitly has an 'any' type.
  • test.ts (33,19): Parameter 'fn' implicitly has an 'any' type.
  • test.ts (33,23): Parameter 'interval' implicitly has an 'any' type.
  • test.ts (34,9): Variable 'timerId' implicitly has type 'any' in some locations where its type cannot be determined.
  • test.ts (35,13): Rest parameter 'args' implicitly has an 'any[]' type.
  • test.ts (36,22): Variable 'timerId' implicitly has an 'any' type.

Promise.all
Promise.all;

メンバーのBANを解除する

メンバーのBANを解除する

message.guild.members.unban('ID or Userオブジェクト')
  .then(user => console.log(`${user.tag}のBANを解除`))
  .catch(console.error)
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.members.unban("ID or User\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8")
    .then(user => console.log(`${user.tag}のBANを解除`))
    .catch(console.error);
  • test.ts (4,1): Object is possibly 'null'.
  • test.ts (4,29): Argument of type '"ID or Userオブジェクト"' is not assignable to parameter of type 'UserResolvable'.

message.guild.members.unban('ID or Userオブジェクト', '理由')
  .then(user => console.log(`${user.tag}のBANを解除`))
  .catch(console.error)
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.members.unban("ID or User\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8", "\u7406\u7531")
    .then(user => console.log(`${user.tag}のBANを解除`))
    .catch(console.error);
  • test.ts (4,1): Object is possibly 'null'.
  • test.ts (4,29): Argument of type '"ID or Userオブジェクト"' is not assignable to parameter of type 'UserResolvable'.

members
members;
  • test.ts (2,1): Cannot find name 'members'.

一定時間ごとに処理を実行したい

一定時間ごとに処理を実行したい

setInterval(function () {
  console.log('foo')
}, 1000)
setInterval(function () {
    console.log("foo");
}, 1000);

foo
foo;
  • test.ts (2,1): Cannot find name 'foo'.

1000
1000;

1000
1000;

変数とは

変数とは

client.on('message', message => {
  console.log(message.content)
})
declare var client: import("discord.js").Client;
client.on("message", message => {
    console.log(message.content);
});
  • used message Event

const Discord = require('discord.js')
const client = new Discord.Client()

client.on('message', message => {
  console.log(message.content)
})

client.login('token')
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("message", message => {
    console.log(message.content);
});
client.login("token");
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • used message Event

require
require;

client
declare var client: import("discord.js").Client;
client;

ReferenceError: client is not defined
declare var client: import("discord.js").Client;
ReferenceError: client;
is;
not;
defined;
  • test.ts (4,1): Cannot find name 'is'.
  • test.ts (5,1): Cannot find name 'not'.
  • test.ts (6,1): Cannot find name 'defined'. Did you mean 'undefined'?

client
declare var client: import("discord.js").Client;
client;

client
declare var client: import("discord.js").Client;
client;

bot
bot;
  • test.ts (2,1): Cannot find name 'bot'.

login
login;
  • test.ts (2,1): Cannot find name 'login'.

Discord
import * as Discord from "discord.js";
Discord;

client
declare var client: import("discord.js").Client;
client;

message
declare var message: import("discord.js").Message;
message;

require
require;

console
console;

ユーザーのアバターを取得する

ユーザーのアバターを取得する

const { Client } = require('discord.js')
const client = new Client()

client.on('message', message => {
  if (message.content === '!avatar') {
    message.channel.send(message.author.avatarURL() || 'アバターが設定されてないよ。')
  }
})
import { Client } from "discord.js";
const client = new Client();
client.on("message", message => {
    if (message.content === "!avatar") {
        message.channel.send(message.author.avatarURL() || "\u30A2\u30D0\u30BF\u30FC\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u306A\u3044\u3088\u3002");
    }
});
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • used message Event

const { Structures, Client } = require('discord.js')

Structures.extend('User', BaseClass => class extends BaseClass {
  avatarURL (options) {
    return super.avatarURL(Object.assign(options || { format: 'png' }, { dynamic: true }))
  }

  displayAvatarURL (options) {
    return super.displayAvatarURL(Object.assign(options || { format: 'png' }, { dynamic: true }))
  }
})

const client = new Client() // 上記のコードはクライアントのインスタンスを作る前に書かないといけない。

client.on('message', message => {
  if (message.content === '!avatar') {
    message.channel.send(message.author.avatarURL() || 'アバターが設定されてないよ。')
  }
})
import { Structures, Client } from "discord.js";
Structures.extend("User", BaseClass => class extends BaseClass {
    avatarURL(options) {
        return super.avatarURL(Object.assign(options || { format: "png" }, { dynamic: true }));
    }
    displayAvatarURL(options) {
        return super.displayAvatarURL(Object.assign(options || { format: "png" }, { dynamic: true }));
    }
});
const client = new Client(); // 上記のコードはクライアントのインスタンスを作る前に書かないといけない。
client.on("message", message => {
    if (message.content === "!avatar") {
        message.channel.send(message.author.avatarURL() || "\u30A2\u30D0\u30BF\u30FC\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u306A\u3044\u3088\u3002");
    }
});
  • test.ts (2,10): Module '"discord.js"' has no exported member 'Structures'.
  • test.ts (3,27): Parameter 'BaseClass' implicitly has an 'any' type.
  • test.ts (4,15): Parameter 'options' implicitly has an 'any' type.
  • test.ts (7,22): Parameter 'options' implicitly has an 'any' type.
  • test.ts (11,16): Expected 1 arguments, but got 0.
  • used message Event

avatarURL
avatarURL;
  • test.ts (2,1): Cannot find name 'avatarURL'.

null
null;

displayAvatarURL
displayAvatarURL;
  • test.ts (2,1): Cannot find name 'displayAvatarURL'.

null
null;

format
format;
  • test.ts (2,1): Cannot find name 'format'. Did you mean 'FormData'?

webp
webp;
  • test.ts (2,1): Cannot find name 'webp'.

webp, png, jpg, jpeg, gif
webp, png, jpg, jpeg, gif;
  • test.ts (2,1): Cannot find name 'webp'.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,7): Cannot find name 'png'.
  • test.ts (2,12): Cannot find name 'jpg'.
  • test.ts (2,17): Cannot find name 'jpeg'.
  • test.ts (2,23): Cannot find name 'gif'.

avatarURL({ format: 'png' })
avatarURL({ format: "png" });
  • test.ts (2,1): Cannot find name 'avatarURL'.

dynamic
dynamic;
  • test.ts (2,1): Cannot find name 'dynamic'.

false
false;

avatarURL({ dynamic: true })
avatarURL({ dynamic: true });
  • test.ts (2,1): Cannot find name 'avatarURL'.

size
size;
  • test.ts (2,1): Cannot find name 'size'.

16, 32, 64, 128, 256, 512, 1024, 2048, 4096
16, 32, 64, 128, 256, 512, 1024, 2048, 4096;
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.
  • test.ts (2,1): Left side of comma operator is unused and has no side effects.

avatarURL({ size: 128 })
avatarURL({ size: 128 });
  • test.ts (2,1): Cannot find name 'avatarURL'.

avatarURL
avatarURL;
  • test.ts (2,1): Cannot find name 'avatarURL'.

displayAvatarURL
displayAvatarURL;
  • test.ts (2,1): Cannot find name 'displayAvatarURL'.

ボットのメッセージのみに反応して返信するサンプル

ボットのメッセージのみに反応して返信するサンプル

client.on('message', message => {
  if (message.author.bot) {
    message.channel.send('hay')
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", message => {
    if (message.author.bot) {
        message.channel.send("hay");
    }
});
  • used message Event

メンバーの参加、退出ログを出力するサンプル

メンバーの参加、退出ログを出力するサンプル

client.on('guildMemberAdd', member => {
  console.log(`${member.guild.name}${member.displayName} が参加しました`)
})

client.on('guildMemberRemove', member => {
  console.log(`${member.guild.name} から ${member.displayName} が退出しました`)
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
client.on("guildMemberAdd", member => {
    console.log(`${member.guild.name}${member.displayName} が参加しました`);
});
client.on("guildMemberRemove", member => {
    console.log(`${member.guild.name} から ${member.displayName} が退出しました`);
});

指定したチャンネルにメッセージを送信したい

指定したチャンネルにメッセージを送信したい

client.channels.cache.get('送信するチャンネルのID').send('メッセージ')
declare var client: import("discord.js").Client;
client.channels.cache.get("\u9001\u4FE1\u3059\u308B\u30C1\u30E3\u30F3\u30CD\u30EB\u306EID").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,27): Argument of type '"送信するチャンネルのID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (3,93): Property 'send' does not exist on type 'Channel'.

client.channels.get('送信するチャンネルのID').send('メッセージ')
declare var client: import("discord.js").Client;
client.channels.get("\u9001\u4FE1\u3059\u308B\u30C1\u30E3\u30F3\u30CD\u30EB\u306EID").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,17): Property 'get' does not exist on type 'ChannelManager'.

client.channels.cache
declare var client: import("discord.js").Client;
client.channels.cache;

.get('id')
get("id");
  • test.ts (2,1): Cannot find name 'get'.

.get('id')
get("id");
  • test.ts (2,1): Cannot find name 'get'.

TypeError: Cannot read property 'send' of undefined
TypeError: Cannot;
read;
property;
"send";
of;
undefined;
  • test.ts (2,12): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'read'.
  • test.ts (4,1): Cannot find name 'property'.
  • test.ts (6,1): Cannot find name 'of'.

メッセージ内のメンションを取得する

メッセージ内のメンションを取得する

if (message.mentions.members.size !== 1) return message.channel.send('メンバーを1人指定してください')
const member = await message.mentions.members.first()
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
if (message.mentions.members.size !== 1)
    return message.channel.send("\u30E1\u30F3\u30D0\u30FC\u30921\u4EBA\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
const member = await message.mentions.members.first();
  • test.ts (4,5): Object is possibly 'null'.
  • test.ts (5,5): A 'return' statement can only be used within a function body.
  • test.ts (6,16): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (6,16): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (6,22): Object is possibly 'null'.

message.mentions
declare var message: import("discord.js").Message;
message.mentions;

.users
users;
  • test.ts (2,1): Cannot find name 'users'.

.roles
roles;
  • test.ts (2,1): Cannot find name 'roles'.

.channels
channels;
  • test.ts (2,1): Cannot find name 'channels'.

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

collection.first()
collection.first();
  • test.ts (2,1): Cannot find name 'collection'.

役職を持つ人だけが実行できるコマンドのサンプル

役職を持つ人だけが実行できるコマンドのサンプル

client.on('message', async (message) => {
  // メッセージが "hi" で、送信されたのがサーバー内だったら実行する(DMだと役職が取得できないので)
  if (message.content === 'hi' && message.guild) {
    // 名前が "member" の役職を取得する
    const role = message.guild.roles.cache.find(roles => roles.name === 'member')
    // 取得した役職のIDから、役職を持っているか確認し、持っていなかったら、ここで処理を止める
    if (!message.member.roles.cache.has(role.id)) return
    // "hello" と送信する
    message.channel.send('hello')
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    // メッセージが "hi" で、送信されたのがサーバー内だったら実行する(DMだと役職が取得できないので)
    if (message.content === "hi" && message.guild) {
        // 名前が "member" の役職を取得する
        const role = message.guild.roles.cache.find(roles => roles.name === "member");
        // 取得した役職のIDから、役職を持っているか確認し、持っていなかったら、ここで処理を止める
        if (!message.member.roles.cache.has(role.id))
            return;
        // "hello" と送信する
        message.channel.send("hello");
    }
});
  • test.ts (12,14): Object is possibly 'null'.
  • test.ts (12,45): Object is possibly 'undefined'.
  • used message Event

ユーザーがサーバーに参加していた日数を計算するサンプル

ユーザーがサーバーに参加していた日数を計算するサンプル

client.on("guildMemberRemove", member => {
  const period = Math.round((Date.now() - member.joinedAt) / 86400000) // サーバーに居た期間を日数にして計算

  console.log(`${member.user.tag}${member.guild.name}に約${period}日間サーバーに参加していました。`)
})
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
declare var guild: import("discord.js").Guild;
client.on("guildMemberRemove", member => {
    const period = Math.round((Date.now() - member.joinedAt) / 86400000); // サーバーに居た期間を日数にして計算
    console.log(`${member.user.tag}${member.guild.name}に約${period}日間サーバーに参加していました。`);
});
  • test.ts (6,45): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (6,45): Object is possibly 'null'.
  • test.ts (7,20): Object is possibly 'null'.

setTimeoutをsetIntervalを組み合わせて指定した時刻ごとに処理を実行するサンプル

setTimeoutをsetIntervalを組み合わせて指定した時刻ごとに処理を実行するサンプル

const date = new Date()
const now = date.getTime()
const nextHours = date.getMinutes() + 1
const next = date.setMinutes(nextHours, 0, 0)
const diff = next - now
const fn = () => console.log('0秒だよ')
setTimeout(() => {
  fn()
  setInterval(fn, 1000 * 60)
}, diff)
const date = new Date();
const now = date.getTime();
const nextHours = date.getMinutes() + 1;
const next = date.setMinutes(nextHours, 0, 0);
const diff = next - now;
const fn = () => console.log("0\u79D2\u3060\u3088");
setTimeout(() => {
    fn();
    setInterval(fn, 1000 * 60);
}, diff);

ユーザーの端末ごとのステータスを送信するボットのサンプル

ユーザーの端末ごとのステータスを送信するボットのサンプル

const Discord = require('discord.js')
const client = new Discord.Client()

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on('message', message => {
  if (message.content === 'status') {
    const userStatus = message.author.presence.clientStatus

    if (!userStatus) {
      return message.channel.send('どのデバイスからもアクセスされていません。')
    }

    message.channel.send(
      [
        'desktop: ' + (userStatus.desktop || 'offline'),
        'mobile: ' + (userStatus.mobile || 'offline'),
        'web: ' + (userStatus.web || 'offline'),
      ].join('\n')
    )
  }
})

client.login('TOKEN')
import * as Discord from "discord.js";
const client = new Discord.Client();
client.on("ready", () => {
    console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", message => {
    if (message.content === "status") {
        const userStatus = message.author.presence.clientStatus;
        if (!userStatus) {
            return message.channel.send("\u3069\u306E\u30C7\u30D0\u30A4\u30B9\u304B\u3089\u3082\u30A2\u30AF\u30BB\u30B9\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002");
        }
        message.channel.send([
            "desktop: " + (userStatus.desktop || "offline"),
            "mobile: " + (userStatus.mobile || "offline"),
            "web: " + (userStatus.web || "offline"),
        ].join("\n"));
    }
});
client.login("TOKEN");
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (5,33): Object is possibly 'null'.
  • test.ts (7,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise | undefined' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise | undefined' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'Awaited'. Type 'Promise' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message, TResult2 = never>(onfulfilled?: ((value: Message) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (9,43): Property 'presence' does not exist on type 'User'.
  • used message Event

チャンネルの権限設定を変更する

チャンネルの権限設定を変更する

channel.overwritePermissions([
  {
    id: '役職のID または メンバーのID', // またはそれらのオブジェクト
    allow: ['ADD_REACTIONS'], // 許可する権限
    deny: ['CHANGE_NICKNAME'] // 許可しない権限
  }
])
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.overwritePermissions([
    {
        id: "\u5F79\u8077\u306EID \u307E\u305F\u306F \u30E1\u30F3\u30D0\u30FC\u306EID",
        allow: ["ADD_REACTIONS"],
        deny: ["CHANGE_NICKNAME"] // 許可しない権限
    }
]);
  • test.ts (3,9): Property 'overwritePermissions' does not exist on type 'Omit<TextChannel, "type"> & Omit<VoiceChannel, "type">'.

.overwritePermissions()
overwritePermissions();
  • test.ts (2,1): Cannot find name 'overwritePermissions'.

id
id;
  • test.ts (2,1): Cannot find name 'id'.

allow
allow;
  • test.ts (2,1): Cannot find name 'allow'.

deny
deny;
  • test.ts (2,1): Cannot find name 'deny'.

id
id;
  • test.ts (2,1): Cannot find name 'id'.

{ id: '役職ID または メンバーのID (オブジェクトも指定可能)', allow: ['ADD_REACTIONS'] }
{
    id: "\u5F79\u8077ID \u307E\u305F\u306F \u30E1\u30F3\u30D0\u30FC\u306EID (\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8\u3082\u6307\u5B9A\u53EF\u80FD)", allow;
    ["ADD_REACTIONS"];
}
  • test.ts (3,9): Left side of comma operator is unused and has no side effects.
  • test.ts (3,148): Cannot find name 'allow'.

allow
allow;
  • test.ts (2,1): Cannot find name 'allow'.

deny
deny;
  • test.ts (2,1): Cannot find name 'deny'.

サーバー内のIDで指定したメンバーのニックネームを変更するサンプル

サーバー内のIDで指定したメンバーのニックネームを変更するサンプル

client.on('message', message => {
  if (message.content === '!nickname') {
    message.guild.member('id').setNickname('ニックネーム')
  }
})
declare var client: import("discord.js").Client;
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
client.on("message", message => {
    if (message.content === "!nickname") {
        message.guild.member("id").setNickname("\u30CB\u30C3\u30AF\u30CD\u30FC\u30E0");
    }
});
  • test.ts (7,9): Object is possibly 'null'.
  • test.ts (7,23): Property 'member' does not exist on type 'Guild'. Did you mean 'members'?
  • used message Event

!nickname
!nickname;
  • test.ts (2,2): Cannot find name 'nickname'.

ユーザーIDからDMを送信するサンプル

ユーザーIDからDMを送信するサンプル

const user = client.users.cache.get('ID')
user.send('メッセージ')
declare var client: import("discord.js").Client;
const user = client.users.cache.get("ID");
user.send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,37): Argument of type '"ID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (4,1): Object is possibly 'undefined'.

送信したメッセージにリアクションを付けるサンプル

送信したメッセージにリアクションを付けるサンプル

client.on('message', async message => {
  if (message.content === 'hello') {
    const reply = await message.channel.send('hi!')
    reply.react('👋')
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    if (message.content === "hello") {
        const reply = await message.channel.send("hi!");
        reply.react("\uD83D\uDC4B");
    }
});
  • used message Event

hello
hello;
  • test.ts (2,1): Cannot find name 'hello'.

hi!
hi!;
  • test.ts (2,1): Cannot find name 'hi'.

送信したメッセージを数秒後に削除するサンプル

送信したメッセージを数秒後に削除するサンプル

client.on('message', async message => {
  if (message.content === 'hello') {
    const reply = await message.channel.send('hi!')
    reply.delete({ timeout: 5000 })
    // v11では代わりに reply.delete(5000) と書く
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    if (message.content === "hello") {
        const reply = await message.channel.send("hi!");
        reply.delete({ timeout: 5000 });
        // v11では代わりに reply.delete(5000) と書く
    }
});
  • test.ts (7,22): Expected 0 arguments, but got 1.
  • used message Event

hello
hello;
  • test.ts (2,1): Cannot find name 'hello'.

hi!
hi!;
  • test.ts (2,1): Cannot find name 'hi'.

定期的にステータスメッセージを変えるサンプル

定期的にステータスメッセージを変えるサンプル

client.on('ready', () => {
  setInterval(() => {
    client.user.setActivity({
      name: `${client.ws.ping}ms`
    })
  }, 10000)
})
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
client.on("ready", () => {
    setInterval(() => {
        client.user.setActivity({
            name: `${client.ws.ping}ms`
        });
    }, 10000);
});
  • test.ts (6,9): Object is possibly 'null'.

指定した時間後に処理を実行する

指定した時間後に処理を実行する

setTimeout(() => {
  console.log('foo')
}, 1000)
setTimeout(() => {
    console.log("foo");
}, 1000);

foo
foo;
  • test.ts (2,1): Cannot find name 'foo'.

1000
1000;

1000
1000;

簡易的な投票コマンドのサンプル

簡易的な投票コマンドのサンプル

const Discord = require('discord.js')
const client = new Discord.Client()

const prefix = '!'

client.on('message', async message => {
  if (!message.content.startsWith(prefix)) return
  const [command, ...args] = message.content.slice(prefix.length).split(' ')
  if (command === 'poll') {
    const [title, ...choices] = args
    if (!title) return message.channel.send('タイトルを指定してください')
    const emojis = ['🇦', '🇧', '🇨', '🇩']
    if (choices.length < 2 || choices.length > emojis.length)
      return message.channel.send(`選択肢は2から${emojis.length}つを指定してください`)
    const poll = await message.channel.send({
      embed: {
        title: title,
        description: choices.map((c, i) => `${emojis[i]} ${c}`).join('\n')
      }
    });
    emojis.slice(0, choices.length).forEach(emoji => poll.react(emoji))
  }
})

client.login()
import * as Discord from "discord.js";
const client = new Discord.Client();
const prefix = "!";
client.on("message", async (message) => {
    if (!message.content.startsWith(prefix))
        return;
    const [command, ...args] = message.content.slice(prefix.length).split(" ");
    if (command === "poll") {
        const [title, ...choices] = args;
        if (!title)
            return message.channel.send("\u30BF\u30A4\u30C8\u30EB\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
        const emojis = ["\uD83C\uDDE6", "\uD83C\uDDE7", "\uD83C\uDDE8", "\uD83C\uDDE9"];
        if (choices.length < 2 || choices.length > emojis.length)
            return message.channel.send(`選択肢は2から${emojis.length}つを指定してください`);
        const poll = await message.channel.send({
            embed: {
                title: title,
                description: choices.map((c, i) => `${emojis[i]} ${c}`).join("\n")
            }
        });
        emojis.slice(0, choices.length).forEach(emoji => poll.react(emoji));
    }
});
client.login();
  • test.ts (3,16): Expected 1 arguments, but got 0.
  • test.ts (5,1): No overload matches this call. Overload 1 of 2, '(event: "message", listener: (message: Message) => Awaited): Client', gave the following error. Argument of type '(message: Message) => Promise<Message | undefined>' is not assignable to parameter of type '(message: Message) => Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'Awaited'. Type 'Promise<Message | undefined>' is not assignable to type 'PromiseLike'. Types of property 'then' are incompatible. Type '<TResult1 = Message | undefined, TResult2 = never>(onfulfilled?: ((value: Message | undefined) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | undefined) => Promise<...>' is not assignable to type '<TResult1 = void, TResult2 = never>(onfulfilled?: ((value: void) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => PromiseLike<...>'. Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible. Types of parameters 'value' and 'value' are incompatible. Type 'Message | undefined' is not assignable to type 'void'. Type 'Message' is not assignable to type 'void'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.
  • test.ts (17,13): Argument of type '{ embed: { title: string; description: string; }; }' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Object literal may only specify known properties, and 'embed' does not exist in type 'MessagePayload | MessageOptions'.
  • used message Event

emojis
emojis;
  • test.ts (2,1): Cannot find name 'emojis'.

送信したメッセージに対して処理をする

送信したメッセージに対して処理をする

client.on('message', async message => {  
  if (message.content === 'ping') {
    const pong = await message.channel.send('pong')
    console.log(pong.content) // pong
  }
})
declare var client: import("discord.js").Client;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
client.on("message", async (message) => {
    if (message.content === "ping") {
        const pong = await message.channel.send("pong");
        console.log(pong.content); // pong
    }
});
  • used message Event

send()
send();
  • test.ts (2,1): Cannot find name 'send'.

コマンドパーサーの実装方法まとめ

コマンドパーサーの実装方法まとめ

console.log('!command arg'.split(' ')) // ['!command', 'arg']
console.log('!command "arg includes spaces"'.split(' ')) // ['!command', '"arg', 'includes', 'spaces"']
console.log("!command arg".split(" ")); // ['!command', 'arg']
console.log("!command \"arg includes spaces\"".split(" ")); // ['!command', '"arg', 'includes', 'spaces"']

 const parse = require('yargs-parser')
 const result = parse('!command arg "arg includes spaces" --foo=33 --bar')
 console.log(result) // { _: ['!command', 'arg', '"arg includes spaces"'], bar: true, foo: 33 }
 // 前後の""を取り除く
 console.log(result._.map(arg => typeof arg === 'string' ? arg.replace(/^(['"])(.*)\1$/, '$2') : arg))
 // ['!command', 'arg', 'arg includes spaces']
import * as parse from "yargs-parser";
const result = parse("!command arg \"arg includes spaces\" --foo=33 --bar");
console.log(result); // { _: ['!command', 'arg', '"arg includes spaces"'], bar: true, foo: 33 }
// 前後の""を取り除く
console.log(result._.map(arg => typeof arg === "string" ? arg.replace(/^(['"])(.*)\1$/, "$2") : arg));
// ['!command', 'arg', 'arg includes spaces']
  • test.ts (2,24): Cannot find module 'yargs-parser' or its corresponding type declarations.
  • test.ts (6,26): Parameter 'arg' implicitly has an 'any' type.

const split = require('split-string')
const result = split('!command subcmd "args includes spaces"', { separator: ' ', quotes: ['"'] })
console.log(result) // ['!command', 'subcmd', '"args includes spaces"']
// 前後の""を取り除く
console.log(result.map(str => str.replace(/^(['"])(.*)\1$/, '$2')))
// ['!command', 'subcmd', 'args includes spaces']
import * as split from "split-string";
const result = split("!command subcmd \"args includes spaces\"", { separator: " ", quotes: ["\""] });
console.log(result); // ['!command', 'subcmd', '"args includes spaces"']
// 前後の""を取り除く
console.log(result.map(str => str.replace(/^(['"])(.*)\1$/, "$2")));
// ['!command', 'subcmd', 'args includes spaces']
  • test.ts (2,24): Cannot find module 'split-string' or its corresponding type declarations.
  • test.ts (6,24): Parameter 'str' implicitly has an 'any' type.

console.log('!command subcmd "args includes spaces"'.split(/(?:"([^"]+)"|([^ ]+)) ?/).filter(e => e))
// ['!command', 'subcmd', 'args includes spaces']
console.log("!command subcmd \"args includes spaces\"".split(/(?:"([^"]+)"|([^ ]+)) ?/).filter(e => e));
// ['!command', 'subcmd', 'args includes spaces']

--foo=33 --bar
--foo;
33--;
bar;
  • test.ts (2,3): Cannot find name 'foo'.
  • test.ts (3,1): The operand of an increment or decrement operator must be a variable or a property access.
  • test.ts (4,1): Cannot find name 'bar'.

""
"";

テンプレートリテラルとは

テンプレートリテラルとは

console.log(`Hello world!`) // Hello world!
console.log(`Hello world!` === 'Hello world!') // true
console.log(`Hello world!`); // Hello world!
console.log(`Hello world!` === "Hello world!"); // true

const target = 'world'
console.log(`Hello ${target}!`) // Hello world!

// テンプレートリテラルを使わない場合
console.log('Hello ' + target + '!') // Hello world!
// 普通の文字列で${}で値を埋め込むことはできない
console.log('Hello ${target}!') // Hello ${target}!
const target = "world";
console.log(`Hello ${target}!`); // Hello world!
// テンプレートリテラルを使わない場合
console.log("Hello " + target + "!"); // Hello world!
// 普通の文字列で${}で値を埋め込むことはできない
console.log("Hello ${target}!"); // Hello ${target}!

${}
$;
{ }
  • test.ts (2,1): Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i --save-dev @types/jquery and then add 'jquery' to the types field in your tsconfig.

constは変数を固定するもので値は固定しない

constは変数を固定するもので値は固定しない

const obj = {}
obj.prop = 'value'
console.log(obj) // {prop: "value"}
const obj = {};
obj.prop = "value";
console.log(obj); // {prop: "value"}
  • 変えられる例.ts (3,5): Property 'prop' does not exist on type '{}'.

const obj = []
obj = [] // Uncaught SyntaxError: Identifier 'obj' has already been declared  
const obj = [];
obj = []; // Uncaught SyntaxError: Identifier 'obj' has already been declared  
  • 変えられない例.ts (3,1): Cannot assign to 'obj' because it is a constant.

const
const ;
  • test.ts (2,6): Variable declaration list cannot be empty.

変数 = 
変数 = ;
  • test.ts (2,1): Cannot find name '変数'.
  • test.ts (2,6): Cannot find name '値'.

obj.prop
obj.prop;
  • test.ts (2,1): Cannot find name 'obj'.

array.push('value')
array.push("value");
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

1
1;

'hoge'
"hoge";

message.content に含まれているMarkdown記法を取り除きたい。

message.content に含まれているMarkdown記法を取り除きたい。

escapeMarkdown(text: string, onlyCodeBlock = false, onlyInlineCode = false): string
escapeMarkdown(text, string, onlyCodeBlock = false, onlyInlineCode = false);
string;
  • test.ts (2,1): Cannot find name 'escapeMarkdown'.
  • test.ts (2,16): Cannot find name 'text'. Did you mean 'Text'?
  • test.ts (2,22): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,30): Cannot find name 'onlyCodeBlock'.
  • test.ts (2,53): Cannot find name 'onlyInlineCode'.
  • test.ts (3,1): 'string' only refers to a type, but is being used as a value here.

const { Util, Client } = require('discord.js')
const bot = new Client()

/**
 * message.contentが"Discord.jsが**No.1**に決まってる!"
 * だった場合コンソールには"Discord.jsがNo.1に決まってる!"と出力される。
 */
bot.on('message', message => console.log(Util.escapeMarkdown(message.content)))

bot.login()
import { Util, Client } from "discord.js";
const bot = new Client();
/**
 * message.contentが"Discord.jsが**No.1**に決まってる!"
 * だった場合コンソールには"Discord.jsがNo.1に決まってる!"と出力される。
 */
bot.on("message", message => console.log(Util.escapeMarkdown(message.content)));
bot.login();
  • test.ts (3,13): Expected 1 arguments, but got 0.
  • used message Event

typingStart

typingStart

const { Client } = require('discord.js')
const bot = new Client()

bot.on('typingStart', (channel, user) => {
  // code
})

bot.login()
import { Client } from "discord.js";
const bot = new Client();
bot.on("typingStart", (channel, user) => {
    // code
});
bot.login();
  • typingstart.ts (3,13): Expected 1 arguments, but got 0.

Gateway Intents の利用に関するガイド

Gateway Intents の利用に関するガイド

GUILDS
GUILDS;
  • test.ts (2,1): Cannot find name 'GUILDS'.

message
declare var message: import("discord.js").Message;
message;

presenceUpdate
presenceUpdate;
  • test.ts (2,1): Cannot find name 'presenceUpdate'.

GUILD_MEMBERS
GUILD_MEMBERS;
  • test.ts (2,1): Cannot find name 'GUILD_MEMBERS'.

guildMemberAdd
guildMemberAdd;
  • test.ts (2,1): Cannot find name 'guildMemberAdd'.

guildMemberRemove
guildMemberRemove;
  • test.ts (2,1): Cannot find name 'guildMemberRemove'.

guildMemberUpdate
guildMemberUpdate;
  • test.ts (2,1): Cannot find name 'guildMemberUpdate'.

guild.members.fetch()
declare var guild: import("discord.js").Guild;
guild.members.fetch();

GUILD_BANS
GUILD_BANS;
  • test.ts (2,1): Cannot find name 'GUILD_BANS'.

guildBanAdd
guildBanAdd;
  • test.ts (2,1): Cannot find name 'guildBanAdd'.

guildBanRemove
guildBanRemove;
  • test.ts (2,1): Cannot find name 'guildBanRemove'.

GUILD_EMOJIS
GUILD_EMOJIS;
  • test.ts (2,1): Cannot find name 'GUILD_EMOJIS'.

emojiCreate
emojiCreate;
  • test.ts (2,1): Cannot find name 'emojiCreate'.

emojiUpdate
emojiUpdate;
  • test.ts (2,1): Cannot find name 'emojiUpdate'.

emojiDelete
emojiDelete;
  • test.ts (2,1): Cannot find name 'emojiDelete'.

GUILD_INTEGRATIONS
GUILD_INTEGRATIONS;
  • test.ts (2,1): Cannot find name 'GUILD_INTEGRATIONS'.

guildIntegrationsUpdate
guildIntegrationsUpdate;
  • test.ts (2,1): Cannot find name 'guildIntegrationsUpdate'.

GUILD_WEBHOOKS
GUILD_WEBHOOKS;
  • test.ts (2,1): Cannot find name 'GUILD_WEBHOOKS'.

webhookUpdate
webhookUpdate;
  • test.ts (2,1): Cannot find name 'webhookUpdate'.

GUILD_INVITES
GUILD_INVITES;
  • test.ts (2,1): Cannot find name 'GUILD_INVITES'.

inviteCreate
inviteCreate;
  • test.ts (2,1): Cannot find name 'inviteCreate'.

inviteDelete
inviteDelete;
  • test.ts (2,1): Cannot find name 'inviteDelete'.

GUILD_VOICE_STATES
GUILD_VOICE_STATES;
  • test.ts (2,1): Cannot find name 'GUILD_VOICE_STATES'.

voiceStateUpdate
voiceStateUpdate;
  • test.ts (2,1): Cannot find name 'voiceStateUpdate'.

GUILD_PRESENCES
GUILD_PRESENCES;
  • test.ts (2,1): Cannot find name 'GUILD_PRESENCES'.

GuildMemberManager#fetch
GuildMemberManager;
#fetch;
  • test.ts (2,1): Cannot find name 'GuildMemberManager'.
  • test.ts (3,1): Cannot find name '#fetch'. Did you mean 'fetch'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GuildMember#fetch
GuildMember;
#fetch;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#fetch'. Did you mean 'fetch'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

User#fetch
User;
#fetch;
  • test.ts (2,1): Cannot find name 'User'.
  • test.ts (3,1): Cannot find name '#fetch'. Did you mean 'fetch'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GuildMemberManager#fetch
GuildMemberManager;
#fetch;
  • test.ts (2,1): Cannot find name 'GuildMemberManager'.
  • test.ts (3,1): Cannot find name '#fetch'. Did you mean 'fetch'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

UserManager#fetch
UserManager;
#fetch;
  • test.ts (2,1): Cannot find name 'UserManager'. Did you mean 'PushManager'?
  • test.ts (3,1): Cannot find name '#fetch'. Did you mean 'fetch'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GUILD_MESSAGES
GUILD_MESSAGES;
  • test.ts (2,1): Cannot find name 'GUILD_MESSAGES'.

message
declare var message: import("discord.js").Message;
message;

messageCreate
messageCreate;
  • test.ts (2,1): Cannot find name 'messageCreate'.

messageUpdate
messageUpdate;
  • test.ts (2,1): Cannot find name 'messageUpdate'.

messageDelete
messageDelete;
  • test.ts (2,1): Cannot find name 'messageDelete'. Did you mean 'MessageEvent'?

messageDeleteBulk
messageDeleteBulk;
  • test.ts (2,1): Cannot find name 'messageDeleteBulk'.

GUILD_MESSAGE_REACTIONS
GUILD_MESSAGE_REACTIONS;
  • test.ts (2,1): Cannot find name 'GUILD_MESSAGE_REACTIONS'.

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

messageReactionRemove
messageReactionRemove;
  • test.ts (2,1): Cannot find name 'messageReactionRemove'.

messageReactionRemoveAll
messageReactionRemoveAll;
  • test.ts (2,1): Cannot find name 'messageReactionRemoveAll'.

messageReactionRemoveEmoji
messageReactionRemoveEmoji;
  • test.ts (2,1): Cannot find name 'messageReactionRemoveEmoji'.

GUILD_MESSAGE_TYPING
GUILD_MESSAGE_TYPING;
  • test.ts (2,1): Cannot find name 'GUILD_MESSAGE_TYPING'.

typingStart
typingStart;
  • test.ts (2,1): Cannot find name 'typingStart'.

DIRECT_MESSAGES
DIRECT_MESSAGES;
  • test.ts (2,1): Cannot find name 'DIRECT_MESSAGES'.

channelCreate
channelCreate;
  • test.ts (2,1): Cannot find name 'channelCreate'.

message
declare var message: import("discord.js").Message;
message;

messageCreate
messageCreate;
  • test.ts (2,1): Cannot find name 'messageCreate'.

messageUpdate
messageUpdate;
  • test.ts (2,1): Cannot find name 'messageUpdate'.

messageDelete
messageDelete;
  • test.ts (2,1): Cannot find name 'messageDelete'. Did you mean 'MessageEvent'?

messageDeleteBulk
messageDeleteBulk;
  • test.ts (2,1): Cannot find name 'messageDeleteBulk'.

DIRECT_MESSAGE_REACTIONS
DIRECT_MESSAGE_REACTIONS;
  • test.ts (2,1): Cannot find name 'DIRECT_MESSAGE_REACTIONS'.

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

messageReactionRemove
messageReactionRemove;
  • test.ts (2,1): Cannot find name 'messageReactionRemove'.

messageReactionRemoveAll
messageReactionRemoveAll;
  • test.ts (2,1): Cannot find name 'messageReactionRemoveAll'.

messageReactionRemoveEmoji
messageReactionRemoveEmoji;
  • test.ts (2,1): Cannot find name 'messageReactionRemoveEmoji'.

DIRECT_MESSAGE_TYPING
DIRECT_MESSAGE_TYPING;
  • test.ts (2,1): Cannot find name 'DIRECT_MESSAGE_TYPING'.

typingStart
typingStart;
  • test.ts (2,1): Cannot find name 'typingStart'.

TODO

TODO

guild
declare var guild: import("discord.js").Guild;
guild;

!
!;
  • test.ts (2,2): Expression expected.

customIdの信頼性に起因するセキュリティ上の問題について

customIdの信頼性に起因するセキュリティ上の問題について

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

Audit Log
Audit;
Log;
  • test.ts (2,1): Cannot find name 'Audit'. Did you mean 'Audio'?
  • test.ts (3,1): Cannot find name 'Log'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

values
values;
  • test.ts (2,1): Cannot find name 'values'.

values
values;
  • test.ts (2,1): Cannot find name 'values'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

values
values;
  • test.ts (2,1): Cannot find name 'values'.

values
values;
  • test.ts (2,1): Cannot find name 'values'.

customId
customId;
  • test.ts (2,1): Cannot find name 'customId'.

井戸端

井戸端

Intents
import { Intents } from "discord.js";
Intents;

new discord.Intents()
import * as discord from "discord.js";
import { Intents } from "discord.js";
new discord.Intents();

例外を握りつぶさない

例外を握りつぶさない

promise.catch(() => { });
promise.catch(() => { });
  • test.ts (2,1): Cannot find name 'promise'. Did you mean 'Promise'?

Snowflake

Snowflake

f(n) = floor(2^(n/log(2)-22)+1420070400000)
f(n) = floor(2 ^ (n / log(2) - 22) + 1420070400000);
  • test.ts (2,1): Cannot find name 'f'.
  • test.ts (2,1): The left-hand side of an assignment expression must be a variable or a property access.
  • test.ts (2,3): Cannot find name 'n'.
  • test.ts (2,8): Cannot find name 'floor'.
  • test.ts (2,19): Cannot find name 'n'.
  • test.ts (2,23): Cannot find name 'log'.

1420070400000
1420070400000;

n=16
n = 16;
  • test.ts (2,1): Cannot find name 'n'.

1422454585791
1422454585791;

1000000000000000000
1000000000000000000;

deferとreplyの違い

deferとreplyの違い

interaction
interaction;
  • test.ts (2,1): Cannot find name 'interaction'.

defer
defer;
  • test.ts (2,1): Cannot find name 'defer'.

defer
defer;
  • test.ts (2,1): Cannot find name 'defer'.

followUp
followUp;
  • test.ts (2,1): Cannot find name 'followUp'.

reply
reply;
  • test.ts (2,1): Cannot find name 'reply'.

followUp
followUp;
  • test.ts (2,1): Cannot find name 'followUp'.

ユーザーがボットかどうか確認する

ユーザーがボットかどうか確認する

.bot
bot;
  • test.ts (2,1): Cannot find name 'bot'.

true
true;

false
false;

message.author.bot
declare var message: import("discord.js").Message;
message.author.bot;

スラッシュコマンドの定義

スラッシュコマンドの定義

name
name;

description
description;
  • test.ts (2,1): Cannot find name 'description'.

value
value;
  • test.ts (2,1): Cannot find name 'value'.

_
_;
  • test.ts (2,1): Cannot find name '_'.

-
-;
  • test.ts (2,2): Expression expected.

name
name;

_
_;
  • test.ts (2,1): Cannot find name '_'.

-
-;
  • test.ts (2,2): Expression expected.

description
description;
  • test.ts (2,1): Cannot find name 'description'.

default_permission
default_permission;
  • test.ts (2,1): Cannot find name 'default_permission'.

options
options;
  • test.ts (2,1): Cannot find name 'options'. Did you mean 'Option'?

[idx]
[idx];
  • test.ts (2,2): Cannot find name 'idx'.

type
type;
  • test.ts (2,1): Cannot find name 'type'.

name
name;

_
_;
  • test.ts (2,1): Cannot find name '_'.

-
-;
  • test.ts (2,2): Expression expected.

description
description;
  • test.ts (2,1): Cannot find name 'description'.

required
required;
  • test.ts (2,1): Cannot find name 'required'. Did you mean 'require'?

false
false;

choices
choices;
  • test.ts (2,1): Cannot find name 'choices'.

[idx]
[idx];
  • test.ts (2,2): Cannot find name 'idx'.

name
name;

value
value;
  • test.ts (2,1): Cannot find name 'value'.

type
type;
  • test.ts (2,1): Cannot find name 'type'.

options
options;
  • test.ts (2,1): Cannot find name 'options'. Did you mean 'Option'?

type
type;
  • test.ts (2,1): Cannot find name 'type'.

サーバーからメンバーを取得する

サーバーからメンバーを取得する

.members.cache
members.cache;
  • test.ts (2,1): Cannot find name 'members'.

guild.members.cache.get('id')
declare var guild: import("discord.js").Guild;
guild.members.cache.get("id");
  • test.ts (3,25): Argument of type '"id"' is not assignable to parameter of type '${bigint}'.

resolve
resolve;
  • test.ts (2,1): Cannot find name 'resolve'.

guild.members.resolve('id')
declare var guild: import("discord.js").Guild;
guild.members.resolve("id");
  • test.ts (3,23): No overload matches this call. Overload 1 of 2, '(resolvable: GuildMember): GuildMember', gave the following error. Argument of type 'string' is not assignable to parameter of type 'GuildMember'. Overload 2 of 2, '(resolvable: GuildMemberResolvable): GuildMember | null', gave the following error. Argument of type '"id"' is not assignable to parameter of type 'GuildMemberResolvable'.

.member()
declare var member: import("discord.js").GuildMember;
member();
  • test.ts (3,1): This expression is not callable. Type 'GuildMember' has no call signatures.

guild.member('id')
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
guild.member("id");
  • test.ts (4,7): Property 'member' does not exist on type 'Guild'. Did you mean 'members'?

guild.fetch()
declare var guild: import("discord.js").Guild;
guild.fetch();

guild.members.fetch('id')
declare var guild: import("discord.js").Guild;
guild.members.fetch("id");
  • test.ts (3,21): No overload matches this call. Overload 1 of 2, '(options: UserResolvable | FetchMemberOptions | (FetchMembersOptions & { user: UserResolvable; })): Promise<...>', gave the following error. Argument of type '"id"' is not assignable to parameter of type 'UserResolvable | FetchMemberOptions | (FetchMembersOptions & { user: UserResolvable; })'. Overload 2 of 2, '(options?: FetchMembersOptions | undefined): Promise<Collection<${bigint}, GuildMember>>', gave the following error. Argument of type '"id"' is not assignable to parameter of type 'FetchMembersOptions | undefined'.

guild.members.fetch({query:username})
declare var guild: import("discord.js").Guild;
guild.members.fetch({ query: username });
  • test.ts (3,30): Cannot find name 'username'.

Guildクラスの.members.cacheでコレクションから取得する

Guildクラスの.members.cacheでコレクションから取得する

.members.cache
members.cache;
  • test.ts (2,1): Cannot find name 'members'.

guild.members.cache.get('id')
declare var guild: import("discord.js").Guild;
guild.members.cache.get("id");
  • test.ts (3,25): Argument of type '"id"' is not assignable to parameter of type '${bigint}'.

resolve
resolve;
  • test.ts (2,1): Cannot find name 'resolve'.

guild.members.resolve('id')
declare var guild: import("discord.js").Guild;
guild.members.resolve("id");
  • test.ts (3,23): No overload matches this call. Overload 1 of 2, '(resolvable: GuildMember): GuildMember', gave the following error. Argument of type 'string' is not assignable to parameter of type 'GuildMember'. Overload 2 of 2, '(resolvable: GuildMemberResolvable): GuildMember | null', gave the following error. Argument of type '"id"' is not assignable to parameter of type 'GuildMemberResolvable'.

.member()
declare var member: import("discord.js").GuildMember;
member();
  • test.ts (3,1): This expression is not callable. Type 'GuildMember' has no call signatures.

guild.member('id')
declare var guild: import("discord.js").Guild;
declare var member: import("discord.js").GuildMember;
guild.member("id");
  • test.ts (4,7): Property 'member' does not exist on type 'Guild'. Did you mean 'members'?

メンバーの権限を確認する

メンバーの権限を確認する

member.permissions.has(permission)
declare var member: import("discord.js").GuildMember;
member.permissions.has(permission);
  • test.ts (3,24): Cannot find name 'permission'. Did you mean 'Permissions'?

'ADMINISTRATOR'
"ADMINISTRATOR";

member.hasPermission(permission)
declare var member: import("discord.js").GuildMember;
member.hasPermission(permission);
  • test.ts (3,8): Property 'hasPermission' does not exist on type 'GuildMember'. Did you mean 'permissions'?
  • test.ts (3,22): Cannot find name 'permission'. Did you mean 'Permissions'?

GuildMember#hasPermission と Permissions#has の違い

GuildMember#hasPermission と Permissions#has の違い

GuildMember#hasPermission
GuildMember;
#hasPermission;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#hasPermission'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GuildMember#permissions.has
GuildMember;
#permissions.has;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#permissions'. Did you mean 'Permissions'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

checkOwner
checkOwner;
  • test.ts (2,1): Cannot find name 'checkOwner'.

false
false;

GuildMember#hasPermission
GuildMember;
#hasPermission;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#hasPermission'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

checkOwner
checkOwner;
  • test.ts (2,1): Cannot find name 'checkOwner'.

true
true;

Permissions#has
Permissions;
#has;
  • test.ts (3,1): Cannot find name '#has'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

Permissions#has
Permissions;
#has;
  • test.ts (3,1): Cannot find name '#has'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

checkAdmin
checkAdmin;
  • test.ts (2,1): Cannot find name 'checkAdmin'.

true
true;

GuildMember#permissions
GuildMember;
#permissions;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#permissions'. Did you mean 'Permissions'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GuildMember
GuildMember;
  • test.ts (2,1): Cannot find name 'GuildMember'.

Permissions.ALL
Permissions.ALL;
  • test.ts (2,13): Property 'ALL' does not exist on type '{ new (): Permissions; prototype: Permissions; }'.

checkOwner
checkOwner;
  • test.ts (2,1): Cannot find name 'checkOwner'.

false
false;

GuildMember#hasPermission
GuildMember;
#hasPermission;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#hasPermission'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

GuildMember#permissions.has
GuildMember;
#permissions.has;
  • test.ts (2,1): Cannot find name 'GuildMember'.
  • test.ts (3,1): Cannot find name '#permissions'. Did you mean 'Permissions'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

MessageAttachment

MessageAttachment

MessageAttachment
MessageAttachment;
  • test.ts (2,1): Cannot find name 'MessageAttachment'.

MessageAttachment#url
MessageAttachment;
#url;
  • test.ts (2,1): Cannot find name 'MessageAttachment'.
  • test.ts (3,1): Cannot find name '#url'. Did you mean 'URL'?
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

サーバーからBANされたユーザーを取得する

サーバーからBANされたユーザーを取得する

guild.fetchBans()
declare var guild: import("discord.js").Guild;
guild.fetchBans();
  • test.ts (3,7): Property 'fetchBans' does not exist on type 'Guild'.

{ user: User, reason: 'BAN理由' }
declare var user: import("discord.js").User;
{
    user: User, reason;
    "BAN\u7406\u7531";
}
  • test.ts (4,11): Cannot find name 'User'. Did you mean 'user'?
  • test.ts (4,11): Left side of comma operator is unused and has no side effects.
  • test.ts (4,17): Cannot find name 'reason'.

guild.fetchBan(user)
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
guild.fetchBan(user);
  • test.ts (4,7): Property 'fetchBan' does not exist on type 'Guild'.

.gitignore

.gitignore

.gitignore
gitignore;
  • test.ts (2,1): Cannot find name 'gitignore'.

*
    * ;
  • test.ts (2,2): Expression expected.
  • test.ts (2,4): Expression expected.

[]
[];

[]
[];

#
#;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

.gitignore
gitignore;
  • test.ts (2,1): Cannot find name 'gitignore'.

fetch

fetch

client.users.cache.get('id')
declare var client: import("discord.js").Client;
client.users.cache.get("id");
  • test.ts (3,24): Argument of type '"id"' is not assignable to parameter of type '${bigint}'.

await client.users.fetch('id')
declare var client: import("discord.js").Client;
await client.users.fetch("id");
  • test.ts (3,1): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (3,1): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (3,26): Argument of type '"id"' is not assignable to parameter of type '${bigint}'.

GlitchでNode.js v14を使う方法

GlitchでNode.js v14を使う方法

//
//

,

Scrapboxの使い方

Scrapboxの使い方

[ ]
[];

[title url]
[title, url];
  • test.ts (2,2): Cannot find name 'title'.
  • test.ts (2,9): Cannot find name 'url'. Did you mean 'URL'?

#
#;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

[ ]
[];

Ctrl+I
Ctrl + I;
  • test.ts (2,1): Cannot find name 'Ctrl'.
  • test.ts (2,8): Cannot find name 'I'.

[自分のユーザー名.icon]
[自分のユーザー名.icon];
  • test.ts (2,2): Cannot find name '自分のユーザー名'.

Pin at home
Pin;
at;
home;
  • test.ts (2,1): Cannot find name 'Pin'.
  • test.ts (3,1): Cannot find name 'at'.
  • test.ts (4,1): Cannot find name 'home'.

Pin at home
Pin;
at;
home;
  • test.ts (2,1): Cannot find name 'Pin'.
  • test.ts (3,1): Cannot find name 'at'.
  • test.ts (4,1): Cannot find name 'home'.

quoted text!
quoted;
text!;
  • test.ts (2,1): Cannot find name 'quoted'.
  • test.ts (3,1): Cannot find name 'text'. Did you mean 'Text'?

messageReactionAddが動作するために必要なもの

messageReactionAddが動作するために必要なもの

partial
partial;
  • test.ts (2,1): Cannot find name 'partial'.

GUILDS
GUILDS;
  • test.ts (2,1): Cannot find name 'GUILDS'.

GUILD_MESSAGES
GUILD_MESSAGES;
  • test.ts (2,1): Cannot find name 'GUILD_MESSAGES'.

GUILD_MESSAGE_REACTIONS
GUILD_MESSAGE_REACTIONS;
  • test.ts (2,1): Cannot find name 'GUILD_MESSAGE_REACTIONS'.

DIRECT_MESSAGES
DIRECT_MESSAGES;
  • test.ts (2,1): Cannot find name 'DIRECT_MESSAGES'.

DIRECT_MESSAGE_REACTIONS
DIRECT_MESSAGE_REACTIONS;
  • test.ts (2,1): Cannot find name 'DIRECT_MESSAGE_REACTIONS'.

v12ではGateway Intentsの指定は不要

v12ではGateway Intentsの指定は不要

全て
全て;
  • test.ts (2,1): Cannot find name '全て'.

(全て - 特権) + 有効化したもの
(全て - 特権) + 有効化したもの;
  • test.ts (2,2): Cannot find name '全て'.
  • test.ts (2,7): Cannot find name '特権'.
  • test.ts (2,13): Cannot find name '有効化したもの'.

Intents.ALL
import { Intents } from "discord.js";
Intents.ALL;
  • test.ts (3,9): Property 'ALL' does not exist on type 'typeof Intents'.

エラーメッセージまとめ

エラーメッセージまとめ

TypeError: fields.flat is not a function
TypeError: fields.flat;
is;
not;
a;
function ();
  • test.ts (2,12): Cannot find name 'fields'.
  • test.ts (3,1): Cannot find name 'is'.
  • test.ts (4,1): Cannot find name 'not'.
  • test.ts (5,1): Cannot find name 'a'.
  • test.ts (6,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (6,10): Identifier expected.

Error [TOKEN_INVALID]: An invalid token was provided.
Error[TOKEN_INVALID];
An;
invalid;
token;
was;
provided.;
  • test.ts (2,1): Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'ErrorConstructor'.
  • test.ts (2,7): Cannot find name 'TOKEN_INVALID'.
  • test.ts (3,1): Cannot find name 'An'.
  • test.ts (4,1): Cannot find name 'invalid'. Did you mean 'oninvalid'?
  • test.ts (5,1): Cannot find name 'token'.
  • test.ts (6,1): Cannot find name 'was'.
  • test.ts (7,1): Cannot find name 'provided'.
  • test.ts (7,10): Identifier expected.

Error: Cannot find module '...'
Error: Cannot;
find;
module "...";
  • test.ts (2,8): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'find'.
  • test.ts (4,8): Only ambient modules can use quoted names.

...

@discordjs/opus
/opus;;
  • test.ts (2,2): Unterminated regular expression literal.

node-opus
node - opus;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (2,8): Cannot find name 'opus'.

TypeError: Cannot read property 'foo' of undefined
TypeError: Cannot;
read;
property;
"foo";
of;
undefined;
  • test.ts (2,12): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'read'.
  • test.ts (4,1): Cannot find name 'property'.
  • test.ts (6,1): Cannot find name 'of'.

'foo'
"foo";

bar.foo
bar.foo;
  • test.ts (2,1): Cannot find name 'bar'.

bar
bar;
  • test.ts (2,1): Cannot find name 'bar'.

DiscordAPIError: Missing Permissions
DiscordAPIError: Missing;
Permissions;
  • test.ts (2,18): Cannot find name 'Missing'.

DiscordAPIError: Two factor is required for this operation
DiscordAPIError: Two;
factor;
is;
required;
for (this; operation;)
    ;
  • test.ts (2,18): Cannot find name 'Two'.
  • test.ts (3,1): Cannot find name 'factor'.
  • test.ts (4,1): Cannot find name 'is'.
  • test.ts (5,1): Cannot find name 'required'. Did you mean 'require'?
  • test.ts (6,12): Cannot find name 'operation'.

DiscordAPIError: Cannot send messages to this user
declare var user: import("discord.js").User;
DiscordAPIError: Cannot;
send;
messages;
to;
this;
user;
  • test.ts (3,18): Cannot find name 'Cannot'.
  • test.ts (4,1): Cannot find name 'send'.
  • test.ts (5,1): Cannot find name 'messages'. Did you mean 'onmessage'?
  • test.ts (6,1): Cannot find name 'to'.

Cannot send an empty message
declare var message: import("discord.js").Message;
Cannot;
send;
an;
empty;
message;
  • test.ts (3,1): Cannot find name 'Cannot'.
  • test.ts (4,1): Cannot find name 'send'.
  • test.ts (5,1): Cannot find name 'an'.
  • test.ts (6,1): Cannot find name 'empty'.

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message listeners added. Use emitter.setMaxListeners() to increase limit
declare var message: import("discord.js").Message;
MaxListenersExceededWarning: Possible;
EventEmitter;
memory;
leak;
detected.;
11;
message;
listeners;
added.Use;
emitter.setMaxListeners();
to;
increase;
limit;
  • test.ts (3,30): Cannot find name 'Possible'.
  • test.ts (4,1): Cannot find name 'EventEmitter'.
  • test.ts (5,1): Cannot find name 'memory'.
  • test.ts (6,1): Cannot find name 'leak'.
  • test.ts (7,1): Cannot find name 'detected'.
  • test.ts (7,10): Identifier expected.
  • test.ts (10,1): Cannot find name 'listeners'.
  • test.ts (11,1): Cannot find name 'added'.
  • test.ts (12,1): Cannot find name 'emitter'.
  • test.ts (13,1): Cannot find name 'to'.
  • test.ts (14,1): Cannot find name 'increase'.
  • test.ts (15,1): Cannot find name 'limit'.

client.on('message', ...)
declare var client: import("discord.js").Client;
client.on("message", ...);
  • test.ts (3,22): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,25): Expression expected.
  • used message Event

TypeError: client.channels.get is not a function
declare var client: import("discord.js").Client;
TypeError: client.channels.get;
is;
not;
a;
function ();
  • test.ts (3,28): Property 'get' does not exist on type 'ChannelManager'.
  • test.ts (4,1): Cannot find name 'is'.
  • test.ts (5,1): Cannot find name 'not'.
  • test.ts (6,1): Cannot find name 'a'.
  • test.ts (7,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (7,10): Identifier expected.

TypeError: message.guild.members.get is not a function
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
TypeError: message.guild.members.get;
is;
not;
a;
function ();
  • test.ts (4,12): Object is possibly 'null'.
  • test.ts (4,34): Property 'get' does not exist on type 'GuildMemberManager'.
  • test.ts (5,1): Cannot find name 'is'.
  • test.ts (6,1): Cannot find name 'not'.
  • test.ts (7,1): Cannot find name 'a'.
  • test.ts (8,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (8,10): Identifier expected.

TypeError: message.channel.messages.get is not a function
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
TypeError: message.channel.messages.get;
is;
not;
a;
function ();
  • test.ts (4,37): Property 'get' does not exist on type 'MessageManager'.
  • test.ts (5,1): Cannot find name 'is'.
  • test.ts (6,1): Cannot find name 'not'.
  • test.ts (7,1): Cannot find name 'a'.
  • test.ts (8,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (8,10): Identifier expected.

TypeError: client.users.get is not a function
declare var client: import("discord.js").Client;
TypeError: client.users.get;
is;
not;
a;
function ();
  • test.ts (3,25): Property 'get' does not exist on type 'UserManager'.
  • test.ts (4,1): Cannot find name 'is'.
  • test.ts (5,1): Cannot find name 'not'.
  • test.ts (6,1): Cannot find name 'a'.
  • test.ts (7,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (7,10): Identifier expected.

SyntaxError: await is only valid in async function
SyntaxError: await is;
only;
valid in async function () { };
  • test.ts (2,14): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (2,14): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (2,20): Cannot find name 'is'.
  • test.ts (3,1): Cannot find name 'only'.
  • test.ts (4,1): Cannot find name 'valid'.

Error: Cannot find module '\node_modules\@discordjs\opus\prebuild\node-v83-napi-v3-win32-ia32-unknown-unknown\opus.node'
Error: Cannot;
find;
module "\node_modules@discordjsopusprebuild\node-v83-napi-v3-win32-ia32-unknown-unknownopus.node";
  • test.ts (2,8): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'find'.
  • test.ts (4,8): Only ambient modules can use quoted names.

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
import { Client } from "discord.js";
TypeError[CLIENT_MISSING_INTENTS];
Valid;
intents;
must;
be;
provided;
for (the; Client.;)
    ;
  • test.ts (3,1): Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'TypeErrorConstructor'.
  • test.ts (3,11): Cannot find name 'CLIENT_MISSING_INTENTS'.
  • test.ts (4,1): Cannot find name 'Valid'.
  • test.ts (5,1): Cannot find name 'intents'.
  • test.ts (6,1): Cannot find name 'must'.
  • test.ts (7,1): Cannot find name 'be'.
  • test.ts (8,1): Cannot find name 'provided'.
  • test.ts (9,6): Cannot find name 'the'.
  • test.ts (9,18): Identifier expected.

ReDoS

ReDoS

^(([a-zA-Z0-9])+)+$
    ^ (([a - zA - Z0 - 9]) + ) + $;
  • test.ts (2,2): Expression expected.
  • test.ts (2,7): Cannot find name 'a'.
  • test.ts (2,11): Cannot find name 'zA'.
  • test.ts (2,16): Cannot find name 'Z0'.
  • test.ts (2,27): Expression expected.
  • test.ts (2,31): Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i --save-dev @types/jquery and then add 'jquery' to the types field in your tsconfig.

^(((0x(0|[1-9A-Fa-F][0-9A-Fa-f]*))|(([1-9][0-9]*)|0)),?)+$
    ^ (((0(0 | [1 - 9, A - Fa - F][0 - 9], A - Fa - f,  * )) | (([1 - 9][0 - 9] * ) | 0)),  ?  : ) + $;
  • test.ts (2,2): Expression expected.
  • test.ts (2,7): This expression is not callable. Type 'Number' has no call signatures.
  • test.ts (2,21): Cannot find name 'A'.
  • test.ts (2,25): Cannot find name 'Fa'.
  • test.ts (2,30): Cannot find name 'F'.
  • test.ts (2,41): Cannot find name 'A'.
  • test.ts (2,45): Cannot find name 'Fa'.
  • test.ts (2,50): Cannot find name 'f'.
  • test.ts (2,54): Expression expected.
  • test.ts (2,56): Expression expected.
  • test.ts (2,80): Expression expected.
  • test.ts (2,90): Expression expected.
  • test.ts (2,93): Expression expected.
  • test.ts (2,95): Expression expected.
  • test.ts (2,99): Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i --save-dev @types/jquery and then add 'jquery' to the types field in your tsconfig.

111111111111111111111111111111111@
1.1111111111111112e+32;

^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$
    ^ ([a - zA - Z0 - 9])(([-.] | [_] + ) ? ([a - zA - Z0 - 9] + ) : ) * ();
{
    1;
}
[a - z0 - 9] + [.];
{
    1;
}
(([a - z]));
{
    2, 3;
}
    | ([a - z]);
{
    2, 3;
}
[.];
{
    1;
}
[a - z];
{
    2, 3;
}
$;
  • test.ts (2,2): Expression expected.
  • test.ts (2,4): This expression is not callable. Type 'number[]' has no call signatures.
  • test.ts (2,6): Cannot find name 'a'.
  • test.ts (2,10): Cannot find name 'zA'.
  • test.ts (2,15): Cannot find name 'Z0'.
  • test.ts (2,25): The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (2,27): Expression expected.
  • test.ts (2,28): Identifier expected.
  • test.ts (2,33): Cannot find name '_'.
  • test.ts (2,38): Expression expected.
  • test.ts (2,44): Cannot find name 'a'.
  • test.ts (2,48): Cannot find name 'zA'.
  • test.ts (2,53): Cannot find name 'Z0'.
  • test.ts (2,63): Expression expected.
  • test.ts (2,67): Expression expected.
  • test.ts (2,72): Expression expected.
  • test.ts (6,1): Operator '+' cannot be applied to types 'number[]' and 'any[]'.
  • test.ts (6,2): Cannot find name 'a'.
  • test.ts (6,6): Cannot find name 'z0'.
  • test.ts (6,17): Expression expected.
  • test.ts (6,18): Identifier expected.
  • test.ts (10,4): Cannot find name 'a'.
  • test.ts (10,8): Cannot find name 'z'.
  • test.ts (12,5): Left side of comma operator is unused and has no side effects.
  • test.ts (14,2): Expression expected.
  • test.ts (14,4): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (14,6): Cannot find name 'a'.
  • test.ts (14,10): Cannot find name 'z'.
  • test.ts (16,5): Left side of comma operator is unused and has no side effects.
  • test.ts (18,2): Expression expected.
  • test.ts (18,3): Identifier expected.
  • test.ts (22,2): Cannot find name 'a'.
  • test.ts (22,6): Cannot find name 'z'.
  • test.ts (24,5): Left side of comma operator is unused and has no side effects.
  • test.ts (26,1): Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i --save-dev @types/jquery and then add 'jquery' to the types field in your tsconfig.

^(([a-z])+.)+[A-Z]([a-z])+$
    ^ (([a - z]) + .) + [A - Z]([a - z]) + $;
  • test.ts (2,2): Expression expected.
  • test.ts (2,7): Cannot find name 'a'.
  • test.ts (2,11): Cannot find name 'z'.
  • test.ts (2,17): Expression expected.
  • test.ts (2,18): Identifier expected.
  • test.ts (2,22): This expression is not callable. Type 'number[]' has no call signatures.
  • test.ts (2,23): Cannot find name 'A'.
  • test.ts (2,27): Cannot find name 'Z'.
  • test.ts (2,31): Cannot find name 'a'.
  • test.ts (2,35): Cannot find name 'z'.
  • test.ts (2,41): Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i --save-dev @types/jquery and then add 'jquery' to the types field in your tsconfig.

IDからユーザーを取得する

IDからユーザーを取得する

.username
username;
  • test.ts (2,1): Cannot find name 'username'.

client.users.fetch('ID')
declare var client: import("discord.js").Client;
client.users.fetch("ID");
  • test.ts (3,20): Argument of type '"ID"' is not assignable to parameter of type '${bigint}'.

await
await;
  • test.ts (2,1): Cannot find name 'await'.

then
then;
  • test.ts (2,1): Cannot find name 'then'.

client.users.cache.get('ID')
declare var client: import("discord.js").Client;
client.users.cache.get("ID");
  • test.ts (3,24): Argument of type '"ID"' is not assignable to parameter of type '${bigint}'.

.cache
cache;
  • test.ts (2,1): Cannot find name 'cache'. Did you mean 'Cache'?

client.users.get('ID')
declare var client: import("discord.js").Client;
client.users.get("ID");
  • test.ts (3,14): Property 'get' does not exist on type 'UserManager'.

ボットをHerokuで動かす方法の初心者向け補足

ボットをHerokuで動かす方法の初心者向け補足

git config --global user.email "you@example.com"
declare var user: import("discord.js").User;
git;
config--;
global;
user.email;
"you@example.com";
  • test.ts (3,1): Cannot find name 'git'.
  • test.ts (4,1): Cannot find name 'config'.
  • test.ts (6,6): Property 'email' does not exist on type 'User'.

git config --global user.name "Your name"
declare var user: import("discord.js").User;
git;
config--;
global;
user.name;
"Your name";
  • test.ts (3,1): Cannot find name 'git'.
  • test.ts (4,1): Cannot find name 'config'.
  • test.ts (6,6): Property 'name' does not exist on type 'User'.

you@example.com
you;
  • test.ts (2,1): Cannot find name 'you'.

Your name
Your;
name;
  • test.ts (2,1): Cannot find name 'Your'.

heroku ps:scale -a アプリケーションの名前 worker=1
heroku;
ps: scale - a;
アプリケーションの名前;
worker = 1;
  • test.ts (2,1): Cannot find name 'heroku'.
  • test.ts (3,5): Cannot find name 'scale'.
  • test.ts (3,13): Cannot find name 'a'.
  • test.ts (4,1): Cannot find name 'アプリケーションの名前'.
  • test.ts (5,1): Cannot find name 'worker'. Did you mean 'Worker'?

メッセージにリアクションを付ける

メッセージにリアクションを付ける

react
react;
  • test.ts (2,1): Cannot find name 'react'.

message.react('🤔')
declare var message: import("discord.js").Message;
message.react("\uD83E\uDD14");

:thinking:
thinking: ;

Emoji.name
Emoji.name;
  • test.ts (2,1): Cannot find name 'Emoji'.

message.react('696208138516561970')
declare var message: import("discord.js").Message;
message.react("696208138516561970");

WIP: デフォルトチャンネルの代替

WIP: デフォルトチャンネルの代替

[some-bot]
[some - bot];
  • test.ts (2,2): Cannot find name 'some'.
  • test.ts (2,9): Cannot find name 'bot'.

collector

collector

.createMessageCollector()
createMessageCollector();
  • test.ts (2,1): Cannot find name 'createMessageCollector'.

.createReactionCollector()
createReactionCollector();
  • test.ts (2,1): Cannot find name 'createReactionCollector'.

collectorとawaitメソッドで指定できる全てのオプションまとめ

collectorとawaitメソッドで指定できる全てのオプションまとめ

{ max: 4, time: 60000, errors: ['time'] }
{
    max: 4, time;
    60000, errors;
    ["time"];
}
  • test.ts (3,10): Left side of comma operator is unused and has no side effects.
  • test.ts (3,13): Cannot find name 'time'.
  • test.ts (4,5): Left side of comma operator is unused and has no side effects.
  • test.ts (4,12): Cannot find name 'errors'. Did you mean 'Error'?

CollectorOptions
CollectorOptions;
  • test.ts (2,1): Cannot find name 'CollectorOptions'.

time: number
time: number;
  • test.ts (2,7): 'number' only refers to a type, but is being used as a value here.

'time'
"time";

idle: number
idle: number;
  • test.ts (2,7): 'number' only refers to a type, but is being used as a value here.

'idle'
"idle";

dispose: boolean
dispose: boolean;
  • test.ts (2,10): 'boolean' only refers to a type, but is being used as a value here.

MessageCollectorOptions
MessageCollectorOptions;
  • test.ts (2,1): Cannot find name 'MessageCollectorOptions'.

ReactionCollectorOptions
ReactionCollectorOptions;
  • test.ts (2,1): Cannot find name 'ReactionCollectorOptions'.

max: number
max: number;
  • test.ts (2,6): 'number' only refers to a type, but is being used as a value here.

'limit'
"limit";

MessageCollectorOptions
MessageCollectorOptions;
  • test.ts (2,1): Cannot find name 'MessageCollectorOptions'.

maxProcessed: number
maxProcessed: number;
  • test.ts (2,15): 'number' only refers to a type, but is being used as a value here.

'processedLimit'
"processedLimit";

ReactionCollectorOptions
ReactionCollectorOptions;
  • test.ts (2,1): Cannot find name 'ReactionCollectorOptions'.

maxEmojis: number
maxEmojis: number;
  • test.ts (2,12): 'number' only refers to a type, but is being used as a value here.

'emojiLimit'
"emojiLimit";

maxUsers: number
maxUsers: number;
  • test.ts (2,11): 'number' only refers to a type, but is being used as a value here.

userLimit
userLimit;
  • test.ts (2,1): Cannot find name 'userLimit'.

AwaitMessagesOptions
AwaitMessagesOptions;
  • test.ts (2,1): Cannot find name 'AwaitMessagesOptions'.

AwaitReactionsOptions
AwaitReactionsOptions;
  • test.ts (2,1): Cannot find name 'AwaitReactionsOptions'.

errors: string[]
errors: string[];
  • test.ts (2,9): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,16): An element access expression should take an argument.

'channelDelete'
"channelDelete";

'guildDelete'
"guildDelete";

'user'
"user";

イベントとawaitメソッド、Collectorの性質の違い

イベントとawaitメソッド、Collectorの性質の違い

message
declare var message: import("discord.js").Message;
message;

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

awaitMessages
awaitMessages;
  • test.ts (2,1): Cannot find name 'awaitMessages'.

awaitReactions
awaitReactions;
  • test.ts (2,1): Cannot find name 'awaitReactions'.

createMessageCollector
createMessageCollector;
  • test.ts (2,1): Cannot find name 'createMessageCollector'.

createReactionCollector
createReactionCollector;
  • test.ts (2,1): Cannot find name 'createReactionCollector'.

author
author;
  • test.ts (2,1): Cannot find name 'author'.

MessageReaction
MessageReaction;
  • test.ts (2,1): Cannot find name 'MessageReaction'.

awaitメソッド

awaitメソッド

awaitReactions
awaitReactions;
  • test.ts (2,1): Cannot find name 'awaitReactions'.

awaitMessages
awaitMessages;
  • test.ts (2,1): Cannot find name 'awaitMessages'.

Clientクラス

Clientクラス

.user
declare var user: import("discord.js").User;
user;

.users
users;
  • test.ts (2,1): Cannot find name 'users'.

.channels
channels;
  • test.ts (2,1): Cannot find name 'channels'.

.guilds
guilds;
  • test.ts (2,1): Cannot find name 'guilds'.

'guildCreate'
"guildCreate";

'guildDelete'
"guildDelete";

'guildMemberAdd'
"guildMemberAdd";

'guildMemberRemove'
"guildMemberRemove";

'channelPinsUpdate'
"channelPinsUpdate";

'messageReactionAdd'
"messageReactionAdd";

2020年10月7日のDiscord APIの仕様変更

2020年10月7日のDiscord APIの仕様変更

client.on('presenceUpdate', ...)
declare var client: import("discord.js").Client;
client.on("presenceUpdate", ...);
  • test.ts (3,29): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,32): Expression expected.

FetchMembersOptions#withPresence
FetchMembersOptions;
#withPresence;
  • test.ts (2,1): Cannot find name 'FetchMembersOptions'.
  • test.ts (3,1): Cannot find name '#withPresence'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

guild.members.fetch(FetchMembersOptions)
declare var guild: import("discord.js").Guild;
guild.members.fetch(FetchMembersOptions);
  • test.ts (3,21): Cannot find name 'FetchMembersOptions'.

client.on('guildMemberAdd', ...)
declare var client: import("discord.js").Client;
client.on("guildMemberAdd", ...);
  • test.ts (3,29): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,32): Expression expected.

client.on('guildMemberUpdate', ...)
declare var client: import("discord.js").Client;
client.on("guildMemberUpdate", ...);
  • test.ts (3,32): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,35): Expression expected.

client.on('guildMemberRemove', ...)
declare var client: import("discord.js").Client;
client.on("guildMemberRemove", ...);
  • test.ts (3,32): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,35): Expression expected.

(query = '', limit = 0 <= n)
(query = "", limit = 0 <= n);
  • test.ts (2,2): Cannot find name 'query'.
  • test.ts (2,14): Cannot find name 'limit'.
  • test.ts (2,27): Cannot find name 'n'.

guild.members.fetch()
declare var guild: import("discord.js").Guild;
guild.members.fetch();

Privileged Intents が影響する処理

Privileged Intents が影響する処理

client.users.cache.get('...')
declare var client: import("discord.js").Client;
client.users.cache.get("...");
  • test.ts (3,24): Argument of type '"..."' is not assignable to parameter of type '${bigint}'.

guild.members.cache.get('...')
declare var guild: import("discord.js").Guild;
guild.members.cache.get("...");
  • test.ts (3,25): Argument of type '"..."' is not assignable to parameter of type '${bigint}'.

guild.members.fetch()
declare var guild: import("discord.js").Guild;
guild.members.fetch();

guild.members.fetch(FetchMembersOptions)
declare var guild: import("discord.js").Guild;
guild.members.fetch(FetchMembersOptions);
  • test.ts (3,21): Cannot find name 'FetchMembersOptions'.

role.members
role.members;
  • test.ts (2,1): Cannot find name 'role'.

client.on('guildMemberAdd', ...)
declare var client: import("discord.js").Client;
client.on("guildMemberAdd", ...);
  • test.ts (3,29): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,32): Expression expected.

client.on('guildMemberRemove', ...)
declare var client: import("discord.js").Client;
client.on("guildMemberRemove", ...);
  • test.ts (3,32): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,35): Expression expected.

client.on('guildMemberUpdate', ...)
declare var client: import("discord.js").Client;
client.on("guildMemberUpdate", ...);
  • test.ts (3,32): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,35): Expression expected.

client.on('presenceUpdate', ...)
declare var client: import("discord.js").Client;
client.on("presenceUpdate", ...);
  • test.ts (3,29): A spread argument must either have a tuple type or be passed to a rest parameter.
  • test.ts (3,32): Expression expected.

<User|Member>.presence
<User | Member>.presence;
  • test.ts (2,2): Cannot find name 'User'.
  • test.ts (2,9): Cannot find name 'Member'.
  • test.ts (2,16): Expression expected.

manager.fetch('id')
manager.fetch("id");
  • test.ts (2,1): Cannot find name 'manager'.

メンバーのキャッシュが必要な処理

メンバーのキャッシュが必要な処理

Guild#members.cache
Guild;
#members.cache;
  • test.ts (2,1): Cannot find name 'Guild'.
  • test.ts (3,1): Cannot find name '#members'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.

ユーザーのキャッシュが必要な処理

ユーザーのキャッシュが必要な処理

Client#users.cache
import { Client } from "discord.js";
Client;
#users.cache;
  • test.ts (4,1): Cannot find name '#users'.
  • test.ts (4,1): Private identifiers are not allowed outside class bodies.

基本的にキャッシュされる

基本的にキャッシュされる

GUILDS
GUILDS;
  • test.ts (2,1): Cannot find name 'GUILDS'.

メッセージの添付ファイルを取得する

メッセージの添付ファイルを取得する

.attachments
attachments;
  • test.ts (2,1): Cannot find name 'attachments'.

message.attachments.map(attachment => attachment.url)
declare var message: import("discord.js").Message;
message.attachments.map(attachment => attachment.url);

Collection

Collection

collection.get('key')
collection.get("key");
  • test.ts (2,1): Cannot find name 'collection'.

object['key']
object["key"];
  • test.ts (2,1): Cannot find name 'object'. Did you mean 'Object'?

マネージャーからデータを取得する

マネージャーからデータを取得する

.cache
cache;
  • test.ts (2,1): Cannot find name 'cache'. Did you mean 'Cache'?

manager.cache.get('id')
manager.cache.get("id");
  • test.ts (2,1): Cannot find name 'manager'.

manager.cache.find(data => data.name === 'name')
manager.cache.find(data => data.name === "name");
  • test.ts (2,1): Cannot find name 'manager'.
  • test.ts (2,20): Parameter 'data' implicitly has an 'any' type.

manager.cache.filter(data => data.name === 'name')
manager.cache.filter(data => data.name === "name");
  • test.ts (2,1): Cannot find name 'manager'.
  • test.ts (2,22): Parameter 'data' implicitly has an 'any' type.

.fetch()
fetch();
  • test.ts (2,1): Expected 1-2 arguments, but got 0.

await manager.fetch('id')
await manager.fetch("id");
  • test.ts (2,1): 'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.
  • test.ts (2,1): Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
  • test.ts (2,7): Cannot find name 'manager'.

マネージャー

マネージャー

.cache
cache;
  • test.ts (2,1): Cannot find name 'cache'. Did you mean 'Cache'?

ボット全体からチャンネルを取得する

ボット全体からチャンネルを取得する

.channels
channels;
  • test.ts (2,1): Cannot find name 'channels'.

client.channels.cache.get('716575590219644929')
declare var client: import("discord.js").Client;
client.channels.cache.get("716575590219644929");

ボット全体からサーバーを取得する

ボット全体からサーバーを取得する

.guilds
guilds;
  • test.ts (2,1): Cannot find name 'guilds'.

client.guilds.cache.get('716575590219644929')
declare var client: import("discord.js").Client;
client.guilds.cache.get("716575590219644929");

Discord API の仕様変更に備えて

Discord API の仕様変更に備えて

new Discord.Client({ ws: { intents: Discord.Intents.NON_PRIVILEGED } })
import * as Discord from "discord.js";
import { Client } from "discord.js";
import { Intents } from "discord.js";
new Discord.Client({ ws: { intents: Discord.Intents.NON_PRIVILEGED } });
  • test.ts (5,28): Type '{ intents: any; }' is not assignable to type 'WebSocketOptions'. Object literal may only specify known properties, and 'intents' does not exist in type 'WebSocketOptions'.
  • test.ts (5,53): Property 'NON_PRIVILEGED' does not exist on type 'typeof Intents'.

new Discord.Client({ ws: { intents: Discord.Intents.ALL } })
import * as Discord from "discord.js";
import { Client } from "discord.js";
import { Intents } from "discord.js";
new Discord.Client({ ws: { intents: Discord.Intents.ALL } });
  • test.ts (5,28): Type '{ intents: any; }' is not assignable to type 'WebSocketOptions'. Object literal may only specify known properties, and 'intents' does not exist in type 'WebSocketOptions'.
  • test.ts (5,53): Property 'ALL' does not exist on type 'typeof Intents'.

Electron で Discord.js を使うとブラウザ版として実行される

Electron で Discord.js を使うとブラウザ版として実行される

window
window;

typeof window !== 'undefined'
typeof window !== "undefined";

typeof process === 'undefined'
typeof process === "undefined";

node_modules/@discordjs/opus/prebuild
node_modules / ;
/opus/prebuild;
  • test.ts (2,1): Cannot find name 'node_modules'.
  • test.ts (2,16): Expression expected.

node-v83-napi-v3-win32-x64-unknown-unknown
node - v83 - napi - v3 - win32 - x64 - unknown - unknown;
  • test.ts (2,1): Cannot find name 'node'. Did you mean 'Node'?
  • test.ts (2,8): Cannot find name 'v83'.
  • test.ts (2,14): Cannot find name 'napi'.
  • test.ts (2,21): Cannot find name 'v3'.
  • test.ts (2,26): Cannot find name 'win32'.
  • test.ts (2,34): Cannot find name 'x64'.
  • test.ts (2,40): 'unknown' only refers to a type, but is being used as a value here.
  • test.ts (2,50): 'unknown' only refers to a type, but is being used as a value here.

electron-v{バージョン}-napi-v3-win32-x64-unknown-unknown
electron - v;
{
    バージョン;
}
-napi - v3 - win32 - x64 - unknown - unknown;
  • test.ts (2,1): Cannot find name 'electron'. Did you mean 'Selection'?
  • test.ts (2,12): Cannot find name 'v'.
  • test.ts (4,5): Cannot find name 'バージョン'.
  • test.ts (6,2): Cannot find name 'napi'.
  • test.ts (6,9): Cannot find name 'v3'.
  • test.ts (6,14): Cannot find name 'win32'.
  • test.ts (6,22): Cannot find name 'x64'.
  • test.ts (6,28): 'unknown' only refers to a type, but is being used as a value here.
  • test.ts (6,38): 'unknown' only refers to a type, but is being used as a value here.

ユーザーのステータスメッセージを取得する

ユーザーのステータスメッセージを取得する

user.presence.activities[0].state
declare var user: import("discord.js").User;
user.presence.activities[0].state;
  • test.ts (3,6): Property 'presence' does not exist on type 'User'.

.state
state;
  • test.ts (2,1): Cannot find name 'state'.

.name
name;

message.author.presence.activities[0].state
declare var message: import("discord.js").Message;
message.author.presence.activities[0].state;
  • test.ts (3,16): Property 'presence' does not exist on type 'User'.

message.author.presence.activities[0].name
declare var message: import("discord.js").Message;
message.author.presence.activities[0].name;
  • test.ts (3,16): Property 'presence' does not exist on type 'User'.

<Activity>.type === 'PLAYING'
<Activity>.type === "PLAYING";
  • test.ts (2,2): Cannot find name 'Activity'.
  • test.ts (2,11): Expression expected.

RPCの制限

RPCの制限

rpc
rpc;
  • test.ts (2,1): Cannot find name 'rpc'.

rpc.api
rpc.api;
  • test.ts (2,1): Cannot find name 'rpc'.

rpc.api
rpc.api;
  • test.ts (2,1): Cannot find name 'rpc'.

rpc
rpc;
  • test.ts (2,1): Cannot find name 'rpc'.

redirectUri
redirectUri;
  • test.ts (2,1): Cannot find name 'redirectUri'.

Discord でのメンションの内部表現

Discord でのメンションの内部表現

\

<@269500497327685633>
<>;
    > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,2): Expression expected.
  • test.ts (3,4): Expression expected.

<@!269500497327685633>
<>;
269500497327685630 > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,22): Expression expected.

<@&700542498837233715>
<>;
    & 700542498837233700 > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,2): Expression expected.
  • test.ts (3,4): The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
  • test.ts (3,25): Expression expected.

@everyone

@here

<#650012034217279498>
<#>650012034217279500 > ;
  • test.ts (2,2): Cannot find name '#'.
  • test.ts (2,3): Invalid character.
  • test.ts (2,25): Expression expected.

<:NAME:ID>
<>;
NAME: ID > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,7): Cannot find name 'ID'.
  • test.ts (3,12): Expression expected.

<:mmLol:216154654256398347>
<>;
mmLol: 216154654256398340 > ;
  • test.ts (2,2): Type expected.
  • test.ts (2,3): Expression expected.
  • test.ts (3,29): Expression expected.

a
a;
  • test.ts (2,1): Cannot find name 'a'.

<a:b1nzy:392938283556143104>
<a>;
b1nzy: 392938283556143100 > ;
  • test.ts (2,2): Cannot find name 'a'.
  • test.ts (2,4): Expression expected.
  • test.ts (3,29): Expression expected.

JavaScriptにsleepは無い

JavaScriptにsleepは無い

while
while ()
    ;
  • test.ts (2,8): Expression expected.

new Date
new Date;

TextChannelクラス

TextChannelクラス

.topic
topic;
  • test.ts (2,1): Cannot find name 'topic'.

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.awaitMessages()
awaitMessages();
  • test.ts (2,1): Cannot find name 'awaitMessages'.

.setName()
setName();
  • test.ts (2,1): Cannot find name 'setName'.

.setRateLimitPerUser()
setRateLimitPerUser();
  • test.ts (2,1): Cannot find name 'setRateLimitPerUser'.

.messages.fetch()
messages.fetch();
  • test.ts (2,1): Cannot find name 'messages'. Did you mean 'onmessage'?

Discord.js v12がリリースされた

Discord.js v12がリリースされた

npm i discord.js
import * as discord from "discord.js";
npm;
i;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

npm i discord.js@11
import * as discord from "discord.js";
npm;
i;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

yarn add discord
import * as discord from "discord.js";
yarn;
add;
discord;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'add'.

yarn add discord.js@11
import * as discord from "discord.js";
yarn;
add;
discord.js;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'add'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

npm i discord.js
import * as discord from "discord.js";
npm;
i;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

npm i discord.js@11
import * as discord from "discord.js";
npm;
i;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

yarn add discord.js@11
import * as discord from "discord.js";
yarn;
add;
discord.js;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'add'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

Gateway APIへ接続してみた

Gateway APIへ接続してみた

https://discordapp.com/api/gateway
https: ; //discordapp.com/api/gateway

{ "url": "wss://gateway.discord.gg/" }
{
    "url";
    "wss://gateway.discord.gg/";
}

https://discordapp.com/api/gateway/bot
https: ; //discordapp.com/api/gateway/bot

?v=6&encoding=json
v = 6 & encoding;
json;
  • test.ts (2,1): Cannot find name 'v'.
  • test.ts (2,9): Cannot find name 'encoding'.
  • test.ts (3,1): Cannot find name 'json'. Did you mean 'JSON'?

wss://gateway.discord.gg/?v=6&encoding=json
wss: ; //gateway.discord.gg/?v=6&encoding=json

v
v;
  • test.ts (2,1): Cannot find name 'v'.

encoding
encoding;
  • test.ts (2,1): Cannot find name 'encoding'.

{ "op": 10, "d": { "heartbeat_interval": 45000 } }
{
    "op";
    10, "d";
    {
        "heartbeat_interval";
        45000;
    }
}
  • test.ts (4,5): Left side of comma operator is unused and has no side effects.

heartbeat_interval
heartbeat_interval;
  • test.ts (2,1): Cannot find name 'heartbeat_interval'.

{ "op": 1, "d": null }
{
    "op";
    1, "d";
    null;
}
  • test.ts (4,5): Left side of comma operator is unused and has no side effects.

{ "op": 2, "d": { "token": "___BOT_TOKEN___", "properties": {} } }
{
    "op";
    2, "d";
    {
        "token";
        "___BOT_TOKEN___", "properties";
        { }
    }
}
  • test.ts (4,5): Left side of comma operator is unused and has no side effects.
  • test.ts (7,9): Left side of comma operator is unused and has no side effects.

properties
properties;
  • test.ts (2,1): Cannot find name 'properties'.

{ "$os": "linux", "$browser": "my_library", "$device": "my_library" }
{
    "$os";
    "linux", "$browser";
    "my_library", "$device";
    "my_library";
}
  • test.ts (4,5): Left side of comma operator is unused and has no side effects.
  • test.ts (5,5): Left side of comma operator is unused and has no side effects.

$browser
$browser;
  • test.ts (2,1): Cannot find name '$browser'.

$device
$device;
  • test.ts (2,1): Cannot find name '$device'.

discord.js
import * as discord from "discord.js";
discord.js;
  • test.ts (3,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

チャンネル名を変更する

チャンネル名を変更する

.setName()
setName();
  • test.ts (2,1): Cannot find name 'setName'.

message.channel.setName('チャンネル名')
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.setName("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D");
  • test.ts (4,17): Property 'setName' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'setName' does not exist on type 'DMChannel'.

client.channels.cache.get('チャンネルID').setName('チャンネル名')
declare var client: import("discord.js").Client;
client.channels.cache.get("\u30C1\u30E3\u30F3\u30CD\u30EBID").setName("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,27): Argument of type '"チャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (3,63): Property 'setName' does not exist on type 'Channel'.

GuildMemberクラス

GuildMemberクラス

message.member
declare var message: import("discord.js").Message;
declare var member: import("discord.js").GuildMember;
message.member;

guild.members.fetch
declare var guild: import("discord.js").Guild;
guild.members.fetch;

guild.members.cache
declare var guild: import("discord.js").Guild;
guild.members.cache;

channel.members
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.members;

.displayName
displayName;
  • test.ts (2,1): Cannot find name 'displayName'.

.nickname
nickname;
  • test.ts (2,1): Cannot find name 'nickname'.

.user
declare var user: import("discord.js").User;
user;

.guild
declare var guild: import("discord.js").Guild;
guild;

.voice.channel
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
voice.channel;
  • test.ts (3,1): Cannot find name 'voice'.

.setNickname()
setNickname();
  • test.ts (2,1): Cannot find name 'setNickname'.

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.ban()
ban();
  • test.ts (2,1): Cannot find name 'ban'.

.kick()
kick();
  • test.ts (2,1): Cannot find name 'kick'.

サーバーからメンバーをキックする

サーバーからメンバーをキックする

member.kick()
declare var member: import("discord.js").GuildMember;
member.kick();

member.kick('kick理由')
declare var member: import("discord.js").GuildMember;
member.kick("kick\u7406\u7531");

v12の主な変更箇所

v12の主な変更箇所

client.users.get
declare var client: import("discord.js").Client;
client.users.get;
  • test.ts (3,14): Property 'get' does not exist on type 'UserManager'.

.get()
get();
  • test.ts (2,1): Cannot find name 'get'.

.find()
find();
  • test.ts (2,1): Cannot find name 'find'.

client.users.cache.get
declare var client: import("discord.js").Client;
client.users.cache.get;

.cache
cache;
  • test.ts (2,1): Cannot find name 'cache'. Did you mean 'Cache'?

client.guilds.get()
declare var client: import("discord.js").Client;
client.guilds.get();
  • test.ts (3,15): Property 'get' does not exist on type 'GuildManager'.

client.guilds.cache.get()
declare var client: import("discord.js").Client;
client.guilds.cache.get();
  • test.ts (3,21): Expected 1 arguments, but got 0.

guild.channels.find()
declare var guild: import("discord.js").Guild;
guild.channels.find();
  • test.ts (3,16): Property 'find' does not exist on type 'GuildChannelManager'.

guild.channels.cache.find()
declare var guild: import("discord.js").Guild;
guild.channels.cache.find();
  • test.ts (3,22): Expected 1-2 arguments, but got 0.

guild.members.filter()
declare var guild: import("discord.js").Guild;
guild.members.filter();
  • test.ts (3,15): Property 'filter' does not exist on type 'GuildMemberManager'.

guild.members.cache.filter()
declare var guild: import("discord.js").Guild;
guild.members.cache.filter();
  • test.ts (3,21): Expected 1-2 arguments, but got 0.

fetchUser
fetchUser;
  • test.ts (2,1): Cannot find name 'fetchUser'.

addRoles
addRoles;
  • test.ts (2,1): Cannot find name 'addRoles'.

client.fetchUser()
declare var client: import("discord.js").Client;
client.fetchUser();
  • test.ts (3,8): Property 'fetchUser' does not exist on type 'Client'.

client.users.fetch()
declare var client: import("discord.js").Client;
client.users.fetch();
  • test.ts (3,14): Expected 1-2 arguments, but got 0.

member.addRoles()
declare var member: import("discord.js").GuildMember;
member.addRoles();
  • test.ts (3,8): Property 'addRoles' does not exist on type 'GuildMember'.

member.roles.add()
declare var member: import("discord.js").GuildMember;
member.roles.add();
  • test.ts (3,14): Expected 1-2 arguments, but got 0.

guild.ban()
declare var guild: import("discord.js").Guild;
guild.ban();
  • test.ts (3,7): Property 'ban' does not exist on type 'Guild'. Did you mean 'bans'?

guild.members.ban()
declare var guild: import("discord.js").Guild;
guild.members.ban();
  • test.ts (3,15): Expected 1-2 arguments, but got 0.

RichEmbed
RichEmbed;
  • test.ts (2,1): Cannot find name 'RichEmbed'.

MessageEmbed
MessageEmbed;
  • test.ts (2,1): Cannot find name 'MessageEmbed'.

.avatarURL({ format: 'png' })
avatarURL({ format: "png" });
  • test.ts (2,1): Cannot find name 'avatarURL'.

user.avatarURL
declare var user: import("discord.js").User;
user.avatarURL;

user.avatarURL()
declare var user: import("discord.js").User;
user.avatarURL();

message.isMemberMentioned(client.user)
declare var message: import("discord.js").Message;
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
message.isMemberMentioned(client.user);
  • test.ts (5,9): Property 'isMemberMentioned' does not exist on type 'Message'.

message.mentions.users.has(client.user.id)
declare var message: import("discord.js").Message;
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
message.mentions.users.has(client.user.id);
  • test.ts (5,28): Object is possibly 'null'.

connection.playFile(stream)
connection.playFile(stream);
  • test.ts (2,1): Cannot find name 'connection'.
  • test.ts (2,21): Cannot find name 'stream'. Did you mean 'MSStream'?

connection.play(stream)
connection.play(stream);
  • test.ts (2,1): Cannot find name 'connection'.
  • test.ts (2,17): Cannot find name 'stream'. Did you mean 'MSStream'?

member.voiceChannel
declare var member: import("discord.js").GuildMember;
member.voiceChannel;
  • test.ts (3,8): Property 'voiceChannel' does not exist on type 'GuildMember'.

member.voice.channel
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
member.voice.channel;

client.ping
declare var client: import("discord.js").Client;
client.ping;
  • test.ts (3,8): Property 'ping' does not exist on type 'Client'.

client.ws.ping
declare var client: import("discord.js").Client;
client.ws.ping;

Glitchを使う上での注意点

Glitchを使う上での注意点

"discord.js": "latest"
"discord.js";
"latest";

?.

キャッシュされていないメッセージへのリアクションを処理する方法

キャッシュされていないメッセージへのリアクションを処理する方法

client.channels.cache.get('チャンネルID').messages.fetch('対象のメッセージID')
declare var client: import("discord.js").Client;
client.channels.cache.get("\u30C1\u30E3\u30F3\u30CD\u30EBID").messages.fetch("\u5BFE\u8C61\u306E\u30E1\u30C3\u30BB\u30FC\u30B8ID");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,27): Argument of type '"チャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (3,63): Property 'messages' does not exist on type 'Channel'.

PowerShell 上で Heroku CLI を使おうとするとエラーが起きる

PowerShell 上で Heroku CLI を使おうとするとエラーが起きる

RemoteSigned
RemoteSigned;
  • test.ts (2,1): Cannot find name 'RemoteSigned'.

Discord.js のインストールまで

Discord.js のインストールまで

start-djs
start - djs;
  • test.ts (2,1): Cannot find name 'start'.
  • test.ts (2,9): Cannot find name 'djs'.

PS D:\Projects\InkoHX\start-djs>
PS;
D: ;
Projects;
InkoHX;
start - djs > ;
  • test.ts (2,1): Cannot find name 'PS'.
  • test.ts (4,1): Cannot find name 'Projects'.
  • test.ts (5,1): Cannot find name 'InkoHX'.
  • test.ts (6,1): Cannot find name 'start'.
  • test.ts (6,9): Cannot find name 'djs'.
  • test.ts (6,15): Expression expected.

start-djs
start - djs;
  • test.ts (2,1): Cannot find name 'start'.
  • test.ts (2,9): Cannot find name 'djs'.

npm install discord.js
import * as discord from "discord.js";
npm;
install;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'install'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

gyp ERR
gyp;
ERR;
  • test.ts (2,1): Cannot find name 'gyp'.
  • test.ts (3,1): Cannot find name 'ERR'.

npm install
npm;
install;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'install'.

GUILD_CREATE イベントが起きたときに起きることメモ

GUILD_CREATE イベントが起きたときに起きることメモ

guild._patch()
declare var guild: import("discord.js").Guild;
guild._patch();
  • test.ts (3,7): Property '_patch' does not exist on type 'Guild'.

channels: GuildChannelManager
channels: GuildChannelManager;
  • test.ts (2,11): Cannot find name 'GuildChannelManager'.

client.channels: ChannelManager
declare var client: import("discord.js").Client;
client.channels;
ChannelManager;
  • test.ts (4,1): Cannot find name 'ChannelManager'.

roles: RoleManager
roles: RoleManager;
  • test.ts (2,8): Cannot find name 'RoleManager'.

members: GuildMemberManager
members: GuildMemberManager;
  • test.ts (2,10): Cannot find name 'GuildMemberManager'.

presences:  PresenceManager
presences: PresenceManager;
  • test.ts (2,12): Cannot find name 'PresenceManager'.

voiceState: VoiceStateManager
voiceState: VoiceStateManager;
  • test.ts (2,13): Cannot find name 'VoiceStateManager'.

emojis: GuildEmojiManager
emojis: GuildEmojiManager;
  • test.ts (2,9): Cannot find name 'GuildEmojiManager'.

guildChannelManager.clear()
guildChannelManager.clear();
  • test.ts (2,1): Cannot find name 'guildChannelManager'.

channelManager.add(channel,guild,cache = true)
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var guild: import("discord.js").Guild;
channelManager.add(channel, guild, cache = true);
  • test.ts (4,1): Cannot find name 'channelManager'.
  • test.ts (4,36): Cannot find name 'cache'. Did you mean 'Cache'?

roleManager.add()
roleManager.add();
  • test.ts (2,1): Cannot find name 'roleManager'.

new Role()
new Role();
  • test.ts (2,5): Cannot find name 'Role'.

role._patch()
role._patch();
  • test.ts (2,1): Cannot find name 'role'.

role._patch()
role._patch();
  • test.ts (2,1): Cannot find name 'role'.

guildMemberManager.add(arg, cache = true)
guildMemberManager.add(arg, cache = true);
  • test.ts (2,1): Cannot find name 'guildMemberManager'.
  • test.ts (2,24): Cannot find name 'arg'.
  • test.ts (2,29): Cannot find name 'cache'. Did you mean 'Cache'?

guildMember._patch( arg )
guildMember._patch(arg);
  • test.ts (2,1): Cannot find name 'guildMember'.
  • test.ts (2,20): Cannot find name 'arg'.

GuildMember
GuildMember;
  • test.ts (2,1): Cannot find name 'GuildMember'.

new
new ;
  • test.ts (2,5): Expression expected.

GuildMember
GuildMember;
  • test.ts (2,1): Cannot find name 'GuildMember'.

guildMember._patch( arg )
guildMember._patch(arg);
  • test.ts (2,1): Cannot find name 'guildMember'.
  • test.ts (2,20): Cannot find name 'arg'.

guildMember._patch( arg )
guildMember._patch(arg);
  • test.ts (2,1): Cannot find name 'guildMember'.
  • test.ts (2,20): Cannot find name 'arg'.

guildMember._patch()
guildMember._patch();
  • test.ts (2,1): Cannot find name 'guildMember'.

userManager.add()
userManager.add();
  • test.ts (2,1): Cannot find name 'userManager'. Did you mean 'PushManager'?

userManager.add()
userManager.add();
  • test.ts (2,1): Cannot find name 'userManager'. Did you mean 'PushManager'?

guildEmojisUpdateAction.handle()
guildEmojisUpdateAction.handle();
  • test.ts (2,1): Cannot find name 'guildEmojisUpdateAction'.

ボットが参加している全サーバーのメンバー数を取得する

ボットが参加している全サーバーのメンバー数を取得する

console.log(client.users.size)
declare var client: import("discord.js").Client;
console.log(client.users.size);
  • test.ts (3,26): Property 'size' does not exist on type 'UserManager'.

console.log(client.guilds.cache.map(guild => guild.memberCount).reduce((p, c) => p + c))
declare var client: import("discord.js").Client;
console.log(client.guilds.cache.map(guild => guild.memberCount).reduce((p, c) => p + c));

サーバー内のチャンネルを取得する

サーバー内のチャンネルを取得する

.channels
channels;
  • test.ts (2,1): Cannot find name 'channels'.

client.channels
declare var client: import("discord.js").Client;
client.channels;

foo
foo;
  • test.ts (2,1): Cannot find name 'foo'.

message.guild.channels.cache.find((channel) => channel.name === "foo");
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.channels.cache.find((channel) => channel.name === "foo");
  • test.ts (4,1): Object is possibly 'null'.

destroy後に再接続する

destroy後に再接続する

client.login(token)
declare var client: import("discord.js").Client;
client.login(token);
  • test.ts (3,14): Cannot find name 'token'.

もし Windows で node-gyp のエラーで詰んでしまった場合にやること

もし Windows で node-gyp のエラーで詰んでしまった場合にやること

npm install --global windows-build-tools
npm;
install--;
global;
windows - build - tools;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'install'.
  • test.ts (5,1): Cannot find name 'windows'. Did you mean 'window'?
  • test.ts (5,11): Cannot find name 'build'.
  • test.ts (5,19): Cannot find name 'tools'.

npm config set python Pythonのパス\python.exe
npm;
config;
set;
python;
Pythonのパス;
python.exe;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'config'.
  • test.ts (4,1): Cannot find name 'set'. Did you mean 'Set'?
  • test.ts (5,1): Cannot find name 'python'.
  • test.ts (6,1): Cannot find name 'Pythonのパス'.
  • test.ts (7,1): Cannot find name 'python'.

npm config set msvs_version 2017
npm;
config;
set;
msvs_version;
2017;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'config'.
  • test.ts (4,1): Cannot find name 'set'. Did you mean 'Set'?
  • test.ts (5,1): Cannot find name 'msvs_version'.

メッセージを削除する

メッセージを削除する

delete
delete ;
  • test.ts (2,7): 'delete' cannot be called on an identifier in strict mode.
  • test.ts (2,7): The operand of a 'delete' operator must be a property reference.
  • test.ts (2,8): Expression expected.

message.delete()
declare var message: import("discord.js").Message;
message.delete();

message.delete({ timeout: 1000 })
declare var message: import("discord.js").Message;
message.delete({ timeout: 1000 });
  • test.ts (3,16): Expected 0 arguments, but got 1.

message.delete(1000)
declare var message: import("discord.js").Message;
message.delete(1000);
  • test.ts (3,16): Expected 0 arguments, but got 1.

Inviteクラス

Inviteクラス

.code
code;
  • test.ts (2,1): Cannot find name 'code'.

.url
url;
  • test.ts (2,1): Cannot find name 'url'. Did you mean 'URL'?

GuildChannelクラス

GuildChannelクラス

.setTopic()
setTopic();
  • test.ts (2,1): Cannot find name 'setTopic'.

.setName()
setName();
  • test.ts (2,1): Cannot find name 'setName'.

.createInvite()
createInvite();
  • test.ts (2,1): Cannot find name 'createInvite'.

サーバーのメンバー数を取得する

サーバーのメンバー数を取得する

.memberCount
memberCount;
  • test.ts (2,1): Cannot find name 'memberCount'.

message.channel.send(message.guild.memberCount)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var guild: import("discord.js").Guild;
message.channel.send(message.guild.memberCount);
  • test.ts (5,22): Object is possibly 'null'.
  • test.ts (5,22): Argument of type 'number' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'.

メンバーのいるボイスチャンネルを移動する

メンバーのいるボイスチャンネルを移動する

member.voice.setChannel(channel)
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
member.voice.setChannel(channel);
  • test.ts (4,25): Argument of type 'Omit<TextChannel, "type"> & Omit<VoiceChannel, "type">' is not assignable to parameter of type 'ChannelResolvable | null'. Property 'type' is missing in type 'Omit<TextChannel, "type"> & Omit<VoiceChannel, "type">' but required in type 'Channel'.

ボイスチャットからユーザーを蹴る

ボイスチャットからユーザーを蹴る

member.voice.kick()
declare var member: import("discord.js").GuildMember;
member.voice.kick();

member.voice.setChannel(null)
declare var member: import("discord.js").GuildMember;
member.voice.setChannel(null);

VoiceState

VoiceState

.kick()
kick();
  • test.ts (2,1): Cannot find name 'kick'.

.setChannel()
setChannel();
  • test.ts (2,1): Cannot find name 'setChannel'.

ping値を取得する

ping値を取得する

client.ws.ping
declare var client: import("discord.js").Client;
client.ws.ping;

client.ping
declare var client: import("discord.js").Client;
client.ping;
  • test.ts (3,8): Property 'ping' does not exist on type 'Client'.

再起動コマンドを作る

再起動コマンドを作る

process.exit()
process.exit();

client.destoroy()
declare var client: import("discord.js").Client;
client.destoroy();
  • test.ts (3,8): Property 'destoroy' does not exist on type 'Client'. Did you mean 'destroy'?

低速モードを設定する

低速モードを設定する

.setRateLimitPerUser()
setRateLimitPerUser();
  • test.ts (2,1): Cannot find name 'setRateLimitPerUser'.

message.channel.setRateLimitPerUser(5)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.setRateLimitPerUser(5);
  • test.ts (4,17): Property 'setRateLimitPerUser' does not exist on type 'TextChannel | DMChannel | NewsChannel | ThreadChannel'. Property 'setRateLimitPerUser' does not exist on type 'DMChannel'.

Discordのタイピング表示に関する挙動

Discordのタイピング表示に関する挙動

typingStart
typingStart;
  • test.ts (2,1): Cannot find name 'typingStart'.

typingStop
typingStop;
  • test.ts (2,1): Cannot find name 'typingStop'.

stopTyping
stopTyping;
  • test.ts (2,1): Cannot find name 'stopTyping'.

startTyping
startTyping;
  • test.ts (2,1): Cannot find name 'startTyping'.

stopTyping
stopTyping;
  • test.ts (2,1): Cannot find name 'stopTyping'.

メンバーのサーバー内での表示名を取得する

メンバーのサーバー内での表示名を取得する

displayName
displayName;
  • test.ts (2,1): Cannot find name 'displayName'.

message.channel.send(message.member.displayName)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var member: import("discord.js").GuildMember;
message.channel.send(message.member.displayName);
  • test.ts (5,22): Object is possibly 'null'.

メンバーのニックネームを取得する

メンバーのニックネームを取得する

.nickname
nickname;
  • test.ts (2,1): Cannot find name 'nickname'.

message.channel.send(message.member.nickname)
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
declare var member: import("discord.js").GuildMember;
message.channel.send(message.member.nickname);
  • test.ts (5,22): Object is possibly 'null'.
  • test.ts (5,22): Argument of type 'string | null' is not assignable to parameter of type 'string | MessagePayload | MessageOptions'. Type 'null' is not assignable to type 'string | MessagePayload | MessageOptions'.

Cannot read property 'includes' of nullに対処する

Cannot read property 'includes' of nullに対処する

channel.topic.includes('foo')
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.topic.includes("foo");
  • test.ts (3,1): Object is possibly 'null'.

Cannot read property 'includes' of null
Cannot;
read;
property;
"includes";
of;
null;
  • test.ts (2,1): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'read'.
  • test.ts (4,1): Cannot find name 'property'.
  • test.ts (6,1): Cannot find name 'of'.

.topic
topic;
  • test.ts (2,1): Cannot find name 'topic'.

Type: ?string
Type:  ? string : ;
  • test.ts (2,8): Expression expected.
  • test.ts (2,10): 'string' only refers to a type, but is being used as a value here.
  • test.ts (2,19): Expression expected.

string
string;
  • test.ts (2,1): 'string' only refers to a type, but is being used as a value here.

?

.channels.cache
channels.cache;
  • test.ts (2,1): Cannot find name 'channels'.

Cannot read property 'includes' of undefined
Cannot;
read;
property;
"includes";
of;
undefined;
  • test.ts (2,1): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'read'.
  • test.ts (4,1): Cannot find name 'property'.
  • test.ts (6,1): Cannot find name 'of'.

.topic
topic;
  • test.ts (2,1): Cannot find name 'topic'.

null
null;

''
"";

channel.topic && channel.topic.includes('foo')
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.topic && channel.topic.includes("foo");

channel.topic
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.topic;

channel.topic.includes('foo')
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.topic.includes("foo");
  • test.ts (3,1): Object is possibly 'null'.

channel.topic?.includes('foo')
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.topic?.includes("foo");

?

?.

Messageクラス

Messageクラス

client.on('message', message => {})
declare var client: import("discord.js").Client;
client.on("message", message => { });
  • used message Event

.attachments
attachments;
  • test.ts (2,1): Cannot find name 'attachments'.

.author
author;
  • test.ts (2,1): Cannot find name 'author'.

.content
content;
  • test.ts (2,1): Cannot find name 'content'.

.channel
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel;

.guild
declare var guild: import("discord.js").Guild;
guild;

.member
declare var member: import("discord.js").GuildMember;
member;

.system
system;
  • test.ts (2,1): Cannot find name 'system'.

.type
type;
  • test.ts (2,1): Cannot find name 'type'.

.delete()
delete ();
  • test.ts (2,9): The operand of a 'delete' operator must be a property reference.
  • test.ts (2,9): Expression expected.

.edit()
edit();
  • test.ts (2,1): Cannot find name 'edit'.

.react()
react();
  • test.ts (2,1): Cannot find name 'react'.

対象のメッセージの上下にあるメッセージを取得する

対象のメッセージの上下にあるメッセージを取得する

messages
messages;
  • test.ts (2,1): Cannot find name 'messages'. Did you mean 'onmessage'?

fetch
fetch;

around
around;
  • test.ts (2,1): Cannot find name 'around'.

around
around;
  • test.ts (2,1): Cannot find name 'around'.

catch
try { }
catch { }

メッセージを送信する

メッセージを送信する

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.send('メッセージ')
send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (2,1): Cannot find name 'send'.

.send({ files: ['https://picsum.photos/200'] })
send({ files: ["https://picsum.photos/200"] });
  • test.ts (2,1): Cannot find name 'send'.

.send(new Discord.MessageEmbed().setTitle('タイトル'))
import * as Discord from "discord.js";
send(new Discord.MessageEmbed().setTitle("\u30BF\u30A4\u30C8\u30EB"));
  • test.ts (3,1): Cannot find name 'send'.

.send({ embed: { title: 'タイトル' } })
send({ embed: { title: "\u30BF\u30A4\u30C8\u30EB" } });
  • test.ts (2,1): Cannot find name 'send'.

.send(new Discord.MessageAttachment())
import * as Discord from "discord.js";
send(new Discord.MessageAttachment());
  • test.ts (3,1): Cannot find name 'send'.
  • test.ts (3,6): Expected 1-3 arguments, but got 0.

Discordでの絵文字の扱い

Discordでの絵文字の扱い

:thinking:
thinking: ;

🤔

U+FE0F
U + FE0F;
  • test.ts (2,1): Cannot find name 'U'.
  • test.ts (2,5): Cannot find name 'FE0F'.

U+FE0F
U + FE0F;
  • test.ts (2,1): Cannot find name 'U'.
  • test.ts (2,5): Cannot find name 'FE0F'.

isMentionedとisMemberMentionedとmentions.hasの違い

isMentionedとisMemberMentionedとmentions.hasの違い

isMentioned
isMentioned;
  • test.ts (2,1): Cannot find name 'isMentioned'.

isMemberMentioned
isMemberMentioned;
  • test.ts (2,1): Cannot find name 'isMemberMentioned'.

mentions.has
mentions.has;
  • test.ts (2,1): Cannot find name 'mentions'.

mentions.has
mentions.has;
  • test.ts (2,1): Cannot find name 'mentions'.

isMentioned
isMentioned;
  • test.ts (2,1): Cannot find name 'isMentioned'.

isMemberMentioned
isMemberMentioned;
  • test.ts (2,1): Cannot find name 'isMemberMentioned'.

mention.has
mention.has;
  • test.ts (2,1): Cannot find name 'mention'.

isMemberMentioned
isMemberMentioned;
  • test.ts (2,1): Cannot find name 'isMemberMentioned'.

POSTでボットからDMにメッセージを送信する

POSTでボットからDMにメッセージを送信する

id
id;
  • test.ts (2,1): Cannot find name 'id'.

VoiceChannelクラス

VoiceChannelクラス

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

.setName()
setName();
  • test.ts (2,1): Cannot find name 'setName'.

SyntaxError

SyntaxError

^
    ^ ;
  • test.ts (2,2): Expression expected.
  • test.ts (2,4): Expression expected.

Unexpected token '〇〇'
Unexpected;
token;
"\u3007\u3007";
  • test.ts (2,1): Cannot find name 'Unexpected'.
  • test.ts (3,1): Cannot find name 'token'.

〇〇
〇〇;
  • test.ts (2,1): Cannot find name '〇〇'.

missing ) after argument list
missing;
after;
argument;
list;
  • test.ts (2,1): Cannot find name 'missing'.
  • test.ts (3,1): Cannot find name 'after'.
  • test.ts (4,1): Cannot find name 'argument'.
  • test.ts (5,1): Cannot find name 'list'.

)

ボイスチャンネルに参加しているメンバーを取得する

ボイスチャンネルに参加しているメンバーを取得する

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

console.log(vc.members.size)
console.log(vc.members.size);
  • test.ts (2,13): Cannot find name 'vc'.

Guildクラス

Guildクラス

client.guilds.cache.get(id)
declare var client: import("discord.js").Client;
client.guilds.cache.get(id);
  • test.ts (3,25): Cannot find name 'id'.

message.guild
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild;

member.guild
declare var member: import("discord.js").GuildMember;
declare var guild: import("discord.js").Guild;
member.guild;

.name
name;

.me
me;
  • test.ts (2,1): Cannot find name 'me'.

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

.memberCount
memberCount;
  • test.ts (2,1): Cannot find name 'memberCount'.

.channels
channels;
  • test.ts (2,1): Cannot find name 'channels'.

.member(user)
declare var member: import("discord.js").GuildMember;
declare var user: import("discord.js").User;
member(user);
  • test.ts (4,1): This expression is not callable. Type 'GuildMember' has no call signatures.

.iconURL()
iconURL();
  • test.ts (2,1): Cannot find name 'iconURL'.

.fetchInvites()
fetchInvites();
  • test.ts (2,1): Cannot find name 'fetchInvites'.

絶対に eval を使うな!

絶対に eval を使うな!

eval
eval;

eval
eval;

eval
eval;

eval
eval;

require
require;

process
process;

setTimeout
setTimeout;

setInterval
setInterval;

日時の表示を日本時間にする

日時の表示を日本時間にする

toLocaleString
  • Error: Debug Failure. Unhandled SyntaxKind: Unknown. at pipelineEmitWithHintWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104814:22) at pipelineEmitWithHint (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104364:17) at pipelineEmitWithComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107818:13) at pipelineEmit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104304:13) at emit (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:104277:13) at emitNodeList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107065:25) at emitList (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106952:13) at emitSourceFileWorker (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106683:13) at emitBodyWithDetachedComments (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:107934:17) at emitSourceFile (D:\develop\djs-jp\fetch-all-code-from-scrapbox\node_modules\typescript\lib\typescript.js:106604:21)

new Date().toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo' })
new Date().toLocaleString("ja-JP", { timeZone: "Asia/Tokyo" });

'2020/5/27 9:23:13'
"2020/5/27 9:23:13";

'en-US'
"en-US";

'5/27/2020, 9:23:21 AM'
"5/27/2020, 9:23:21 AM";

process.env.TZ
process.env.TZ;

process.env.TZ = 'Asia/Tokyo'
process.env.TZ = "Asia/Tokyo";

なぜv12でデフォルトのformatがwebpなのかについての考察

なぜv12でデフォルトのformatがwebpなのかについての考察

avatarURL()
avatarURL();
  • test.ts (2,1): Cannot find name 'avatarURL'.

avatarURL({ format: 'jpg' })
avatarURL({ format: "jpg" });
  • test.ts (2,1): Cannot find name 'avatarURL'.

filterを使って指定した条件で絞り込む

filterを使って指定した条件で絞り込む

.filter()
filter();
  • test.ts (2,1): Cannot find name 'filter'. Did you mean 'File'?

mapやfilterを活用しよう

mapやfilterを活用しよう

map
map;
  • test.ts (2,1): Cannot find name 'map'. Did you mean 'Map'?

filter
filter;
  • test.ts (2,1): Cannot find name 'filter'. Did you mean 'File'?

mapでデータを加工する

mapでデータを加工する

.map()
map();
  • test.ts (2,1): Cannot find name 'map'. Did you mean 'Map'?

.map()
map();
  • test.ts (2,1): Cannot find name 'map'. Did you mean 'Map'?

[1, 2, 3].map(n => n * 2)
[1, 2, 3].map(n => n * 2);

[2, 4, 6]
[2, 4, 6];

1
1;

n => n * 2
n => n * 2;
  • test.ts (2,1): Parameter 'n' implicitly has an 'any' type.

message.member.roles.cache.map(role => role.name)
declare var message: import("discord.js").Message;
declare var member: import("discord.js").GuildMember;
message.member.roles.cache.map(role => role.name);
  • test.ts (4,1): Object is possibly 'null'.

システムメッセージであるかを判定する

システムメッセージであるかを判定する

.system
system;
  • test.ts (2,1): Cannot find name 'system'.

メッセージの種類を判定する

メッセージの種類を判定する

.type
type;
  • test.ts (2,1): Cannot find name 'type'.

'DEFAULT'
"DEFAULT";

'PINS_ADD'
"PINS_ADD";

なぜボットを起動した後に送信されたメッセージにしか反応しないか

なぜボットを起動した後に送信されたメッセージにしか反応しないか

messageReactionAdd
messageReactionAdd;
  • test.ts (2,1): Cannot find name 'messageReactionAdd'.

client.on('messageReactionAdd', reaction => reaction.message.content)
declare var client: import("discord.js").Client;
declare var message: import("discord.js").Message;
client.on("messageReactionAdd", reaction => reaction.message.content);
  • test.ts (4,1): No overload matches this call. Overload 1 of 2, '(event: "messageReactionAdd", listener: (message: MessageReaction | PartialMessageReaction, user: User | PartialUser) => Awaited<...>): Client', gave the following error. Type 'string | null' is not assignable to type 'Awaited'. Type 'null' is not assignable to type 'Awaited'. Overload 2 of 2, '(event: never, listener: (...args: any[]) => Awaited): Client', gave the following error. Argument of type 'string' is not assignable to parameter of type 'never'.

Raw Events

Raw Events

raw
raw;
  • test.ts (2,1): Cannot find name 'raw'.

文字列内に含まれているか確認する

文字列内に含まれているか確認する

includes
includes;
  • test.ts (2,1): Cannot find name 'includes'.

abc
abc;
  • test.ts (2,1): Cannot find name 'abc'.

b
b;
  • test.ts (2,1): Cannot find name 'b'.

'abc'.includes('b')
"abc".includes("b");

includes
includes;
  • test.ts (2,1): Cannot find name 'includes'.

インストールされたDiscord.jsのバージョンを確認する方法

インストールされたDiscord.jsのバージョンを確認する方法

console.log(require('discord.js').version)
console.log(require("discord.js").version);

npm ls discord.js
import * as discord from "discord.js";
npm;
ls;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'ls'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

yarn list discord.js
import * as discord from "discord.js";
yarn;
list;
discord.js;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'list'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

discord.js@11.6.1
import * as discord from "discord.js";
discord.js;
0.1;
  • test.ts (3,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

discord.js@12.0.1
import * as discord from "discord.js";
discord.js;
0.1;
  • test.ts (3,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

@

11
11;

12
12;

自身が付けたリアクションを消す

自身が付けたリアクションを消す

message.reactions.cache.get('🤔').users.remove()
declare var message: import("discord.js").Message;
message.reactions.cache.get("\uD83E\uDD14").users.remove();
  • test.ts (3,1): Object is possibly 'undefined'.

特定のユーザーのリアクションのみを消す

特定のユーザーのリアクションのみを消す

message.reactions.cache.get('🤔').users.remove(user)
declare var message: import("discord.js").Message;
declare var user: import("discord.js").User;
message.reactions.cache.get("\uD83E\uDD14").users.remove(user);
  • test.ts (4,1): Object is possibly 'undefined'.

メッセージから特定のリアクションのみを全て消す

メッセージから特定のリアクションのみを全て消す

delete
delete ;
  • test.ts (2,7): 'delete' cannot be called on an identifier in strict mode.
  • test.ts (2,7): The operand of a 'delete' operator must be a property reference.
  • test.ts (2,8): Expression expected.

message.reactions.cache.get('🤔').remove()
declare var message: import("discord.js").Message;
message.reactions.cache.get("\uD83E\uDD14").remove();
  • test.ts (3,1): Object is possibly 'undefined'.

UnhandledPromiseRejectionWarningに関する考察

UnhandledPromiseRejectionWarningに関する考察

.catch(() => {})
try { }
catch () { }
() => { };
  • test.ts (3,8): Identifier expected.

--trace-warnings
--trace - warnings;
  • test.ts (2,3): Cannot find name 'trace'.
  • test.ts (2,11): Cannot find name 'warnings'.

--unhandled-rejections=warn
--unhandled - rejections;
warn;
  • test.ts (2,3): Cannot find name 'unhandled'.
  • test.ts (2,15): Cannot find name 'rejections'.
  • test.ts (3,1): Cannot find name 'warn'.

--unhandled-rejections=warn
--unhandled - rejections;
warn;
  • test.ts (2,3): Cannot find name 'unhandled'.
  • test.ts (2,15): Cannot find name 'rejections'.
  • test.ts (3,1): Cannot find name 'warn'.

配列を連結して文字列にする

配列を連結して文字列にする

join
join;
  • test.ts (2,1): Cannot find name 'join'.

['1', '2', '3'].join(' ')
["1", "2", "3"].join(" ");

'1 2 3'
"1 2 3";

['1', '2', '3'].join('')
["1", "2", "3"].join("");

'123'
"123";

'\n'
"\n";

['1', '2', '3'].join('\n')
["1", "2", "3"].join("\n");

'1\n2\n3'
"1\n2\n3";

\n
n;
  • test.ts (2,1): Cannot find name 'n'.

メンバーの参加しているボイスチャンネルを取得する

メンバーの参加しているボイスチャンネルを取得する

member.voice.channel
declare var member: import("discord.js").GuildMember;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
member.voice.channel;

.voice
voice;
  • test.ts (2,1): Cannot find name 'voice'.

.channel
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel;

.channel
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel;

指定したチャンネルにメッセージを送信する方法まとめ

指定したチャンネルにメッセージを送信する方法まとめ

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.cache
cache;
  • test.ts (2,1): Cannot find name 'cache'. Did you mean 'Cache'?

message.channel.send('メッセージ')
declare var message: import("discord.js").Message;
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
message.channel.send("\u30E1\u30C3\u30BB\u30FC\u30B8");

message.guild.channels.cache.get('チャンネルID').send('メッセージ')
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.channels.cache.get("\u30C1\u30E3\u30F3\u30CD\u30EBID").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (4,1): Object is possibly 'null'.
  • test.ts (4,1): Object is possibly 'undefined'.
  • test.ts (4,34): Argument of type '"チャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (4,70): Property 'send' does not exist on type 'GuildChannel | ThreadChannel'. Property 'send' does not exist on type 'GuildChannel'.

message.guild.channels.cache.find(ch => ch.name === 'チャンネル名').send('メッセージ')
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.channels.cache.find(ch => ch.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (4,1): Object is possibly 'null'.
  • test.ts (4,1): Object is possibly 'undefined'.
  • test.ts (4,93): Property 'send' does not exist on type 'GuildChannel | ThreadChannel'. Property 'send' does not exist on type 'GuildChannel'.

message.guild.channels.cache.filter(ch => ch.name === 'チャンネル名').forEach(ch => ch.send('メッセージ'))
declare var message: import("discord.js").Message;
declare var guild: import("discord.js").Guild;
message.guild.channels.cache.filter(ch => ch.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D").forEach(ch => ch.send("\u30E1\u30C3\u30BB\u30FC\u30B8"));
  • test.ts (4,1): Object is possibly 'null'.
  • test.ts (4,112): Property 'send' does not exist on type 'GuildChannel | ThreadChannel'. Property 'send' does not exist on type 'GuildChannel'.

client.channels.cache.get('チャンネルID').send('メッセージ')
declare var client: import("discord.js").Client;
client.channels.cache.get("\u30C1\u30E3\u30F3\u30CD\u30EBID").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,27): Argument of type '"チャンネルID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (3,63): Property 'send' does not exist on type 'Channel'.

client.channels.cache.find(ch => ch.name === 'チャンネル名').send('メッセージ')
declare var client: import("discord.js").Client;
client.channels.cache.find(ch => ch.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,37): Property 'name' does not exist on type 'Channel'.
  • test.ts (3,86): Property 'send' does not exist on type 'Channel'.

client.channels.cache.filter(ch => ch.name === 'チャンネル名').forEach(ch => ch.send('メッセージ'))
declare var client: import("discord.js").Client;
client.channels.cache.filter(ch => ch.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D").forEach(ch => ch.send("\u30E1\u30C3\u30BB\u30FC\u30B8"));
  • test.ts (3,39): Property 'name' does not exist on type 'Channel'.
  • test.ts (3,105): Property 'send' does not exist on type 'Channel'.

client.guilds.cache.get('サーバーID').channels.cache.find(ch => ch.name === 'チャンネル名').send('メッセージ')
declare var client: import("discord.js").Client;
client.guilds.cache.get("\u30B5\u30FC\u30D0\u30FCID").channels.cache.find(ch => ch.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D").send("\u30E1\u30C3\u30BB\u30FC\u30B8");
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,25): Argument of type '"サーバーID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (3,133): Property 'send' does not exist on type 'GuildChannel | ThreadChannel'. Property 'send' does not exist on type 'GuildChannel'.

client.guilds.cache.get('サーバーID').channels.cache.filter(ch => ch.name === 'チャンネル名').forEach(ch => ch.send('メッセージ'))
declare var client: import("discord.js").Client;
client.guilds.cache.get("\u30B5\u30FC\u30D0\u30FCID").channels.cache.filter(ch => ch.name === "\u30C1\u30E3\u30F3\u30CD\u30EB\u540D").forEach(ch => ch.send("\u30E1\u30C3\u30BB\u30FC\u30B8"));
  • test.ts (3,1): Object is possibly 'undefined'.
  • test.ts (3,25): Argument of type '"サーバーID"' is not assignable to parameter of type '${bigint}'.
  • test.ts (3,152): Property 'send' does not exist on type 'GuildChannel | ThreadChannel'. Property 'send' does not exist on type 'GuildChannel'.

サーバーから全てのメンバーを取得する

サーバーから全てのメンバーを取得する

guild.members.fetch()
declare var guild: import("discord.js").Guild;
guild.members.fetch();

guild.members.cache
declare var guild: import("discord.js").Guild;
guild.members.cache;

.fetch()
fetch();
  • test.ts (2,1): Expected 1-2 arguments, but got 0.

ピン留めが更新されたときに処理を実行する

ピン留めが更新されたときに処理を実行する

channelPinsUpdate
channelPinsUpdate;
  • test.ts (2,1): Cannot find name 'channelPinsUpdate'.

チャンネルトピックを取得する

チャンネルトピックを取得する

.topic
topic;
  • test.ts (2,1): Cannot find name 'topic'.

引き続きDiscord.js v11をインストールする方法

引き続きDiscord.js v11をインストールする方法

discord.js@11
import * as discord from "discord.js";
discord.js;
  • test.ts (3,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

npm i discord.js
import * as discord from "discord.js";
npm;
i;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

npm i discord.js@11
import * as discord from "discord.js";
npm;
i;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'i'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

yarn add discord.js
import * as discord from "discord.js";
yarn;
add;
discord.js;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'add'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

yarn add discord.js@11
import * as discord from "discord.js";
yarn;
add;
discord.js;
  • test.ts (3,1): Cannot find name 'yarn'.
  • test.ts (4,1): Cannot find name 'add'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

MessageReactionクラス

MessageReactionクラス

.message
declare var message: import("discord.js").Message;
message;

.emoji
emoji;
  • test.ts (2,1): Cannot find name 'emoji'.

メッセージを一括削除する

メッセージを一括削除する

.bulkDelete()
bulkDelete();
  • test.ts (2,1): Cannot find name 'bulkDelete'.

channel.bulkDelete(5)
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.bulkDelete(5);

channel.bulkDelete(messages)
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.bulkDelete(messages);
  • test.ts (3,20): Cannot find name 'messages'. Did you mean 'onmessage'?

チャンネルに送信された過去のメッセージを取得する

チャンネルに送信された過去のメッセージを取得する

channel.messages.fetch()
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.messages.fetch();

channel.messages.fetch('99539446449315840')
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.messages.fetch("99539446449315840");

channel.messages.fetch({ limit: 10 })
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.messages.fetch({ limit: 10 });

Channelクラス

Channelクラス

.type
type;
  • test.ts (2,1): Cannot find name 'type'.

質問対応用手引き

質問対応用手引き

npm ls discord.js
import * as discord from "discord.js";
npm;
ls;
discord.js;
  • test.ts (3,1): Cannot find name 'npm'.
  • test.ts (4,1): Cannot find name 'ls'.
  • test.ts (5,9): Property 'js' does not exist on type 'typeof import("D:/develop/djs-jp/fetch-all-code-from-scrapbox/node_modules/discord.js/typings/index")'.

^12.2.0
    ^ 12.2;
0;
  • test.ts (2,2): Expression expected.

"engines": { "node": ">=12.0.0" }
"engines";
{
    "node";
    ">=12.0.0";
}

fields.flat is not a function
fields.flat;
is;
not;
a;
function ();
  • test.ts (2,1): Cannot find name 'fields'.
  • test.ts (3,1): Cannot find name 'is'.
  • test.ts (4,1): Cannot find name 'not'.
  • test.ts (5,1): Cannot find name 'a'.
  • test.ts (6,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (6,10): Identifier expected.

client.channels.get is not a function
declare var client: import("discord.js").Client;
client.channels.get;
is;
not;
a;
function ();
  • test.ts (3,17): Property 'get' does not exist on type 'ChannelManager'.
  • test.ts (4,1): Cannot find name 'is'.
  • test.ts (5,1): Cannot find name 'not'.
  • test.ts (6,1): Cannot find name 'a'.
  • test.ts (7,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (7,10): Identifier expected.

is not a function
is;
not;
a;
function ();
  • test.ts (2,1): Cannot find name 'is'.
  • test.ts (3,1): Cannot find name 'not'.
  • test.ts (4,1): Cannot find name 'a'.
  • test.ts (5,9): '(Missing)', which lacks return-type annotation, implicitly has an 'any' return type.
  • test.ts (5,10): Identifier expected.

Cannot read property
Cannot;
read;
property;
  • test.ts (2,1): Cannot find name 'Cannot'.
  • test.ts (3,1): Cannot find name 'read'.
  • test.ts (4,1): Cannot find name 'property'.

ステータスメッセージを設定する

ステータスメッセージを設定する

client.user.setActivity('hi!')
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
client.user.setActivity("hi!");
  • test.ts (4,1): Object is possibly 'null'.

client.user.setActivity('hi!', { type: 'WATCHING' })
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
client.user.setActivity("hi!", { type: "WATCHING" });
  • test.ts (4,1): Object is possibly 'null'.

'PLAYING'
"PLAYING";

'STREAMING'
"STREAMING";

'LISTENING'
"LISTENING";

'WATCHING'
"WATCHING";

メッセージが送信されたチャンネルを取得する

メッセージが送信されたチャンネルを取得する

.channel
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel;

メッセージから本文を取得する

メッセージから本文を取得する

.content
content;
  • test.ts (2,1): Cannot find name 'content'.

ファイルを添付したメッセージを送信する

ファイルを添付したメッセージを送信する

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.send({ files: [ファイル] })
send({ files: [ファイル] });
  • test.ts (2,1): Cannot find name 'send'.
  • test.ts (2,16): Cannot find name 'ファイル'.

.send(new Discord.MessageAttachment(ファイル))
import * as Discord from "discord.js";
send(new Discord.MessageAttachment(ファイル));
  • test.ts (3,1): Cannot find name 'send'.
  • test.ts (3,36): Cannot find name 'ファイル'.

ファイル
ファイル;
  • test.ts (2,1): Cannot find name 'ファイル'.

.send({ files: ['https://picsum.photos/200'] })
send({ files: ["https://picsum.photos/200"] });
  • test.ts (2,1): Cannot find name 'send'.

.send({ files: ['./image.png'] })
send({ files: ["./image.png"] });
  • test.ts (2,1): Cannot find name 'send'.

ボットがサーバーから退出したときに処理を実行する

ボットがサーバーから退出したときに処理を実行する

'guildDelete'
"guildDelete";

client.on('guildDelete', guild => { console.log(guild.name) })
declare var client: import("discord.js").Client;
client.on("guildDelete", guild => { console.log(guild.name); });

ボットがサーバーに参加したときに処理を実行する

ボットがサーバーに参加したときに処理を実行する

'guildCreate'
"guildCreate";

client.on('guildCreate', guild => { console.log(guild.name) })
declare var client: import("discord.js").Client;
client.on("guildCreate", guild => { console.log(guild.name); });

サーバーからメンバーが退出したら処理を実行する

サーバーからメンバーが退出したら処理を実行する

'guildMemberRemove'
"guildMemberRemove";

client.on('guildMemberRemove', member => { console.log(member.displayName) })
declare var client: import("discord.js").Client;
client.on("guildMemberRemove", member => { console.log(member.displayName); });

サーバーにユーザーが参加したら処理を実行する

サーバーにユーザーが参加したら処理を実行する

'guildMemberAdd'
"guildMemberAdd";

client.on('guildMemberAdd', member => { console.log(member.displayName) })
declare var client: import("discord.js").Client;
client.on("guildMemberAdd", member => { console.log(member.displayName); });

Discord.jsのドキュメントに出てくるimplements TextBasedChannelとは

Discord.jsのドキュメントに出てくるimplements TextBasedChannelとは

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.startTyping()
startTyping();
  • test.ts (2,1): Cannot find name 'startTyping'.

Collectionの主な使い方

Collectionの主な使い方

.size
size;
  • test.ts (2,1): Cannot find name 'size'.

.length
length;

.get()
get();
  • test.ts (2,1): Cannot find name 'get'.

client.guilds.cache.get('391390986770710528')
declare var client: import("discord.js").Client;
client.guilds.cache.get("391390986770710528");

.forEach()
forEach();
  • test.ts (2,1): Cannot find name 'forEach'.

client.guilds.cache.forEach(guild => console.log(guild.name))
declare var client: import("discord.js").Client;
client.guilds.cache.forEach(guild => console.log(guild.name));

.filter()
filter();
  • test.ts (2,1): Cannot find name 'filter'. Did you mean 'File'?

true
true;

client.users.cache.filter(user => !user.bot)
declare var client: import("discord.js").Client;
client.users.cache.filter(user => !user.bot);

.find()
find();
  • test.ts (2,1): Cannot find name 'find'.

true
true;

client.guilds.cache.find(guild => guild.name === 'サーバー名')
declare var client: import("discord.js").Client;
client.guilds.cache.find(guild => guild.name === "\u30B5\u30FC\u30D0\u30FC\u540D");

.map()
map();
  • test.ts (2,1): Cannot find name 'map'. Did you mean 'Map'?

client.guilds.cache.map(guild => guild.name)
declare var client: import("discord.js").Client;
client.guilds.cache.map(guild => guild.name);

メッセージからユーザーを取得する

メッセージからユーザーを取得する

.author
author;
  • test.ts (2,1): Cannot find name 'author'.

Userクラス

Userクラス

client.users.cache.get(id)
declare var client: import("discord.js").Client;
client.users.cache.get(id);
  • test.ts (3,24): Cannot find name 'id'.

message.author
declare var message: import("discord.js").Message;
message.author;

.username
username;
  • test.ts (2,1): Cannot find name 'username'.

.tag
tag;
  • test.ts (2,1): Cannot find name 'tag'.

.bot
bot;
  • test.ts (2,1): Cannot find name 'bot'.

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.avatarURL()
avatarURL();
  • test.ts (2,1): Cannot find name 'avatarURL'.

Collectionのメソッド解説

Collectionのメソッド解説

.array()
array();
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

collection.array()
collection.array();
  • test.ts (2,1): Cannot find name 'collection'.

.clone()
clone();
  • test.ts (2,1): Cannot find name 'clone'. Did you mean 'close'?

collection.clone()
collection.clone();
  • test.ts (2,1): Cannot find name 'collection'.

.concat(...collections)
concat(...collections);
  • test.ts (2,1): Cannot find name 'concat'.
  • test.ts (2,11): Cannot find name 'collections'.

collection.concat(otherCollection)
collection.concat(otherCollection);
  • test.ts (2,1): Cannot find name 'collection'.
  • test.ts (2,19): Cannot find name 'otherCollection'.

.deleteAll()
deleteAll();
  • test.ts (2,1): Cannot find name 'deleteAll'.

delete()
delete ();
  • test.ts (2,9): The operand of a 'delete' operator must be a property reference.
  • test.ts (2,9): Expression expected.

collection.deleteAll()
collection.deleteAll();
  • test.ts (2,1): Cannot find name 'collection'.

.equals(collection)
equals(collection);
  • test.ts (2,1): Cannot find name 'equals'.
  • test.ts (2,8): Cannot find name 'collection'.

collection.equals(otherCollection)
collection.equals(otherCollection);
  • test.ts (2,1): Cannot find name 'collection'.
  • test.ts (2,19): Cannot find name 'otherCollection'.

{} == {} // false
{ }
    == {}; // false
  • test.ts (3,2): Expression expected.

.every(fn, [thisArg])
every(fn, [thisArg]);
  • test.ts (2,1): Cannot find name 'every'.
  • test.ts (2,7): Cannot find name 'fn'.
  • test.ts (2,12): Cannot find name 'thisArg'.

fn
fn;
  • test.ts (2,1): Cannot find name 'fn'.

collection.every(item => item.name === 'hoge')
collection.every(item => item.name === "hoge");
  • test.ts (2,1): Cannot find name 'collection'.
  • test.ts (2,18): Parameter 'item' implicitly has an 'any' type.

.exists(prop, value)
exists(prop, value);
  • test.ts (2,1): Cannot find name 'exists'.
  • test.ts (2,8): Cannot find name 'prop'.
  • test.ts (2,14): Cannot find name 'value'.

collection.exists('name', 'hoge')
collection.exists("name", "hoge");
  • test.ts (2,1): Cannot find name 'collection'.

collection.has(id)
collection.has(id);
  • test.ts (2,1): Cannot find name 'collection'.
  • test.ts (2,16): Cannot find name 'id'.

.find()
find();
  • test.ts (2,1): Cannot find name 'find'.

.filter(fn, [thisArg])
filter(fn, [thisArg]);
  • test.ts (2,1): Cannot find name 'filter'. Did you mean 'File'?
  • test.ts (2,8): Cannot find name 'fn'.
  • test.ts (2,13): Cannot find name 'thisArg'.

collection.filter(item => item.name === 'hoge')
collection.filter(item => item.name === "hoge");
  • test.ts (2,1): Cannot find name 'collection'.
  • test.ts (2,19): Parameter 'item' implicitly has an 'any' type.

.filterArray(fn, [thisArg])
filterArray(fn, [thisArg]);
  • test.ts (2,1): Cannot find name 'filterArray'.
  • test.ts (2,13): Cannot find name 'fn'.
  • test.ts (2,18): Cannot find name 'thisArg'.

.filter()
filter();
  • test.ts (2,1): Cannot find name 'filter'. Did you mean 'File'?

collection.filterArray(item => item.name === 'hoge')
collection.filterArray(item => item.name === "hoge");
  • test.ts (2,1): Cannot find name 'collection'.
  • test.ts (2,24): Parameter 'item' implicitly has an 'any' type.

.find(propOrFn, [value])
find(propOrFn, [value]);
  • test.ts (2,1): Cannot find name 'find'.
  • test.ts (2,6): Cannot find name 'propOrFn'.
  • test.ts (2,17): Cannot find name 'value'.

.findAll(prop, value)
findAll(prop, value);
  • test.ts (2,1): Cannot find name 'findAll'.
  • test.ts (2,9): Cannot find name 'prop'.
  • test.ts (2,15): Cannot find name 'value'.

.findKey(propOrFn, [value])
findKey(propOrFn, [value]);
  • test.ts (2,1): Cannot find name 'findKey'.
  • test.ts (2,9): Cannot find name 'propOrFn'.
  • test.ts (2,20): Cannot find name 'value'.

.first([count])
first([count]);
  • test.ts (2,1): Cannot find name 'first'.
  • test.ts (2,8): Cannot find name 'count'.

collection.first()
collection.first();
  • test.ts (2,1): Cannot find name 'collection'.

collection.first(3)
collection.first(3);
  • test.ts (2,1): Cannot find name 'collection'.

.firstKey([count])
firstKey([count]);
  • test.ts (2,1): Cannot find name 'firstKey'.
  • test.ts (2,11): Cannot find name 'count'.

collection.first()
collection.first();
  • test.ts (2,1): Cannot find name 'collection'.

collection.first(3)
collection.first(3);
  • test.ts (2,1): Cannot find name 'collection'.

.keyArray()
keyArray();
  • test.ts (2,1): Cannot find name 'keyArray'.

.last(count)
last(count);
  • test.ts (2,1): Cannot find name 'last'.
  • test.ts (2,6): Cannot find name 'count'.

collection.last()
collection.last();
  • test.ts (2,1): Cannot find name 'collection'.

collection.last(3)
collection.last(3);
  • test.ts (2,1): Cannot find name 'collection'.

.lastKey(count)
lastKey(count);
  • test.ts (2,1): Cannot find name 'lastKey'.
  • test.ts (2,9): Cannot find name 'count'.

collection.last()
collection.last();
  • test.ts (2,1): Cannot find name 'collection'.

collection.last(3)
collection.last(3);
  • test.ts (2,1): Cannot find name 'collection'.

.map(fn, [thisArg])
map(fn, [thisArg]);
  • test.ts (2,1): Cannot find name 'map'. Did you mean 'Map'?
  • test.ts (2,5): Cannot find name 'fn'.
  • test.ts (2,10): Cannot find name 'thisArg'.

.partition(fnthisArg)
partition(fnthisArg);
  • test.ts (2,1): Cannot find name 'partition'.
  • test.ts (2,11): Cannot find name 'fnthisArg'.

.random(count)
random(count);
  • test.ts (2,1): Cannot find name 'random'.
  • test.ts (2,8): Cannot find name 'count'.

.randomKey(count)
randomKey(count);
  • test.ts (2,1): Cannot find name 'randomKey'.
  • test.ts (2,11): Cannot find name 'count'.

.reduce(fninitialValue)
reduce(fninitialValue);
  • test.ts (2,1): Cannot find name 'reduce'.
  • test.ts (2,8): Cannot find name 'fninitialValue'.

.some(fnthisArg)
some(fnthisArg);
  • test.ts (2,1): Cannot find name 'some'.
  • test.ts (2,6): Cannot find name 'fnthisArg'.

.sort(compareFunction)
sort(compareFunction);
  • test.ts (2,1): Cannot find name 'sort'.
  • test.ts (2,6): Cannot find name 'compareFunction'.

compareFunction
compareFunction;
  • test.ts (2,1): Cannot find name 'compareFunction'.

.sweep(fnthisArg)
sweep(fnthisArg);
  • test.ts (2,1): Cannot find name 'sweep'.
  • test.ts (2,7): Cannot find name 'fnthisArg'.

.tap(fnthisArg)
tap(fnthisArg);
  • test.ts (2,1): Cannot find name 'tap'.
  • test.ts (2,5): Cannot find name 'fnthisArg'.

メンバーに指定した役職が付与されているか確認する

メンバーに指定した役職が付与されているか確認する

member.roles.cache.has('役職ID')
declare var member: import("discord.js").GuildMember;
member.roles.cache.has("\u5F79\u8077ID");
  • test.ts (3,24): Argument of type '"役職ID"' is not assignable to parameter of type '${bigint}'.

.roles
roles;
  • test.ts (2,1): Cannot find name 'roles'.

READ_MESSAGES権限は廃止された

READ_MESSAGES権限は廃止された

READ_MESSAGES
READ_MESSAGES;
  • test.ts (2,1): Cannot find name 'READ_MESSAGES'.

VIEW_CHANNEL
VIEW_CHANNEL;
  • test.ts (2,1): Cannot find name 'VIEW_CHANNEL'.

チャンネルを作成する

チャンネルを作成する

.channels.create()
channels.create();
  • test.ts (2,1): Cannot find name 'channels'.

guild.channels.create('チャンネル名')
declare var guild: import("discord.js").Guild;
guild.channels.create("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D");

guild.channels.create('チャンネル名', { type: 'voice' })
declare var guild: import("discord.js").Guild;
guild.channels.create("\u30C1\u30E3\u30F3\u30CD\u30EB\u540D", { type: "voice" });
  • test.ts (3,65): No overload matches this call. The last overload gave the following error. Type '"voice"' is not assignable to type '"GUILD_CATEGORY" | ChannelTypes.GUILD_TEXT | ChannelTypes.GUILD_VOICE | ChannelTypes.GUILD_CATEGORY | ChannelTypes.GUILD_NEWS | ChannelTypes.GUILD_STORE | ChannelTypes.GUILD_NEWS_THREAD | ... 7 more ... | undefined'.

個別にメンションされているか確認する

個別にメンションされているか確認する

message.mentions.users.has(id)
declare var message: import("discord.js").Message;
message.mentions.users.has(id);
  • test.ts (3,28): Cannot find name 'id'.

.users
users;
  • test.ts (2,1): Cannot find name 'users'.

.members
members;
  • test.ts (2,1): Cannot find name 'members'.

.roles
roles;
  • test.ts (2,1): Cannot find name 'roles'.

.channels
channels;
  • test.ts (2,1): Cannot find name 'channels'.

.has(id)
has(id);
  • test.ts (2,1): Cannot find name 'has'.
  • test.ts (2,5): Cannot find name 'id'.

message.isMentioned(data)
declare var message: import("discord.js").Message;
message.isMentioned(data);
  • test.ts (3,9): Property 'isMentioned' does not exist on type 'Message'.
  • test.ts (3,21): Cannot find name 'data'.

役職を作成する

役職を作成する

.roles
roles;
  • test.ts (2,1): Cannot find name 'roles'.

.create()
create();
  • test.ts (2,1): Cannot find name 'create'.

guild.roles.create({ data: { name: '役職名' } })
declare var guild: import("discord.js").Guild;
guild.roles.create({ data: { name: "\u5F79\u8077\u540D" } });
  • test.ts (3,22): Argument of type '{ data: { name: string; }; }' is not assignable to parameter of type 'CreateRoleOptions'. Object literal may only specify known properties, and 'data' does not exist in type 'CreateRoleOptions'.

メンションできる役職を作成する

メンションできる役職を作成する

mentionable: true
mentionable: true;

guild.roles.create({ data: { name: '役職名', mentionable: true } })
declare var guild: import("discord.js").Guild;
guild.roles.create({ data: { name: "\u5F79\u8077\u540D", mentionable: true } });
  • test.ts (3,22): Argument of type '{ data: { name: string; mentionable: boolean; }; }' is not assignable to parameter of type 'CreateRoleOptions'. Object literal may only specify known properties, and 'data' does not exist in type 'CreateRoleOptions'.

guild.createRole({ name: '役職名', mentionable: true })
declare var guild: import("discord.js").Guild;
guild.createRole({ name: "\u5F79\u8077\u540D", mentionable: true });
  • test.ts (3,7): Property 'createRole' does not exist on type 'Guild'.

サーバー名を取得する

サーバー名を取得する

.name
name;

メンバーからサーバーにアクセスする

メンバーからサーバーにアクセスする

.guild
declare var guild: import("discord.js").Guild;
guild;

ボット全体からユーザーを取得する

ボット全体からユーザーを取得する

.users
users;
  • test.ts (2,1): Cannot find name 'users'.

ボット自身をユーザーとして取得する

ボット自身をユーザーとして取得する

.user
declare var user: import("discord.js").User;
user;

チャンネルトピックを変更する

チャンネルトピックを変更する

.setTopic()
setTopic();
  • test.ts (2,1): Cannot find name 'setTopic'.

channel.setTopic('トピック')
declare var channel: Omit<import("discord.js").TextChannel, "type"> & Omit<import("discord.js").VoiceChannel, "type">;
channel.setTopic("\u30C8\u30D4\u30C3\u30AF");

ニックネームを変更する

ニックネームを変更する

setNickname
setNickname;
  • test.ts (2,1): Cannot find name 'setNickname'.

ボット自身のニックネームを変更する

ボット自身のニックネームを変更する

guild.me.setNickname('ニックネーム')
declare var guild: import("discord.js").Guild;
guild.me.setNickname("\u30CB\u30C3\u30AF\u30CD\u30FC\u30E0");
  • test.ts (3,1): Object is possibly 'null'.

サーバーからボット自身を取得する

サーバーからボット自身を取得する

.me
me;
  • test.ts (2,1): Cannot find name 'me'.

ユーザーにDMを送信する

ユーザーにDMを送信する

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

.send()
send();
  • test.ts (2,1): Cannot find name 'send'.

メッセージからメンバーを取得する

メッセージからメンバーを取得する

.member
declare var member: import("discord.js").GuildMember;
member;

ユーザータグを取得する

ユーザータグを取得する

.tag
tag;
  • test.ts (2,1): Cannot find name 'tag'.

ユーザー名を取得する

ユーザー名を取得する

.username
username;
  • test.ts (2,1): Cannot find name 'username'.

ユーザータグ

ユーザータグ

#0001
#;
1;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

username#0001
username;
#;
1;
  • test.ts (2,1): Cannot find name 'username'.
  • test.ts (3,1): Cannot find name '#'.
  • test.ts (3,1): Private identifiers are not allowed outside class bodies.
  • test.ts (3,2): Invalid character.

#0001
#;
1;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

配列内のいずれかの文字列を含むかどうか確認する

配列内のいずれかの文字列を含むかどうか確認する

some
some;
  • test.ts (2,1): Cannot find name 'some'.

includes
includes;
  • test.ts (2,1): Cannot find name 'includes'.

apple
apple;
  • test.ts (2,1): Cannot find name 'apple'.

a
a;
  • test.ts (2,1): Cannot find name 'a'.

b
b;
  • test.ts (2,1): Cannot find name 'b'.

c
c;
  • test.ts (2,1): Cannot find name 'c'.

['a', 'b', 'c'].some(str => 'apple'.includes(str))
["a", "b", "c"].some(str => "apple".includes(str));

配列に含まれているか確認する

配列に含まれているか確認する

includes
includes;
  • test.ts (2,1): Cannot find name 'includes'.

some
some;
  • test.ts (2,1): Cannot find name 'some'.

includes
includes;
  • test.ts (2,1): Cannot find name 'includes'.

[1, 2].includes(2)
[1, 2].includes(2);

some
some;
  • test.ts (2,1): Cannot find name 'some'.

[1, 2].some(n => n > 1)
[1, 2].some(n => n > 1);

ミリ秒

ミリ秒

10000
10000;

60000
60000;

3600000
3600000;

60 * 1000
60 * 1000;

メッセージからリアクションを全て消したい

メッセージからリアクションを全て消したい

message.reactions.removeAll()
declare var message: import("discord.js").Message;
message.reactions.removeAll();

message.clearReactions()
declare var message: import("discord.js").Message;
message.clearReactions();
  • test.ts (3,9): Property 'clearReactions' does not exist on type 'Message'.

文字列を分割して配列にする

文字列を分割して配列にする

split
split;
  • test.ts (2,1): Cannot find name 'split'.

'1 2 3'.split(' ')
"1 2 3".split(" ");

['1', '2', '3']
["1", "2", "3"];

'1  2    3'.split(/\s+/)
"1  2    3".split(/\s+/);

['1', '2', '3']
["1", "2", "3"];

@everyoneや役職を考慮してメンションされているか確認する

@everyoneや役職を考慮してメンションされているか確認する

message.mentions.has(data)
declare var message: import("discord.js").Message;
message.mentions.has(data);
  • test.ts (3,22): Cannot find name 'data'.

message.mentions.has(data, { ignoreEveryone: true })
declare var message: import("discord.js").Message;
message.mentions.has(data, { ignoreEveryone: true });
  • test.ts (3,22): Cannot find name 'data'.

message.isMemberMentioned(member)
declare var message: import("discord.js").Message;
declare var member: import("discord.js").GuildMember;
message.isMemberMentioned(member);
  • test.ts (4,9): Property 'isMemberMentioned' does not exist on type 'Message'.

ボットが参加しているサーバー数を取得する

ボットが参加しているサーバー数を取得する

.size
size;
  • test.ts (2,1): Cannot find name 'size'.

client.guilds.cache.size
declare var client: import("discord.js").Client;
client.guilds.cache.size;

client.guilds.size
declare var client: import("discord.js").Client;
client.guilds.size;
  • test.ts (3,15): Property 'size' does not exist on type 'GuildManager'.

サーバーからメンバーをBAN・BAN解除する

サーバーからメンバーをBAN・BAN解除する

guild.members.ban(user)
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
guild.members.ban(user);

guild.members.unban(user)
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
guild.members.unban(user);

guild.ban(user)
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
guild.ban(user);
  • test.ts (4,7): Property 'ban' does not exist on type 'Guild'. Did you mean 'bans'?

guild.unban(user)
declare var guild: import("discord.js").Guild;
declare var user: import("discord.js").User;
guild.unban(user);
  • test.ts (4,7): Property 'unban' does not exist on type 'Guild'.

member.ban()
declare var member: import("discord.js").GuildMember;
member.ban();

ボットのアバターを変更したい

ボットのアバターを変更したい

client.user.setAvatar('./avatar.png')
declare var client: import("discord.js").Client;
declare var user: import("discord.js").User;
client.user.setAvatar("./avatar.png");
  • test.ts (4,1): Object is possibly 'null'.

Discord.jsで色を指定する方法まとめ

Discord.jsで色を指定する方法まとめ

16777215
16777215;

0xFFFFFF
16777215;

#FFFFFF
#FFFFFF;
  • test.ts (2,1): Cannot find name '#FFFFFF'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.

#
#;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

0x
0;
x;
  • test.ts (3,1): Cannot find name 'x'.

'#FFFFFF'
"#FFFFFF";

'#fff'
"#fff";

#
#;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

#FFFFFF
#FFFFFF;
  • test.ts (2,1): Cannot find name '#FFFFFF'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.

#
#;
  • test.ts (2,1): Cannot find name '#'.
  • test.ts (2,1): Private identifiers are not allowed outside class bodies.
  • test.ts (2,2): Invalid character.

FFFFFF
FFFFFF;
  • test.ts (2,1): Cannot find name 'FFFFFF'.

[255, 255, 255]
[255, 255, 255];

"RANDOM"
"RANDOM";

RANDOM
RANDOM;
  • test.ts (2,1): Cannot find name 'RANDOM'.

"WHITE"
"WHITE";

DEFAULT WHITE AQUA GREEN BLUE YELLOW PURPLE LUMINOUS_VIVID_PINK GOLD ORANGE RED GREY DARKER_GREY NAVY DARK_AQUA DARK_GREEN DARK_BLUE DARK_PURPLE DARK_VIVID_PINK DARK_GOLD DARK_ORANGE DARK_RED DARK_GREY LIGHT_GREY DARK_NAVY
DEFAULT;
WHITE;
AQUA;
GREEN;
BLUE;
YELLOW;
PURPLE;
LUMINOUS_VIVID_PINK;
GOLD;
ORANGE;
RED;
GREY;
DARKER_GREY;
NAVY;
DARK_AQUA;
DARK_GREEN;
DARK_BLUE;
DARK_PURPLE;
DARK_VIVID_PINK;
DARK_GOLD;
DARK_ORANGE;
DARK_RED;
DARK_GREY;
LIGHT_GREY;
DARK_NAVY;
  • test.ts (2,1): Cannot find name 'DEFAULT'.
  • test.ts (3,1): Cannot find name 'WHITE'.
  • test.ts (4,1): Cannot find name 'AQUA'.
  • test.ts (5,1): Cannot find name 'GREEN'.
  • test.ts (6,1): Cannot find name 'BLUE'.
  • test.ts (7,1): Cannot find name 'YELLOW'.
  • test.ts (8,1): Cannot find name 'PURPLE'.
  • test.ts (9,1): Cannot find name 'LUMINOUS_VIVID_PINK'.
  • test.ts (10,1): Cannot find name 'GOLD'.
  • test.ts (11,1): Cannot find name 'ORANGE'. Did you mean 'Range'?
  • test.ts (12,1): Cannot find name 'RED'.
  • test.ts (13,1): Cannot find name 'GREY'.
  • test.ts (14,1): Cannot find name 'DARKER_GREY'.
  • test.ts (15,1): Cannot find name 'NAVY'.
  • test.ts (16,1): Cannot find name 'DARK_AQUA'.
  • test.ts (17,1): Cannot find name 'DARK_GREEN'.
  • test.ts (18,1): Cannot find name 'DARK_BLUE'.
  • test.ts (19,1): Cannot find name 'DARK_PURPLE'.
  • test.ts (20,1): Cannot find name 'DARK_VIVID_PINK'.
  • test.ts (21,1): Cannot find name 'DARK_GOLD'.
  • test.ts (22,1): Cannot find name 'DARK_ORANGE'.
  • test.ts (23,1): Cannot find name 'DARK_RED'.
  • test.ts (24,1): Cannot find name 'DARK_GREY'.
  • test.ts (25,1): Cannot find name 'LIGHT_GREY'.
  • test.ts (26,1): Cannot find name 'DARK_NAVY'.

DEFAULT
DEFAULT;
  • test.ts (2,1): Cannot find name 'DEFAULT'.

dotenvを使って機密情報を安全に管理する

dotenvを使って機密情報を安全に管理する

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

npm i dotenv
npm;
i;
dotenv;
  • test.ts (2,1): Cannot find name 'npm'.
  • test.ts (3,1): Cannot find name 'i'.
  • test.ts (4,1): Cannot find name 'dotenv'.

yarn add dotenv
yarn;
add;
dotenv;
  • test.ts (2,1): Cannot find name 'yarn'.
  • test.ts (3,1): Cannot find name 'add'.
  • test.ts (4,1): Cannot find name 'dotenv'.

require('dotenv').config()
require("dotenv").config();

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

ラベル=
ラベル = ;
  • test.ts (2,1): Cannot find name 'ラベル'.
  • test.ts (2,7): Cannot find name '値'.

.gitignore
gitignore;
  • test.ts (2,1): Cannot find name 'gitignore'.

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

client.login(process.env.TOKEN)
declare var client: import("discord.js").Client;
client.login(process.env.TOKEN);

TOKEN
TOKEN;
  • test.ts (2,1): Cannot find name 'TOKEN'.

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

.env.example
env.example;
  • test.ts (2,1): Cannot find name 'env'.

.env
env;
  • test.ts (2,1): Cannot find name 'env'.

ユーザーの端末ごとのステータスを取得する

ユーザーの端末ごとのステータスを取得する

user.presence.clientStatus
declare var user: import("discord.js").User;
user.presence.clientStatus;
  • test.ts (3,6): Property 'presence' does not exist on type 'User'.

clientStatus
clientStatus;
  • test.ts (2,1): Cannot find name 'clientStatus'.

undefined
undefined;

clientStatus
clientStatus;
  • test.ts (2,1): Cannot find name 'clientStatus'.

web
web;
  • test.ts (2,1): Cannot find name 'web'.

desktop
desktop;
  • test.ts (2,1): Cannot find name 'desktop'.

mobile
mobile;
  • test.ts (2,1): Cannot find name 'mobile'.

online
online;
  • test.ts (2,1): Cannot find name 'online'. Did you mean 'ononline'?

idle
idle;
  • test.ts (2,1): Cannot find name 'idle'.

dnd
dnd;
  • test.ts (2,1): Cannot find name 'dnd'.

undefined
undefined;

ユーザーのステータスを取得する

ユーザーのステータスを取得する

member.presence.status
declare var member: import("discord.js").GuildMember;
member.presence.status;
  • test.ts (3,1): Object is possibly 'null'.

user.presence.status
declare var user: import("discord.js").User;
user.presence.status;
  • test.ts (3,6): Property 'presence' does not exist on type 'User'.

online
online;
  • test.ts (2,1): Cannot find name 'online'. Did you mean 'ononline'?

idle
idle;
  • test.ts (2,1): Cannot find name 'idle'.

offline
offline;
  • test.ts (2,1): Cannot find name 'offline'. Did you mean 'onoffline'?

dnd
dnd;
  • test.ts (2,1): Cannot find name 'dnd'.

presence
presence;
  • test.ts (2,1): Cannot find name 'presence'.

status
status;

clientStatus
clientStatus;
  • test.ts (2,1): Cannot find name 'clientStatus'.

配列とSetの違い

配列とSetの違い

const array = [1, 2, 3]
const array = [1, 2, 3];

const set = new Set([1, 2, 3])
const set = new Set([1, 2, 3]);

new Set()
new Set();

[1, 2, 1] // > (3) [1, 2, 1]
[1, 2, 1]; // > (3) [1, 2, 1]

new Set([1, 2, 1]) // > Set(2) {1, 2}
new Set([1, 2, 1]); // > Set(2) {1, 2}

array.shift()
array.shift();
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

array.unshift('value')
array.unshift("value");
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

array.push('value')
array.push("value");
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

array.pop()
array.pop();
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

set.add('value')
set.add("value");
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

set.delete('value')
set.delete("value");
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

array[2] = 1
array[2] = 1;
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

set.delete('3')
set.delete("3");
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

array[2] // > 3
array[2]; // > 3
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?

set.has(3) // > true
set.has(3); // > true
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

array.map(n => n + 1)
array.map(n => n + 1);
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?
  • test.ts (2,11): Parameter 'n' implicitly has an 'any' type.

array.filter(n => n > 1)
array.filter(n => n > 1);
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?
  • test.ts (2,14): Parameter 'n' implicitly has an 'any' type.

array.reduce((p, c) => p + c)
array.reduce((p, c) => p + c);
  • test.ts (2,1): Cannot find name 'array'. Did you mean 'Array'?
  • test.ts (2,15): Parameter 'p' implicitly has an 'any' type.
  • test.ts (2,18): Parameter 'c' implicitly has an 'any' type.

set.add('value')
set.add("value");
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

set.delete('value')
set.delete("value");
  • test.ts (2,1): Cannot find name 'set'. Did you mean 'Set'?

Setの使い方

Setの使い方

const ids = new Set()
const ids = new Set();

ids.add('1')
ids.add("1");
  • test.ts (2,1): Cannot find name 'ids'.

ids.has('1') // > true
ids.has("1"); // > true
  • test.ts (2,1): Cannot find name 'ids'.

ids.delete('1')
ids.delete("1");
  • test.ts (2,1): Cannot find name 'ids'.

ids.clear()
ids.clear();
  • test.ts (2,1): Cannot find name 'ids'.

分割代入の使い方

分割代入の使い方

const obj = { hoge: 1 }
const obj = { hoge: 1 };

console.log(obj.hoge) // > 1
console.log(obj.hoge); // > 1
  • test.ts (2,13): Cannot find name 'obj'.

const hoge = obj.hoge
const hoge = obj.hoge;
  • test.ts (2,14): Cannot find name 'obj'.

console.log(hoge) // > 1
console.log(hoge); // > 1
  • test.ts (2,13): Cannot find name 'hoge'.

const { hoge } = obj
const { hoge } = obj;
  • test.ts (2,18): Cannot find name 'obj'.

console.log(hoge) // > 1
console.log(hoge); // > 1
  • test.ts (2,13): Cannot find name 'hoge'.

const obj = { hoge: 1, fuga: 2 }
const obj = { hoge: 1, fuga: 2 };

const { hoge, fuga } = obj
const { hoge, fuga } = obj;
  • test.ts (2,24): Cannot find name 'obj'.

console.log(hoge, fuga) // > 1 2
console.log(hoge, fuga); // > 1 2
  • test.ts (2,13): Cannot find name 'hoge'.
  • test.ts (2,19): Cannot find name 'fuga'.

const { hoge: Hoge } = obj
const { hoge: Hoge } = obj;
  • test.ts (2,24): Cannot find name 'obj'.

console.log(Hoge) // > 1
console.log(Hoge); // > 1
  • test.ts (2,13): Cannot find name 'Hoge'.

Client.loginの引数にトークンを書きたくない

Client.loginの引数にトークンを書きたくない

DISCORD_TOKEN
DISCORD_TOKEN;
  • test.ts (2,1): Cannot find name 'DISCORD_TOKEN'.

Client.login()
import { Client } from "discord.js";
Client.login();
  • test.ts (3,8): Property 'login' does not exist on type 'typeof Client'.

DISCORD_TOKEN
DISCORD_TOKEN;
  • test.ts (2,1): Cannot find name 'DISCORD_TOKEN'.

メソッド

メソッド

obj
obj;
  • test.ts (2,1): Cannot find name 'obj'.

prop
prop;
  • test.ts (2,1): Cannot find name 'prop'.

obj.prop
obj.prop;
  • test.ts (2,1): Cannot find name 'obj'.

obj.prop()
obj.prop();
  • test.ts (2,1): Cannot find name 'obj'.

Map

Map

map
map;
  • test.ts (2,1): Cannot find name 'map'. Did you mean 'Map'?

オブジェクト

オブジェクト

{ prop: 'value' }
{
    prop: "value";
}

プリミティブ値

プリミティブ値

undefined
undefined;

null
null;

ラッパーオブジェクト

ラッパーオブジェクト

true
true;

false
false;

Boolean
Boolean;

1
1;

-100
-100;

Number
Number;

JavaScriptのデータ型

JavaScriptのデータ型

true
true;

false
false;

1
1;

-100
-100;

0.1
0.1;

Infinity
Infinity;

NaN
NaN;

Infinity
Infinity;

1 / 0
1 / 0;

NaN
NaN;

0 / 0
0 / 0;

1n
1n;

-100n
-100n;

'hello'
"hello";

Symbol('説明')
Symbol("\u8AAC\u660E");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment