Automated github issue bot? - javascript

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.

Related

Need some help regarding the Elasticsearch engine and react js

I hope you are doing well, I need some help regarding the Elasticsearch engine. what I am doing is I am trying to create a search engine I have successfully post my data through kibana to elasticsearch engine. but "but how can I add the search component of elastyicsearch to my react app", I have like 4 million records into the kibana index, when I try to search directly from react it take a long time to display records into my frontapp app with nodejs api. below is the code with nodejs but the problem with this code it just gives me 10 records only.
router.get('/tweets', (req, res)=>{
let query = {
index: 'tweets',
// size: 10000
}
if(req.query.tweets) query.q = `*${req.query.tweets}*`;
client.search(query)
.then(resp => {
return res.status(200).json({
tweets: resp.body.hits.hits
});
})
.catch(err=>{
console.log(err);
return res.status(500).json({
err
});
});
});
Is there any way to impliment elasticsearch component directly to my reactjs app. like with the localhost:9200/index.. directly from the elasticsearch api?
Your request to Elasticsearch looks a bit strange to me, have you tried to search using a body like in the documentation? This line:
if(req.query.tweets) query.q = `*${req.query.tweets}*`;
doesn't seem like a correct way to write a query. Which field do you want to search for?
I saw that you tried to use the size field, which should be correct. You can also try the following:
client.search({
index: 'tweets',
body: {
size: 1000, // You can put the size here to get more than 10 results
query: {
wildcard: { yourfield: `*${req.query.tweets}*` }
}
}
}, (err, result) => {
if (err) console.log(err)
})
You could use SearchKit to directly query elasticsearch from you react app. But be aware that exposing DB services outside of your own infrastructure is bad practice.
You can use the component like this:
import {
SearchkitManager,
SearchkitProvider,
SearchkitComponent
} from 'searchkit'
const searchkit = new SearchkitManager(host)
class Render extends SearchkitComponent {
render(){
let results = await this.searchkit.reloadSearch()
return <div>{results}</div>
}
}
function table(){
return <SearchkitProvider searchkit={searchkit}>
<Render />
</SearchkitProvider>
}

MS teams bot JS - create conversation

I need to proactivly create conversation on channel in msteams. So i looked for examples but didn't find any examples of realy proactive conversation creation. All examples include first of all handling message, and creating conversation using context.
To be more accurate i have facebook, whatsapp, and web widget. Users write for example from facebook, i get message through fb webhook and i need to create new thread ( block with replies inside channel ) and only after that, someone who will answer in channel using thread block and i'll get message.
As i understood i need to bootstrap conversation object and use adapter.createConversation({ ...convFields }), but for example i don't have serviceUrl.
// i am using adapter from examples
new BotFrameworkAdapter({
appId: id,
appPassword: password
});
// then i have something like that in examples
const conversationParameters = {
isGroup: true,
channelData: {
channel: {
id: 'msteams'
}
},
activity: 'dsada'
};
const connectorClient = this.adapter.createConnectorClient(
context.activity.serviceUrl // i don't have context to get that serviceUrl, because i must do it first, not handle message and create thread after that.
);
const conversationResourceResponse = await connectorClient.conversations.createConversation(
conversationParameters as any
);
const conversationReference = TurnContext.getConversationReference(
context.activity // same here, i don't have context
);
conversationReference.conversation.id = conversationResourceResponse.id;
return [conversationReference, conversationResourceResponse.activityId];
In order to prevent (or at least hinder) spam, your bot can only send proactive messages to channels or group chats where it is already installed. In that instance you'll need to store the necessary information from the conversationUpdate membersAdded event you'll receive.
For 1:1 chats, it is possible to create a new conversation with a user, however your bot needs to know the Id of the user in order to do so. Typically this is achieved by retrieving the roster of a group chat or team where your bot is installed.
Essentially, it isn't possible to send a completely proactive message - the bot needs to be installed and/or have some amount of information about where it is sending the message previously.
Assuming you can achieve the correct permissions, it is possible to proactively install your bot. See this article for more details on that approach: https://learn.microsoft.com/en-us/graph/teams-proactive-messaging
Even though it is in C#, you may find this sample helpful as it demonstrates the minimal amount of information required in order to send proactive messages to each type of destination (which is the same across languages): https://github.com/clearab/teamsProactiveMessaging.
The relevant file is below:
public class MessageSender : IMessageSender
{
private ConnectorClient conClient;
private string serviceUrl;
public MessageSender(string serviceUrl, string id, string password)
{
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
conClient = new ConnectorClient(new Uri(serviceUrl), id, password);
}
public async Task<ResourceResponse> SendOneToOneMessage(string conversationId, Activity activity)
{
return await conClient.Conversations.SendToConversationAsync(conversationId, activity);
}
public async Task<ConversationResourceResponse> CreateOneToOneConversation(string userId, string tenantId)
{
var members = new List<ChannelAccount>()
{
new ChannelAccount
{
Id = userId
}
};
ConversationParameters conParams = new ConversationParameters
{
Members = members,
TenantId = tenantId
};
return await this.conClient.Conversations.CreateConversationAsync(conParams);
}
public async Task<ConversationResourceResponse> CreateAndSendChannelMessage(string channelId, Activity activity)
{
ConversationParameters conParams = new ConversationParameters
{
ChannelData = new TeamsChannelData
{
Channel = new ChannelInfo(channelId)
},
Activity = activity
};
ConversationResourceResponse response = await this.conClient.Conversations.CreateConversationAsync(conParams);
return response;
}
public async Task<ResourceResponse> SendReplyToConversationThread(string threadId, Activity activity)
{
return await this.conClient.Conversations.SendToConversationAsync(threadId, activity);
}
}

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

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

Getting PUT routes to work in Angular

I'm seeking some wisdom from the Angular community. I am working on a simple project using the MEAN stack. I have set up my back-end api and everything is working as expected. Using Postman, I observe expected behavior for both a GET and PUT routes to retrieve/update a single value - a high score - which is saved in it's own document in its own collection in a MongoDB. So far so good.
Where things go off track is when trying to access the PUT api endpoint from within Angular. Accessing the GET endpoint is no problem, and retrieving and displaying data works smoothly. However, after considerable reading and searching, I am stll unable to properly access the PUT endpoint and update the high score data when that event is triggered by gameplay. Below are the snippets of code that I believe to be relevant for reference.
BACK-END CODE:
SCHEMA:
const _scoreSchema = {
name: { type: String, required: true },
value: { type: Number, "default": 0 }
};
ROUTES:
router
.route('/api/score/:highScore')
.put(scoreController.setHighScore);
CONTROLLER:
static setHighScore(req, res) {
scoreDAO
.setHighScore(req.params.highScore)
.then(highScore => res.status(200).json(highScore))
.catch(error => res.status(400).json(error));
}
DAO:
scoreSchema.statics.setHighScore = (value) => {
return new Promise((resolve, reject) => {
score
.findOneAndUpdate(
{"name": "highScore"},
{$set: {"value": value} }
)
.exec(function(err, response) {
err ? reject(err)
: resolve(response);
});
});
}
ANGULAR CODE:
CONTROLLER:
private _updateHighScore(newHighScore): void {
console.log('score to be updated to:', newHighScore)
this._gameService
.updateHighScore(newHighScore);
}
SERVICE:
updateHighScore(newHighScore: Number): Observable<any> {
console.log(newHighScore);
let url = '/api/score/' + newHighScore;
let _scoreStringified = JSON.stringify({value: newHighScore});
let headers = new Headers();
headers.append("Content-Type", "application/json");
return this._http
.put(url , _scoreStringified, {headers})
.map((r) => r.json());
}
Note that the console.log(newHighScore) in the last block of code above correctly prints the value of the new high score to be updated, it's just not being written to the database.
The conceptual question with PUT routes in angular is this: If the api is already set up such that it receives all the information it needs to successfully update the database (via the route param) why is it required to supply all of this information again in the Angular .put() function? It seems like reinventing the wheel and not really utilizing the robust api endpoint that was already created. Said differently, before digging into the docs, I naively was expecting something like .put(url) to be all that was required to call the api, so what is the missing link in my logic?
Thanks!

How to write a simple chat, without a database on meteor.js and react.js?

I want to write a simple chat on meteor.js and thus I do not want to store the data in the database.
But I never found how to make an application without a database.
Here is an example of code as I can imagine.
Server code:
export let ws = [{_id:'1', text:'test1'}, {_id:'2', text:'test2'}];
Meteor.publish('ws', function wsPub() { return ws; });
let ctr = 3;
Meteor.methods({
'addMsg'(text) { ws.push({_id:ctr+1, text:text}); }
});
and client code:
import {ws} from '../api/model.js';
class Rtc extends Component {
constructor(props) {
super(props);
}
addMsg(e){
e.preventDefault();
Meteor.call('addMsg', this.refs.input.value);
}
render() {
return (
<div>
{this.props.ws.map((item, i)=>{
return(<span key={i._id}>{item.text}</span>);
})}
<input type="text" ref="input" />
<input type="submit" value="submit" onClick={this.addMsg.bind(this)}/>
</div>
);
}
}
export default createContainer( () => {
Meteor.subscribe('ws');
return { ws: ws };
}, Rtc);
but I do not understand what I wrote is not so in the createContainer?
UPD: I updated server code, but still websockets does not work:
Meteor.publish('ws', function wsPub() {
let self = this;
ws.forEach( (msg)=> {
self.added( "msg", msg._id, msg.text );
});
self.ready();
// return ws;
});
If you want to control what is sent over a publish, get a reference to the "publish instance" (really a specific client with a specific subscription) and use its add/change/remove commands:
let messages = [];
let clients = [];
Meteor.publish('ws', function() {
clients.push(this);
_.each(messages, (message) => {this.added('msg', message._id, message);});
this.ready();
});
Meteor.methods({
addMsg(text) {
let newMessage = {_id: Meteor.uuid(), text: text};
messages.push(newMessage);
_.each(clients, (client) => {client.added('msg', newMessage._id, newMessage);});
}
});
Regarding your code that you wrote in an update: you're sending a string where the function added expects a document (an object). Also, unlike this example above, you do not tell the clients when the ws (messages array) has changed.
I'd recommend also renaming these things to be more verbose and clear :)
What you suppose won't work. Because Meteor.publish returns a cursor to a Collection or array of Collections. According to the official documentation:
Publish functions can return a Collection.Cursor, in which case Meteor will publish that cursor’s documents to each subscribed client. You can also return an array of Collection.Cursors, in which case Meteor will publish all of the cursors.
Again, when you subscribe to a publication, it stores the data(as cursor to the same collection as the publication) locally in MiniMongo. So a chat without database is not technically possible with pub-sub in Meteor.

Categories

Resources