Telegram Bot - JS - Bot stops working after a while - node.js

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

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")

deploy telegram bot on heroku

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

Dialogflow/Google Actions fulfillment (using Google App Engine & Storage) returning error 4: DEADLINE EXCEEDED, despite being simple

So let's say I want to create a simple Action that provides the user with a random code from a list of codes (strings in a .csv file). What I currently have set up is a Dialogflow agent with fulfillment running on Google App Engine and I stored the 'codes.csv' file using Google Storage.
The code I have succefully reads the file (I have it log the first code as a check), however, when it comes to returning a response to Dialogflow, I get a "Webhook call failed. Error: DEADLINE_EXCEEDED."
I understand that responses to Dialogflow/Google Actions can't take longer than 10 seconds to complete, but from what I gathered from the logs is that it has read the relatively small codes.csv within 3 seconds. I don't understand what causes the holdup...
The code running on Google App Engine:
const express = require('express');
const bodyParser = require('body-parser');
const csv = require('csv-parser');
const { WebhookClient } = require('dialogflow-fulfillment');
const {dialogflow} = require('actions-on-google');
const app = dialogflow({debug: true});
const {Storage} = require('#google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('<bucket name>');
const file = bucket.file('codes.csv');
let codes = [];
file.createReadStream()
.pipe(csv())
.on('error', function(err) {
console.log('woops');
})
.on('data', function(response) {
codes.push(response);
})
.on('end', function() {
console.log('read csv');
console.log(codes[0]['code']); // checks whether 'codes' actually contains the codes
});
function randomCode() {
return codes[Math.floor(Math.random()*codes.length)]['code'];
}
app.intent('Default Welcome Intent', (conv) => {
console.log(codes[1]['code']);
conv.ask('Hey, here is your random code: ' + randomCode());
console.log(codes[2]['code']);
}); // neither of the two console.log are reached here
const expressApp = express().use(bodyParser.json());
expressApp.post('/', app);
expressApp.listen(4444);
Had my app listen to port 4444, but App Engine needs to listen to port 8080

IBM Watson integration with Twilio via Whatsapp

I am trying to integrate IBM Watson bot with twilio, whatsapp using IBM cloud functions using Nodejs. I followed the following to come up with this code https://github.com/ChaitanyaGhantasala/Whatsapp/blob/master/app.js
Please find below the Code:
// Import Modules
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var AssistantV1 = require('ibm-watson/assistant/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
// Twilio Credentials
var accountSid = '';
var authToken = '';
var client = require('twilio')(accountSid, authToken);
app.use(bodyParser.urlencoded({ entended: false }));
var env= require('dotenv').config()
// Watson Credentials
var assistant = new AssistantV1({
version: '2018-09-20',
authenticator: new IamAuthenticator({
apikey: '',
}),
url: '',
});
var context1 = {};
app.get('/test', function (req, res) {
})
// API
app.post('/api', function (req, res) {
console.log("Request Object");
var From = req.body.From;
console.log(From);
assistant.message({
skill_id: '',
input: { 'text': req.body.Body },
context: context1
}, function (err, response) {
if (err)
console.log('error:', err);
else {
context1 = response.context;
var msg = response.output.text[0];
console.log("message", msg);
client.messages
.create({
body: msg,
from:'whatsapp:+14155238886',
to: 'From',
}).then(message = console.log(msg))
.done();
}
})
});
//PORT Listen
app.listen(process.env.PORT||8000, function () {
console.log("Server is running at 8000");
});
This line shows an error
const { IamAuthenticator } = require('ibm-watson/auth');
Also, i have no idea how the integration work
Can you please help me with any resources?
This does not work with me,
I am basing this answer on you not being able to format code. The code you show is basic / simple, yet you have made it undecipherable by not formatting it.
You say your error is on the line:
const { IamAuthenticator } = require('ibm-watson/auth');
This is a simple import of a pre-requisite module, which suggests that you have not imported the module ibm-watson, however, if that were the case then the line above it should also fail.
var AssistantV1 = require('ibm-watson/assistant/v1');
In which case you are hitting a version problem, either in your version of Node.js that is not recognising the const format, or in the version of ibm-watson that is not exporting ibm-watson/auth.
Based on your lack of basic code formatting, I am guessing that it is the version of Node.js. The current version of ibm-watson : 5.6.0 requires "node": ">=10.0.0".

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