tdlib / telegram-bot-api

Telegram Bot API server
https://core.telegram.org/bots
Boost Software License 1.0
3.17k stars 599 forks source link

How to mention users by their username (telegram-bot) #638

Closed Behruz999 closed 1 month ago

Behruz999 commented 1 month ago

Hi everyone, I got a lack of insight about mentioning users by it's @username, my code's:

require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const env = process.env;
const isProduction = env?.NODE_ENV === "production";
const token = env?.BOT_TOKEN;
const TelegramBot = require("node-telegram-bot-api");
const bot = new TelegramBot(token, { polling: true });

app.use(express.json());
app.use(cors());

bot.on("message", (ctx) => {
  const chatId = ctx.chat.id;
  const text = ctx.text;
  const user = ctx.from;
  if (text === "/start") {
    bot.sendMessage(chatId, "hello");
  }
  bot.getChatAdministrators(chatId).then((admins) => {
    const isAdmin = admins.some((u) => u.user.id == user.id);
    if (!isAdmin) {
      if (ctx?.entities) {
        for (const entity of ctx?.entities) {
          if (entity.type === "url") {
            const messageId = ctx.message_id;
            const username = ctx.from.username;
            const response = `<a href="tg://user?id=${user.id}">${user.first_name}</a> Please do not share links in this group!`;
            bot.sendChatAction(chatId, "typing");
            bot.deleteMessage(chatId, messageId);
            bot.sendMessage(chatId, response, {
              entities: [
                { type: "text_mention", offset: 0, length: response.length, user },
              ],
              parse_mode: "HTML",
            });
          }
        }
      }
    }
  });
});

app.listen(env?.PORT, () => console.log(`${env?.PORT}th port's online...`));

it's a mention by user id, I've read docs too however I coudn't figure out what i need to do to reach my purpose. I typically use NODEJS + EXPRESS

levlam commented 1 month ago

You just need to include the username in the text of the message.

Behruz999 commented 1 month ago

levlam, you helped me get rid depress out, enormous thanks

and my modified code snippet:

const messageId = ctx.message_id;
const username = ctx.from.username;
const response = username ? `@${username} Please do not share links in this group!`
 : `<a href="tg://user?id=${user.id}">${user.first_name}</a> Please do not share links in this group!`;
const options = username ? { entities: [{ type: "mention", offset: 0, length: response.length }] } : {
  entities: [{
    type: "text_mention",
    offset: 0,
    length: response.length,
    user,
   },
  ], parse_mode: "HTML" };

  bot.sendMessage(chatId, response, options);