DEV Community

Cover image for Monitoring Discord server, detect CA, sending it to telegram bot
Jason Smith
Jason Smith

Posted on

Monitoring Discord server, detect CA, sending it to telegram bot

What’s a Discord Self-Bot?

A Discord self-bot is basically a bot that runs using your personal Discord account instead of a separate bot account.

Why Use a Self-Bot?

With a self-bot, you can keep an eye on all the servers and channels your account is part of. Just remember, while self-bots can do some cool automation stuff, they come with big risks and are against Discord's rules.

Let’s Build a Simple Discord Self-Bot!

Requirements:

  • Monitor Specific Servers and Channels: We’ll track the servers and channels that your account has joined.
  • Catch Messages: The bot will listen for messages in these channels and look for Solana token contract addresses.
  • Send to Telegram: When it finds a token address, it will send that info to a Telegram trading bot so you can buy the token ASAP. ## Analysis:
  • Monitoring: We’ll use the Discord self-bot for monitoring.
  • Messaging: To send messages to the Telegram bot, we’ll use the Telegram API.
  • Implementation: We’ll write this using JavaScript or TypeScript with Node.js.

Development

Installation

Node.js 18+

npm install discord.js-selfbot-v13@latest telegram
Enter fullscreen mode Exit fullscreen mode

Make self-bot

import { Client } from "discord.js-selfbot-v13";

// Initialize Discord client
const discordClient = new Client();

// Discord event handlers
discordClient.on("ready", () => {
  console.log(`Logged in as ${discordClient.user?.tag}`);
});

...

await discordClient.login(DISCORD_USER_TOKEN);
Enter fullscreen mode Exit fullscreen mode

How to get DISCORD_USER_TOKEN?

Run code (Discord Console - [Ctrl + Shift + I])

allow pasting
Enter fullscreen mode Exit fullscreen mode
window.webpackChunkdiscord_app.push([
  [Math.random()],
  {},
  req => {
    if (!req.c) return;
    for (const m of Object.keys(req.c)
      .map(x => req.c[x].exports)
      .filter(x => x)) {
      if (m.default && m.default.getToken !== undefined) {
        return copy(m.default.getToken());
      }
      if (m.getToken !== undefined) {
        return copy(m.getToken());
      }
    }
  },
]);
console.log('%cWorked!', 'font-size: 50px');
console.log(`%cYou now have your token in the clipboard!`, 'font-size: 16px');
Enter fullscreen mode Exit fullscreen mode

Sending message to telegram bot using Telegram API

import { TelegramClient } from "telegram";

const TELEGRAM_API_ID = parseInt(process.env.TELEGRAM_API_ID || "0");
const TELEGRAM_API_HASH = process.env.TELEGRAM_API_HASH || "";

// Initialize Telegram client
const telegramClient = new TelegramClient(
  new StringSession(""),
  TELEGRAM_API_ID,
  TELEGRAM_API_HASH,
  { connectionRetries: 5 }
);

...
  console.log("Starting Telegram client...");
    await telegramClient.start({
      phoneNumber: async () =>
        await promptUser("Please enter your phone number: "),
      password: async () => await promptUser("Please enter your password: "),
      phoneCode: async () =>
        await promptUser("Please enter the code you received: "),
      onError: (err: any) => console.log(err),
    });
    // logger.info("📲 Telegram client started successfully");

Enter fullscreen mode Exit fullscreen mode

How to get Telegram API key?

  • Go to https://my.telegram.org/auth
  • Log in with your phone number
  • Go to "API development tools"
  • Create a new application
  • You'll receive:
    • api_id (numbers)
    • api_hash (string)

Codebase

import { Client } from "discord.js-selfbot-v13";
import { TelegramClient } from "telegram";
import { StringSession } from "telegram/sessions";
import * as readline from "readline";
import dotenv from "dotenv";
import fs from "fs";
import {
  detectSolanaTokenAddress,
  saveAddress,
  loadTrackedAddresses,
} from "./utils/utils";
// import logger from "./utils/logger";

// Create readline interface
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// Prompt function
function promptUser(question: string): Promise<string> {
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      resolve(answer);
    });
  });
}

// Load environment variables
dotenv.config();

// Load config
function loadConfig() {
  return JSON.parse(fs.readFileSync("config.json", "utf8"));
}

const config = loadConfig();

// Access environment variables
const DISCORD_USER_TOKEN = process.env.DISCORD_USER_TOKEN;
const TELEGRAM_API_ID = parseInt(process.env.TELEGRAM_API_ID || "0");
const TELEGRAM_API_HASH = process.env.TELEGRAM_API_HASH || "";

// Get settings from config
const BOT_USERNAME = config.telegram.bot_username;
const MONITORED_SERVERS = config.discord.server_channels;

// Initialize Discord client
const discordClient = new Client();

// Initialize Telegram client
const telegramClient = new TelegramClient(
  new StringSession(""),
  TELEGRAM_API_ID,
  TELEGRAM_API_HASH,
  { connectionRetries: 5 }
);

// Discord event handlers
discordClient.on("ready", () => {
  // logger.info(`Logged in as ${discordClient.user?.tag}`);
  console.log(`Logged in as ${discordClient.user?.tag}`);
});

discordClient.on("messageCreate", async (message: any) => {
  try {
    const serverId = message.guild?.id.toString();
    const channelId = message.channel.id.toString();

    for (const serverConfig of MONITORED_SERVERS) {
      if (
        serverId in serverConfig &&
        serverConfig[serverId].includes(channelId)
      ) {
        // logger.info(`Detected message in ${serverConfig[serverId]}`);

        const solanaAddresses = await detectSolanaTokenAddress(message.content);
        // logger.info(`Detected Solana addresses: ${solanaAddresses}`);

        if (solanaAddresses.length > 0) {
          const addressMap = loadTrackedAddresses();
          // Process addresses sequentially
          for (const address of solanaAddresses) {
            // Check if address exists in Map before sending
            if (!addressMap.has(address)) {
              try {
                await telegramClient.sendMessage(BOT_USERNAME, {
                  message: address,
                });
                // logger.info(`Sent message for address: ${address}`);
                saveAddress(address);
                // Add delay between messages
                await new Promise((resolve) => setTimeout(resolve, 1000));
              } catch (error) {
                // logger.error(
                //   `Failed to send message for address ${address}: ${error}`
                // );
                continue;
              }
            } else {
              // logger.info(`Skipping existing address: ${address}`);
            }
          }
        }
      }
    }
  } catch (error) {
    // logger.error(`Error processing message: ${error}`);
    // Don't exit process, just log the error and continue
  }
});

async function startTelegramClient() {
  try {
    console.log("Starting Telegram client...");
    await telegramClient.start({
      phoneNumber: async () =>
        await promptUser("Please enter your phone number: "),
      password: async () => await promptUser("Please enter your password: "),
      phoneCode: async () =>
        await promptUser("Please enter the code you received: "),
      onError: (err: any) => console.log(err),
    });
    // logger.info("📲 Telegram client started successfully");
  } catch (err: any) {
    console.error("Error starting Telegram client:", err);
    process.exit(1);
  }
}

async function startDiscordClient() {
  try {
    console.log("Starting Discord client... ");
    await discordClient.login(DISCORD_USER_TOKEN);
    // logger.info("🤖 Discord client started successfully");
  } catch (err: any) {
    console.error("Error starting Discord client:", err);
    process.exit(1);
  }
}

// Improve error handling in main function
async function main() {
  console.log("-------------------------> Starting bot...", Date.now());
  try {
    await startTelegramClient();
    await startDiscordClient(); // Make this await

    // Add process error handlers
    process.on("uncaughtException", (error) => {
      // logger.error("Uncaught Exception:", error);
    });

    process.on("unhandledRejection", (error) => {
      // logger.error("Unhandled Rejection:", error);
    });
  } catch (error) {
    // logger.error("Error in main:", error);
    process.exit(1);
  }
}

main();
Enter fullscreen mode Exit fullscreen mode

Additional link: https://github.com/Any-bot/D2T_CA_bot_Node

Discord #self-bot #telegram-api

Top comments (4)

Collapse
 
thomasbnt profile image
Thomas Bnt

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
pleasebugmenot profile image
Jason Smith

Sorry, I fixed it

Collapse
 
thomasbnt profile image
Thomas Bnt

Awesome 😎

Collapse
 
james_takahashi_77908481e profile image
James Takahashi

Thanks your post.