Node.Js using tmi.js and cleverbot.io trouble - javascript

I am currently having trouble with a twitch bot that I am trying to make. I decided to try out Node.js, but I am having a couple of errors. I am using the tmi.js and cleverbot.io libraries, installed via npm. My code so far is as shown below:
var tmi = require('tmi.js');
var cleverbot = require('cleverbot.io');
var options = {
options: {
debug: true
},
connections: {
cluster: "aws",
reconnect: true
},
identity: {
username: "TwitchCleverBot",
password: "APIKEY"
},
channels: ["klausmana"]
};
var client = new tmi.client(options);
var smartbot = new
cleverbot('APIUSERNAME','APIKEY');
client.connect();
client.on("chat", function(channel, userstate, message, self){
if(self){
return;
}
if(message.toLowerCase().includes("cleverbot")){
var lowmessage = message.toLowerCase();
var newmessage = lowmessage.replace("cleverbot", " ");
smartbot.create(function(err, session){
smartbot.ask(newmessage, function(err, response){
client.action(channel, response);
});
});
}
});
This is all the code I have in my app.js so far. The error occurs when I try to make a request to the cleverbot.io, so the tmi.js part works (with as much as I know). It gives me the following error:
Apparently, I am trying to make a JSON parse to a html file, but I really do not understand where and how that happens if anyone is able to help, I would really appreciate it.
P.S : The project is indeed a twitch bot, but my problem was in Node.js and Javascript, so that is why I decided to turn to StackOverflow

Related

Automated github issue bot?

I would like to make a discord bot that creates an issue based on user input from discord. Any idea how I would do this? I am using JavaScript and would like to integrate it into an existing bot. Thanks!
You can take ideas from the LeagueSandbox/IssueBot (Typescript), which does create issues.
It does use npmjs.com/package/github-api, from github-tools/github
export class IssueCommand extends Command {
execute() {
if(!this.args) {
return
}
let issueBody = ISSUE_TEMPLATE
.replace("{PLACEHOLDER}", this.args[2] || "_No content_")
.replace("{CHANNEL}", this.message.channel.name)
.replace("{USER}", this.message.author.username)
Bot.gitHub.api.issues.create({
owner: config.githubName,
repo: this.args[0],
title: this.args[1],
body: <any>issueBody // Typings for the `github` package are incorrect, so we have to cast to any here.
},
(error, response) => this.handleGithubResponse(error, response)
)
}
handleGithubResponse(error, response) {
if(error) {
let formattedError = JSON.stringify(error, null, 4)
let reply = ERROR_TEMPLATE.replace('{PLACEHOLDER}', formattedError)
this.message.reply(reply)
return
}
let reply = SUCCESS_TEMPLATE.replace('{PLACEHOLDER}', response.html_url)
this.message.reply(reply)
}
}
You have to set up that bot in your Discord application.
Maybe see the GitHub API docs for Creating Issues
You might need to create an app for it.

How to login to gmail account and read a mail in protractor not using the browser

I have a scenario which I need to login to a gmail account and read the content or the message. Then need to get a URL from that message. I can do this using a browser in protractor. But the issue is that gmail account enabled the 2FA. I have achieved this using the core Selenium which has jar files to log in to the gmail account using IMAP protocol.
Can someone please give me a good solution?
You can read emails from Gmail inside protractor tests using mail-listener2 npm package. Check the below example code.
mailListener.ts
const MailListenerClient = require("mail-listener2");
const cheerio = require('cheerio');
const simpleParser = require('mailparser').simpleParser;
export class MailListener {
public mailListener:any;
constructor() {
this.mailListener = new MailListenerClient({
username: "username#gmail.com",
password: "password",
host: "imap.gmail.com",
port: 993,
tls: true,
mailbox: "INBOX",
searchFilter: ["UNSEEN", ["FROM", "fromemail#gmail.com"],["SUBJECT","subject of the email"]],
/*it will search for are "unseen" mail send from "fromemail#gmail.com" with subject "fromemail#gmail.com"*/
connTimeout: 10000,
authTimeout: 5000,
markSeen: true,
mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: {directory: "attachments/"},
debug : console.log
});
}
init() {
this.mailListener.start();
}
close() {
this.mailListener.stop();
}
getLinkFromEmail() {
var self = this;
return new Promise((resolve, reject) => {
self.mailListener.on("mail", function (mail) {
/*simpleParser is used to convert string to HTML format*/
simpleParser(mail.eml).then(function (parsedEmail) {
var html = parsedEmail.html;
/* cheerio is used to write query on parsed HTML content
* refer https://www.npmjs.com/package/cheerio
*/
resolve(cheerio.load(html)("a").attr("href"));
});
});
self.mailListener.on("error", function (err) {
reject(err);
});
});
}
}
test.ts
import {MailListener} from "mailListner";
describe("Read email from gmail using imap", function () {
let mailListener = new MailListener();
beforeAll(function(){
mailListener.init();
});
afterAll(function(){
mailListener.close();
})
it("Test email recieved",function(){
let urlFromEmail = mailListener.getLinkFromEmail();
/*Perform some action on UI that triggers email.(Just for example im doing it)*/
element(by.id("email")).sendKeys("email#gmail.com");
element(by.buttonText("Send Email")).click();
expect(urlFromEmail).toEqual("some link");
})
});
I have written the code in typescript and hope you can rewrite the same in javascript. Let me know if this is clear or do I need to add more details to the code.
One of the best practice is to use Gmail API. Take a look at official documentation

How to use servicebus topic sessions in azure functionapp using javascript

I have an Azure Functionapp that processes some data and pushes that data into an Azure servicebus topic.
I require sessions to be enabled on my servicebus topic subscription. I cannot seem to find a way to set the session id when using the javascript functionapp API.
Here is a modified extract from my function app:
module.exports = function (context, streamInput) {
context.bindings.outputSbMsg = [];
context.bindings.logMessage = [];
function push(response) {
let message = {
body: CrowdSourceDatum.encode(response).finish()
, customProperties: {
protoType: manifest.Type
, version: manifest.Version
, id: functionId
, rootType: manifest.RootType
}
, brokerProperties: {
SessionId: "1"
}
context.bindings.outputSbMsg.push(message);
}
.......... some magic happens here.
push(crowdSourceDatum);
context.done();
}
But the sessionId does not seem to get set at all. Any idea on how its possible to enable this?
I tested sessionid on my function, I can set the session id property of a message and view it in Service Bus explorer. Here is my sample code.
var connectionString = 'servicebus_connectionstring';
var serviceBusService = azure.createServiceBusService(connectionString);
var message = {
body: '',
customProperties:
{
messagenumber: 0
},
brokerProperties:
{
SessionId: "1"
}
};
message.body= 'This is Message #101';
serviceBusService.sendTopicMessage('testtopic', message, function(error)
{
if (error)
{
console.log(error);
}
});
Here is the test result.
Please make sure you have enabled the portioning and sessions when you created the topic and the subscription.

How do I use persist with node.js?

I am attempting to get familiar with this persist package for node. Can someone tell me if the connection is being made here with persist.connect or are these properties?
var persist = require("persist");
var type = persist.type;
// define some model objects
Phone = persist.define("Phone", {
"number": type.STRING
});
Person = persist.define("Person", {
"name": type.STRING
}).hasMany(this.Phone);
persist.connect({
driver: 'sqlite3',
filename: 'test.db',
trace: true
}, function(err, connection) {
Person.using(connection).all(function(err, people) {
// people contains all the people
});
});
The code above runs without error on my system if I just change this.Phone to Phone.
persist.connect "connects" to a test.db file which contains the database.

Accessing MySQL database in node.js - internal assertion fails

I'm trying to connect to MySQL database from node.js using db-mysql library. Everything works great with example code, but now I'm trying to write a simple ORM.
This is my code:
require.paths.unshift('/usr/lib/node_modules'); // default require.paths doesn't include this
function Model() {
this.database = null;
}
Model.prototype.getDB = function(callback) {
if (this.database != null)
callback(this.database);
else {
console.log("Connecting to database...");
this.database = require("db-mysql").Database({
"hostname" : "localhost",
"user" : "root",
"password" : "pass",
"database" : "miku",
}).on("ready", function() {
console.log("Database ready, saving for further use.");
this.database = this;
callback(this);
});
}
}
exports.Model = Model;
And simple code I use for testing:
orm = require('./orm');
model = new orm.Model();
model.getDB(function (db) { console.log("callback'd"); });
It looks fine (at least for me), however node.js fails with internal assertion:
Connecting to database...
node: /usr/include/node/node_object_wrap.h:61: void node::ObjectWrap::Wrap(v8::Handle<v8::Object>): Assertion `handle->InternalFieldCount() > 0' failed.
Przerwane (core dumped)
After further investigation, if fails before/during creating Database object. I have no idea why this happens. I first though that it's because I was using git node.js version, but it fails with current release (v0.4.7) as well.
I'm trying to track down this issue in node.js code, with no success at the moment.
Oh, it was me to fail hard. It seems that having Python background is undesired in JavaScript world ;).
Database initialization should look like:
db = require("db-mysql");
new db.Database({
"hostname" : "localhost",
"user" : "root",
"password" : "pass",
"database" : "miku",
}).on("ready", function() {
console.log("Database ready, saving for further use.");
this.database = this;
callback(this);
}).connect();
So, I basically forgot to call new and connect().

Categories

Resources