Node.js Telegram BOT retrieve data from API
To retrieve data from an API and send it via a Telegram bot using Node.js, you can combine the axios library for API requests with the node-telegram-bot-api library for sending messages. Below is an example that fetches data from an API and then sends it as a message using a Telegram bot:
const TelegramBot = require('node-telegram-bot-api'); const axios = require('axios'); // Telegram Bot API token (replace this with your own token) const token = 'YOUR_TELEGRAM_BOT_API_TOKEN'; const bot = new TelegramBot(token, { polling: true }); // API endpoint to fetch data from const apiUrl = 'YOUR_API_ENDPOINT'; // Replace with your API endpoint // Client ID and Client Secret for authentication const clientId = 'YOUR_CLIENT_ID'; const clientSecret = 'YOUR_CLIENT_SECRET'; // Function to fetch data from the API const fetchDataFromAPI = async () => { try { const response = await axios.get(apiUrl, { headers: { 'Client-ID': clientId, 'Client-Secret': clientSecret, }, }); // Sending the fetched data to the Telegram bot bot.sendMessage(CHAT_ID, JSON.stringify(response.data)); } catch (error) { console.error('Error fetching data from API:', error.message); } }; // Set the chat ID to which you want to send the message const CHAT_ID = 'YOUR_CHAT_ID'; // Replace with your chat ID // Call the function to fetch data from the API and send it to the Telegram bot fetchDataFromAPI();
Make sure to replace 'YOUR_TELEGRAM_BOT_API_TOKEN', 'YOUR_API_ENDPOINT', 'YOUR_CLIENT_ID', and 'YOUR_CLIENT_SECRET' with your actual values. Also, replace 'YOUR_CHAT_ID' with the ID of the chat where you want to send the message. Run this script using Node.js, and it will fetch data from the specified API and send it to the designated Telegram chat.
Komentar
Posting Komentar