Logo

dev-resources.site

for different kinds of informations.

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

Published at
11/27/2024
Categories
webdev
discord
telegram
selfbot
Author
plzbugmenot
Categories
4 categories in total
webdev
open
discord
open
telegram
open
selfbot
open
Author
11 person written this
plzbugmenot
open
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

discord Article's
30 articles in total
Favicon
TypeScript Discord Bot Handler
Favicon
Desvendando Subprocessos: Criando um Bot de Música com Go
Favicon
Does anyone know someone who makes Discord bots for free, or where to find such a person?
Favicon
Alarme Dynamo Throttle Events - Discord
Favicon
Boost Communication on Slack, Discord, GitHub, and Beyond! /BUTIFULL EMOJIS
Favicon
Using Discord as an unlimited cloud storage service
Favicon
Deploy your Discord Bot using Amazon EC2
Favicon
Discord Developer Cheat Sheet
Favicon
How to Set Up a Mock Server
Favicon
10 Cool Ideas for Discord Bots You Can Build Today
Favicon
Intro: Jonah 🐷
Favicon
Monetize your Discord community with these tips
Favicon
Creating a Moderation Bot for Discord
Favicon
Automating Event Management: A Discord to Google Calendar Bot
Favicon
Bulk Delete Messages with MEE6 Discord Bot
Favicon
Monitoring Discord server, detect CA, sending it to telegram bot
Favicon
Building a Discord Bot with OpenAI GPT
Favicon
Building a Cost-Effective Valheim Server on Azure with Serverless Discord Bot Integration
Favicon
Mass Delete Discord Messages Easily
Favicon
Hacktoberfest Extended Until November 30 for Robo.js
Favicon
Hacktoberfest 2024: Code Templates and Win Rewards 🎉
Favicon
Get News Updates automatically posted to your Discord using Supercog
Favicon
Hacktoberfest 2024: Create Discord Features or Videos to Win Rewards 🎉
Favicon
Running a Discord Bot on Raspberry Pi
Favicon
Missing Launch Button in your Discord Activity? Fix the Entry Point Command!
Favicon
🌟 Join the Open Source Community on Discord! 🚀
Favicon
DISCORD PROMOTION, DISOCRD SERVER PROMOTION
Favicon
I will discord promotion, nft discord server promotion, nft discord server marketing
Favicon
Patch Your Discord Activity’s Network Requests for Smooth CSP Compliance
Favicon
New PHP Package: Discord Table Builder

Featured ones: