discord bot in typescript

To create a discord bot in TypeScript, first you need to set up a new project with Node.js and npm installed. After that, you can create a new package.json file with the following command:

index.ts
npm init -y
12 chars
2 lines

Next, you need to install discord.js module which is required to interact with Discord API. You can install it using the following command:

index.ts
npm install discord.js
23 chars
2 lines

Once discord.js has been installed, you can begin coding your bot using TypeScript. To enable TypeScript in your project, add a tsconfig.json file, initialize it with the following command:

index.ts
tsc --init
11 chars
2 lines

This will create a default tsconfig.json file in your project root.

Next, you should install TypeScript as a development dependency, because you need to compile your TypeScript code to JavaScript. You can install TypeScript using the following command:

index.ts
npm install --save-dev typescript
34 chars
2 lines

Now that you have set up TypeScript, you can start coding your bot. Create a new file in your project named myBot.ts and start with the following code:

index.ts
import Discord from 'discord.js';

const bot = new Discord.Client();

bot.on('ready', () => {
  console.log(`Logged in as ${bot.user?.tag}!`);
});

bot.on('message', (msg) => {
  if (msg.content === 'ping') {
    msg.reply('Pong!');
  }
});

bot.login('YOUR_DISCORD_BOT_TOKEN');
279 chars
16 lines

Here we have imported Discord.js and created a new instance of a bot. We have also added two event listeners: one for when the bot is ready and another for when a message is received.

To compile your TypeScript code, you can run the following command:

index.ts
tsc
4 chars
2 lines

Once compiled, you can start your bot by running the following command:

index.ts
node myBot.js
14 chars
2 lines

Make sure to replace YOUR_DISCORD_BOT_TOKEN with your actual Discord bot token, which you can get from the Discord Developer Portal.

That's it! You have successfully created a Discord bot in TypeScript.

gistlibby LogSnag