discord.js How do i make a bot talk in a specific channel - chat

I'm making a announcement command where when a admin does -announce (text) it will announce it into the channel called announcement, How would I do this?

In the standard implementation, you can do it as follows
bot.on('message', message => {
if(message.content.startsWith('-announce') && message.member.hasPermission("ADMINISTRATOR")) {
let announceChannel = bot.channels.get('YOUR ChannelID')
if(!announceChannel) return
announceChannel.send(message.content.substr(10,message.content.length)) //10 its length of you command
}})

Getting channel by name:
const Channel = client.channels.find(channel => channel.name === "announcements");
client.channels is a Collection.
Sending the message using .send() method of GuildChannel:
Channel.send("your announcement here");

Related

QnA Maker: How to count a specific answer in a session?

I have QnA Maker chatbot. I want to do that: If bot gives the DefaultNoAnswer 3 times in a session, I want to show different DefaultNoAnswer. How can I count the DefaultNoAnswers in QnAMakerBaseDialog ?
ex:
Client: asdaaasd
Bot: Sorry, Could you phrase your question differently?
Client: dsjhdsgjdsa
Bot:Sorry, Could you phrase your question differently?
Client: aasdjhajds
Bot: Sorry, I couldn't get the question. Send an email for detailed information.
I find the best way to handle this is with a conversation state variable. I have my default message set up in my helper (i.e. I have a helper file that makes the call to QnA Maker, checks the confidence, and sends a default message in case of low confidence or no answer). If you are using a similar case, you can increment your state variable there. If you are using QnA Maker's default answer directly, you still need to do some check on every result before sending the response to user. I haven't used that method, but I would probably just check the result for the default answer and increment the variable accordingly.
Here is a sample for the first case. I am assuming here that you are already familiar with managing user and conversation state.
var qnaResult = await QnAServiceHelper.queryQnaService(query, oldState);
if (qnaResult[0].score > MINIMUM_SCORE) {
const conversationData = await this.dialogState.get(step.context, {});
conversationData.defaultAnswerCounter = 0;
await this.conversationState.saveChanges(step.context);
var outputActivity = MessageFactory.text(qnaResult[0].answer);
} else {
const conversationData = await this.dialogState.get(step.context, {});
conversationData.defaultAnswerCounter += 1;
if (conversationData.defaultAnswerCounter <= 2) {
var outputActivity = defaultAnswer;
} else {
var outputActivity = escalationAnswer;
}
await this.conversationState.saveChanges(step.context);
}

bot responds to specific channel discord.js

How do I get a bot to respond only to a specific channel where I write a command
client.on('message', message => {
if(message.content.startsWith("hey")) {
message.channel.send('hello');
}
});
A simple approach is to check message.channel.name against the name of the authorized channel or list of channels. For example if (message.channel.name === "BotLounge"). For other information available about the channel please see https://discord.com/developers/docs/resources/channel
You can use message.channel.id because the channel has a unique id, or you can check with message.channel.name but this is less unique, and you can have troubles with it.
Sou you can do something like:
const myChannelId = '0123456789'
client.on('message', message => {
if(message.channel.id === myChannelId) return;
if(message.content.startsWith("hey")) {
message.channel.send('hello');
}
});

Twilio Autopilot - sourceChannel

Is there a way to check the source channel (ie Alexa vs Programmable Chat) in the functions to direct to different answers depending on the source? I found some sourceChannel references in the docs, but I couldn't figure out how to reference those properties in a function.
https://www.twilio.com/docs/autopilot/api/query#query-properties
If you use Twilio functions behind your Autopilot task, it is possible.
In the event parameter you'll find the channel.
Eg. Checking if facebook else Whatsapp
exports.handler = function(context, event, callback) {
let channel = "";
if(event.Channel == "messageing.facebook-messenger"){
channel = "Facebook";
}else{
channel = "Whatsapp";
}
responseObject = {
"actions": [
{
"say": `Your channel is ${channel}`
}
]
};
return callback(null, responseObject);
}

Microsoft Bot Framework channel integration: more endpoints?

I'm using Microsoft Bot Framework using the channel registration product and the REST API. I have setup the "messaging endpoint" and everything works fine for sending and receiving messages.
But I don't just want to send/receive messages. Something as simple as setting up a welcome message seems impossible because my endpoint receives nothing other than messaging events (when the bot is in the channel / conversation.)
Is there something I have missed?
I would like to setup several endpoints, or use the same, whatever, to listen to other types of events.
You need to implement in the MessageController something like these:
Pay attention in the else if. The funcition in the controller is HandleSystemMessage.
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
IConversationUpdateActivity update = message;
var cliente = new ConnectorClient(new System.Uri(message.ServiceUrl), new MicrosoftAppCredentials());
if (update.MembersAdded != null && update.MembersAdded.Count > 0)
{
foreach(var member in update.MembersAdded)
{
if(member.Id != message.Recipient.Id)
{
//var username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var username = message.From.Name;
var reply = message.CreateReply();
//string dir = System.AppDomain.CurrentDomain.BaseDirectory + "Images" + Path.DirectorySeparatorChar + "cajamar.png";
string dir = HttpRuntime.AppDomainAppPath + "Images" + Path.DirectorySeparatorChar + "cajamar.png";
reply.Attachments.Add(new Attachment(
contentUrl: dir,
contentType: "image/png",
name: "cajamar.png"
));
reply.Text = $"Bienvenido {username} al ChatBot de convenios:";
cliente.Conversations.ReplyToActivity(reply);
//var reply = message.CreateReply();
//reply.Text = $"El directorio base es: {HttpRuntime.AppDomainAppPath}";
//cliente.Conversations.ReplyToActivityAsync(reply);
}
}
}
}

Parse.com resend verification email

I am using the email verification feature that Parse offers and would like my users to be able to resend the email verification if it fails to send or they cannot see it. Last I saw, Parse does not offer an intrinsic way to do this (stupid) and people have been half-hazzerdly writing code to change the email and then change it back to trigger a re-send. Has there been any updates to this or is changing the email from the original and back still the only way? Thanks
You should only need to update the email to its existing value. This should trigger another email verification to be sent. I haven't been able to test the code, but this should be how you do it for the various platforms.
// Swift
PFUser.currentUser().email = PFUser.currentUser().email
PFUser.currentUser().saveInBackground()
// Java
ParseUser.getCurrentUser().setEmail(ParseUser.getCurrentUser().getEmail());
ParseUser.getCurrentUser().saveInBackground();
// JavaScript
Parse.User.current().set("email", Parse.User.current().get("email"));
Parse.User.current().save();
You have to set the email address to a fake one save and then set it back to the original and then parse will trigger the verification process. Just setting it to what it was will not trigger the process.
iOS
if let email = PFUser.currentUser()?.email {
PFUser.currentUser()?.email = email+".verify"
PFUser.currentUser()?.saveInBackgroundWithBlock({ (success, error) -> Void in
if success {
PFUser.currentUser()?.email = email
PFUser.currentUser()?.saveEventually()
}
})
}
Poking around the source code for Parse server, there doesn't seem to be any public api to manually resend verification emails. However I was able to find 2 undocumented ways to access the functionality.
The first would be to use the internal UserController on the server (for instance from a Cloud function) like this:
import { AppCache } from 'parse-server/lib/cache'
Cloud.define('resendVerificationEmail', async request => {
const userController = AppCache.get(process.env.APP_ID).userController
await userController.resendVerificationEmail(
request.user.get('username')
)
return true
})
The other is to take advantage of an endpoint that is used for the verification webpage:
curl -X "POST" "http://localhost:5000/api/apps/press-play-development/resend_verification_email" \
-H 'Content-Type: application/json; charset=utf-8' \
-d $'{ "username": "7757429624" }'
Both are prone to break if you update Parse and internals get changed, but should be more reliable than changing the users email and then changing it back.
We were setting emails to an empty string, but found that there was a race condition where 2 users would hit it at the same time and 1 would fail because Parse considered it to be a duplicate of the other blank email. In other cases, the user's network connection would fail between the 2 requests and they would be stuck without an email.
Now, with Parse 3.4.1 that I'm testing, you can do (for Javascript):
Parse.User.requestEmailVerification(Parse.User.current().get("email"));
BUT NOTE that it will throw error if user is already verified.
Reference:
http://parseplatform.org/Parse-SDK-JS/api/3.4.1/Parse.User.html#.requestEmailVerification
To resend the verification email, as stated above, you have to modify then reset the user email address. To perform this operation in secure and efficient way, you can use the following cloud code function:
Parse.Cloud.define("resendVerificationEmail", async function(request, response) {
var originalEmail = request.params.email;
const User = Parse.Object.extend("User");
const query = new Parse.Query(User);
query.equalTo("email", originalEmail);
var userObject = await query.first({useMasterKey: true});
if(userObject !=null)
{
userObject.set("email", "tmp_email_prefix_"+originalEmail);
await userObject.save(null, {useMasterKey: true}).catch(error => {response.error(error);});
userObject.set("email", originalEmail);
await userObject.save(null, {useMasterKey: true}).catch(error => {response.error(error);});
response.success("Verification email is well resent to the user email");
}
});
After that, you just need to call the cloud code function from your client code. From Android client, you can use the following code (Kotlin):
fun resendVerificationEmail(email:String){
val progress = ProgressDialog(this)
progress.setMessage("Loading ...")
progress.show()
val params: HashMap<String, String> = HashMap<String,String>()
params.put("email", email)
ParseCloud.callFunctionInBackground("resendVerificationEmail", params,
FunctionCallback<Any> { response, exc ->
progress.dismiss()
if (exc == null) {
// The function executed, but still has to check the response
Toast.makeText(baseContext, "Verification email is well sent", Toast.LENGTH_SHORT)
.show()
} else {
// Something went wrong
Log.d(TAG, "$TAG: ---- exeception: "+exc.message)
Toast.makeText(
baseContext,
"Error encountered when resending verification email:"+exc.message,
Toast.LENGTH_LONG
).show()
}
})
}