如何使用Telebot API或Telegram API发送消息到Telegram机器人。

huangapple go评论56阅读模式
英文:

How to send message to a telegram bot using telebot api or telegram api

问题

目前,我已在Telegram中创建了一个机器人,并使用telebot API执行某些操作,每当通过telebot API发送消息到机器人时执行。现在我正在创建一个新的应用程序,其中我的后端从webhook获取数据,我想直接将该数据发送到机器人,然后机器人将执行预定义的任务。这可能吗?我该如何做?任何指南的链接也将有助于。

到目前为止,我只回复了直接从telebot API接收到的机器人消息,从未从我的后端向机器人发送过消息。根据我的阅读,您需要获取要发送消息的用户的ID,您如何获取机器人的ID并直接向该ID发送数据呢?

英文:

I currently have created a bot in telegram and am using it to perform some action whenever a msg is sent to the bot uisng the telebot api. I now am creating a new app where my back end gets the data from a webhook and I want to directly send that data to the bot after which the bot will perform the pre defined task on it. Is it possible ?. How can I do it?. Links to any guides would also be helpful.

so far I have only ever replied to msg received to the bot direct from the telebot api an have never have sent a msg to the bot from my back end. From what I read you need to get the id of user you want to send msg to how can I get the id for a bot and send data to that id directly.

答案1

得分: -1

    import express from 'express';
    import TeleBot from 'telebot';

    const bot = new TeleBot(process.env.BOT_TOKEN);

    bot.on('/start', async (msg) => {
      const chatId = msg.chat.id;
      await bot.sendMessage(chatId, 'Hello world!');
    });

    const app = express();

    app.use(express.json());

    app.post('/webhook', (req, res) => {
      const chatId = process.env.BOT_CHAT_ID;
      const message = req.body.message;

      bot.sendMessage(chatId, message);

      res.send('Message sent to bot!');
    });

    const port = process.env.PORT || 3000;

    app.listen(port, () => {
      console.log(`Server listening on port ${port}`);
    });
英文:
import express from 'express';
import TeleBot from 'telebot';

const bot = new TeleBot(process.env.BOT_TOKEN);

bot.on('/start', async (msg) => {
  const chatId = msg.chat.id;
  await bot.sendMessage(chatId, 'Hello world!');
});

const app = express();

app.use(express.json());

app.post('/webhook', (req, res) => {
  const chatId = process.env.BOT_CHAT_ID;
  const message = req.body.message;

  bot.sendMessage(chatId, message);

  res.send('Message sent to bot!');
});

const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

does this code help?

huangapple
  • 本文由 发表于 2023年5月13日 23:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定