yagop / node-telegram-bot-api

Telegram Bot API for NodeJS
MIT License
8.45k stars 1.53k forks source link

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

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

sc0Vu commented 1 month ago

In tgbot, you can use markdownv2 to mention user. But I believe you may need to extend the sendMessage function to mention user (https://core.telegram.org/bots/api#markdown-style).

UPDATE: I think you can call sendMessage(id, message, { parse_mode: 'MarkdownV2' }) to tag user, just use markdown link and user id [inline mention of a user](tg://user?id=123456789). You can use HTML <a href="tg://user?id=123456789">inline mention of a user</a> to tag user either.