deploy telegram bot on heroku - node.js

I want to learn how to create telegram bot but I have trouble on deploying it on the cloud. I kept getting this error on Heroku log
2021-11-01T16:51:38.071120+00:00 heroku[router]: at=info method=POST path="/2xxxxxXXxx:AAAAAAAAxxxx-xxx" host=xxxx-Xxxx-xxxx.herokuapp.com request_id=ed02154c-af96-44b7-af50-0ad1d8891f8f fwd="91.108.6.83" dyno=web.1 connect=0ms service=1ms status=500 bytes=404 protocol=https
2021-11-01T16:51:38.076047+00:00 app[web.1]: TypeError: bot.processUpdate is not a function
2021-11-01T16:51:38.076210+00:00 app[web.1]: at /app/index.js:18:6
here is my index.js
// DEPENDENCIES
const express = require('express');
require('dotenv').config();
const bot = require('./bot');
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.get('/', (req, res) => {
res.status(200).json({ message: 'Hello from the Bot API.' });
});
// TELEGRAM WEBHOOK - https://core.telegram.org/bots/api#setwebhook
app.post(`/${process.env.TELEGRAM_TOKEN}`, (req, res) => {
bot.processUpdate(req.body);
res.status(200).json({ message: 'ok' });
});
app.listen(port, () => {
console.log(`\n\nServer running on port ${port}.\n\n`);
});
and here is my bot.js
//dependency
const TelegramBot = require('node-telegram-bot-api');
require('dotenv').config();
const axios = require('axios');
const fs = require('fs');
//bot token
const token = process.env.TELEGRAM_TOKEN;
//initialize bot
var bot;
// if production env, we use webhooks
// https://core.telegram.org/bots/api#setwebhook
// https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md#TelegramBot+setWebHook
if (process.env.NODE_ENV === 'production') {
bot = new TelegramBot(token);
bot.setWebHook(process.env.HEROKU_URL + bot.token);
console.log('**** BOT initiated ***** ');
} else {
// otherwise, we use polling
// differences between webhooks and polling:
// https://core.telegram.org/bots/webhooks
// https://stackoverflow.com/questions/40033150/telegram-bot-getupdates-vs-setwebhook
bot = new TelegramBot(token, { polling: true });
}
console.log(`Bot started in the ${process.env.NODE_ENV} mode`);
bot.onText(/^\/say_hello (.+)$/, function (msg, match) {
var name = match[1];
bot.sendMessage(msg.chat.id, 'Hello ' + name + '!').then(function () {
// reply sent!
});
});
bot.onText(/^\/sum((\s+\d+)+)$/, function (msg, match) {
var result = 0;
match[1].trim().split(/\s+/).forEach(function (i) {
result += (+i || 0);
})
bot.sendMessage(msg.chat.id, result).then(function () {
// reply sent!
});
});
everything works flawlessly on local. I thought the problem was with the webhook URL at first, after spending hours I realized the log said something else. I'm using https://github.com/yagop/node-telegram-bot-api and the documentation definitely still have processUpdate written but I have no idea how to test it. Since deploying on local works maybe the problem is somewhere else that I have no idea about.

You need to exports bot defined in bot.js adding to that module next line
module.exports = bot

Related

how can i print discord messages to express server?

I have been searching for a long time how I can send a discord message to my site.
then i found the express, i don't understand how to print data to site when discord message event is triggered can you help with this issue?
I just tried the following but it only works once and then it doesn't work again
const {Client} = require("discord.js")
const client = new Client({intents: ["GUILDS","GUILD_MEMBERS","GUILD_MESSAGES","GUILD_PRESENCES"]})
client.login("token")
client.on("ready", () => {
console.log("oks")
})
const express = require("express")
var app = express();
client.on("message", message => {
app.get("/",function(qu,res){
res.send(message.content)
})
})
})
let servers = app.listen(3000,function(){
})
Use messageCreate because the message event is depreciated. app.get() should be defined outside your message event listener. I'm not sure what you mean by "print data to site", but you can add every message sent to a database or maybe a JSON file if you'd like, and send that data through express. If you want messages on your site updated in real-time look into sockets.
Here's an example of what I mean:
const { Client } = require("discord.js")
const express = require("express")
const client = new Client({ intents: ["GUILD_MESSAGES"] })
const app = express();
const messages = []
app.get("/", (req, res) => {
res.status(200).json(messages)
})
client.on("ready", () => {
console.log("ready!")
})
client.on("message", message => {
messages.push(message)
})
client.login("token")
app.listen(3000, () => console.log("listening on port 3000")

Express app failing to connect without errors

I have been trying to connect my express app, but for some reason it is just not connecting.
I am going to "IP:PORT" on chrome and I get a typical "Refused to connect" error.
I am using node.js, and the latest version of express.
"Received" does not print to the console, however it logs "App listening on port 8088"
I have tried a lot of things, hosting on digital ocean, no connection. I am currently trying it in VSC (Ip address is my ipv4 address)
When trying using HTTP, I get a connect fail error.
My code:
const express = require('express');
const app = express()
app.use(express.json())
const fs = require('fs');
require('dotenv').config()
const serverKey = process.env.SERVER_KEY
const port = process.env.PORT
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
module.exports = {
async execute(client) {
console.log('Test')
app.post("/getVerificationCode", function (req, res, next) {
console.log("Recieved")
if (req.body.serverKey !== serverKey) {
console.log("Invalid serverKey supplied.")
return res.status(403).json({
error: "You do not have permission to use this."
})
}
let verificationCode = randomString(4, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').toUpperCase()
const userID = parseInt(req.body.userid)
console.log(verificationCode)
client.verificationCodes[userID] = {
code: verificationCode
}
fs.writeFile("./codes.json", JSON.stringify(client.verificationCodes, null, 4), err => {
if (err) throw err
})
return res.status(200).json({
VerificationCode: verificationCode
})
})
app.get("/*", function (req, res, next) {
return res.status(200).json({})
})
app.listen(port)
console.log(`App listening on port ${port}`)
}
}
"Test" does log, so the module IS being required. Before, I was trying it in my server.js, but that did not work and the code was messy, so I moved it into a folder.
I would really appreciate some help, thank you!

Telegram Bot - JS - Bot stops working after a while

Devs! I created a simple bot for Telegram using JS language that when typing '/ tutorials' a txt list is loaded.
I deployed this bot to Heroku so that it goes online.
The problem is that the bot works for a while and then stops working, I don't know why.
Has anyone had this problem?
//Correction message error on console
process.env.NTBA_FIX_319 = 1;
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
const TelegramBot = require('node-telegram-bot-api')
const TOKEN = 'myToken'
const bot = new TelegramBot(TOKEN, { polling: true })
bot.on('message', (msg) => {
const chatId = msg.chat.id;
const text = msg.text;
//read list txt
var fs = require('fs');
try {
var data = fs.readFileSync('lista.txt', 'utf8');
} catch (e) {
console.log('Error:', e.stack);
}
//send message
if (text.includes('/tutoriais')) {
bot.sendMessage(chatId, `Olá, ${msg.chat.first_name}! 😎\nLista de Tutoriais`)
bot.sendMessage(chatId, data);
}
});
I added a webhook to the python file and it ended up working fine
https://github.com/victoraugusto6/bot-Telegram-JS-Heroku

textnow api with nodejs not working logging in

const express = require("express");
const app = express();
const textNow = require('textnow-api');
app.use(express.static("public"));
app.get("/", function(request, response) {
textNow.login("email", "'password").then(client => {
console.log(`Logged in as ${client.username}`);
textNow.fetchMessages(client.id, client.username).then(messages => {
console.log(messages.map(message => `ID: ${message.id} | Message: ${message.message} | Sender: ${message.contact_value}`).join('\n'));
});
});
});
const listener = app.listen("80", function() {
console.log("Your app is listening on port " + listener.address().port);
});
It only responds with a 400 error, even though I have the correct login. Can anyone please help me with this, or is it depricated and not working anymore?
textnow-api is deprecated you can use it textbelt or Twilio api

Viber Chatbot - Creating an echo bot

I was following the Viber Node.JS Bot Documentation and was creating an echo bot that would repeat the messages back to the user. But it does not work and the bot does not reply to my messages. Here is the code:
'use strict';
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const bot = new ViberBot({
authToken: "api-key",
name: "Override API",
avatar: "https://cdn3.iconfinder.com/data/icons/customer-support-7/32/40_robot_bot_customer_help_support_automatic_reply-512.png" // It is recommended to be 720x720, and no more than 100kb.
});
// Perfect! Now here's the key part:
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
// Echo's back the message to the client. Your bot logic should sit here.
response.send(message);
});
// Wasn't that easy? Let's create HTTPS server and set the webhook:
const https = require('https');
const port = process.env.PORT || 8080;
// Viber will push messages sent to this URL. Web server should be internet-facing.
const webhookUrl = "https://webhook.site/09f0b45e-1ad8-466c-9441-e5edb3d783e3";
https.createServer(bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
try this :
const webhookUrl = "https://webhook.site/09f0b45e-1ad8-466c-9441-e5edb3d783e3";
app.use('/viber/webhook', bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${webhookUrl}/viber/webhook`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
instead of:
https.createServer(bot.middleware()).listen(port, () => bot.setWebhook(webhookUrl));
Source

Resources