bot responds to specific channel discord.js - command

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');
}
});

Related

Get twilio call status at client side javascript

I am working twilio client JavaScript. I successfully placed a voice call to specific number but i want to know whether or not call is cancelled, unanswered and other status
if(Twilio) {
Twilio.Device.setup(token);
Twilio.Device.ready((device:any) => {
console.log('Twilio.Device Ready!');
});
Twilio.Device.error((error:any) => {
console.log('Twilio.Device Error: ' + error.message);
// setShowInCallMenu(!showInCallMenu);
setIsCallConnected(false);
});
Twilio.Device.connect((conn:any) => {
console.log('Successfully established call!');
setIsCallConnected(true);
setStartTimestamp(moment());
handleRecording(true);
});
Twilio.Device.disconnect((conn:any) => {
console.log('Call ended.');
setIsCallConnected(false);
handleRecording(false);
//toggleCaller()
onNativeCallback(
{
'code':4001,
'message':'Call Ended'
}
);
});
}
webhook doesn't solve this problem all. I need the status of the call. another way would be make a separate call to callSid endpoint and get information about call but in that case it wont gave details like whether call is not answered or cancelled

SignalR sending notification to a specific client it's not working

When sending a notification with SignalR to a specific user it's not working.
I'm storing connection IDs in a table and when the notification should be sent I get the connection ID for the receiver from the DB but he doesn't get anything. What is wrong with my code?
// get the connectionId of the receiver
if (_db.UserConnectionid != null)
{
var userConn = await _db.UserConnectionid.Where(x => x.UserId == receiver).Select(x => x.ConnectionId).FirstOrDefaultAsync();
//if the receiver is online
if (userConn != null)
{
await Clients.Client(userConn).SendAsync("RecieveMessage", message);
}
}
I'm storing connection IDs in a table and when the notification should be sent I get the connection ID for the receiver from the DB but he doesn't get anything. What is wrong with my code?
Firstly, please note that a user could have more than one connection id, to troubleshoot the issue, you can try to debug the code and make sure the connection id you retrieved from db is same as the one of current connecting user.
Besides, to send message to a specific user, you can try to get all stored connection id(s) of a specific user/receiver, then send message by specify connectionIds, like below.
var ConnectionIds = _db.UserConnectionid.Where(x => x.UserId == receiver).Select(x => x.ConnectionId).ToList();
if (ConnectionIds.Count > 0)
{
await Clients.Clients(ConnectionIds).SendAsync("RecieveMessage", message);
}
If you are using default user claims mechanism for authorization, you probably can take a look into this mechanism:
https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0#use-claims-to-customize-identity-handling
If you will provide IUserIdProvider service or map userId to ClaimTypes.NameIdentifier claim, you will be able to filter your SignalR clients by stringified user id using this method:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.signalr.ihubclients-1.user?view=aspnetcore-5.0#Microsoft_AspNetCore_SignalR_IHubClients_1_User_System_String_
Like this:
await Clients.User(receiver.ToString()).SendAsync("RecieveMessage", message);
As recommended in the article, don’t store Id’s.
https://consultwithgriff.com/signalr-connection-ids/

How can I catch errors in my firebase function when setting a document fails?

I have a firebase cloud function to create a user document with user data whenever a user registers. How would I return an error when the set() fails? Since this is not an http request (an I don't want to use an http request in this case) I have no response. So how would I catch errors?
export const onUserCreated = functions.region('europe-west1').auth.user().onCreate(async user => {
const privateUserData = {
phoneNumber: user.phoneNumber
}
const publicUserData = {
name: 'Nameless'
}
try
{
await firestore.doc('users').collection('private').doc('data').set(privateUserData);
}catch(error)
{
//What do I put here?
}
try
{
await firestore.doc('users').collection('public').doc('data').set(publicUserData);
}catch(error)
{
//What do I put here?
}
});
You can't "return" an error, since the client doesn't even "know" about this function running, there is nobody to respond to.
You can make a registration collection, and in your function make a document there for the current user (using the uid as the document id). In that document, you can put any information you'd like your user to know (status, errors, etc).
So your clients would have to add a listener to this document to learn about their registration.
In your particular code, I think the error is in doc('users'). I guess you meant doc('users/'+user.uid).
Your catch -block will receive errors that occur on your set -call:
try {
await firestore.doc('users').collection('public').doc('data').set(publicUserData);
} catch (error) {
// here you have the error info.
}

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

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

How to stop the user from entering the duplicate record on default save

I have a custom module where there is an email field. Now i want to stop the user if the email is already in the database.
I want to stop the user on save button and show the error. Like when a required field goes empty.
I tried to get some help but was not able to understand it.
Note: I realized after posting this that you are using suitecrm which this answer will not be applicable toward but I will leave it in case anyone using Sugar has this question.
There are a couple of ways to accomplish this so I'll do my best to walk through them in the order I would recommend. This would apply if you are using a version of Sugar post 7.0.0.
1) The first route is to manually create an email address relationship. This approach would use the out of box features which will ensure your system only keeps track of a single email address. If that would work for your needs, you can review this cookbook article and let me know if you have any questions:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_the_Email_Field_to_a_Bean/
2) The second approach, where you are using a custom field, is to use field validation. Documentation on field validation can be found here:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/index.html
The code example I would focus on is:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/#Method_1_Extending_the_RecordView_and_CreateView_Controllers
For your example, I would imagine you would do something like this:
Create a language key for your error message:
./custom/Extension/application/Ext/Language/en_us.error_email_exists_message.php
<?php
$app_strings['ERROR_EMAIL_EXISTS_MESSAGE'] = 'This email already exists.';
Create a custom controller for the record creation (you may also want to do this in your record.js):
./custom/modules//clients/base/views/create/create.js
({
extendsFrom: 'RecordView',
initialize: function (options) {
this._super('initialize', [options]);
//reference your language key here
app.error.errorName2Keys['email_exists'] = 'ERROR_EMAIL_EXISTS_MESSAGE';
//add validation tasks
this.model.addValidationTask('check_email', _.bind(this._doValidateEmail, this));
},
_doValidateEmail: function(fields, errors, callback) {
var emailAddress = this.model.get('your_email_field');
//this may take some time so lets give the user an alert message
app.alert.show('email-check', {
level: 'process',
title: 'Checking for existing email address...'
});
//make an api call to a custom (or stock) endpoint of your choosing to see if the email exists
app.api.call('read', app.api.buildURL("your_custom_endpoint/"+emailAddress), {}, {
success: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//analyze your response here
if (response == '<email exists>') {
errors['your_email_field'] = errors['your_email_field'] || {};
errors['your_email_field'].email_exists = true;
}
callback(null, fields, errors);
}, this),
error: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//throw an error alert
app.alert.show('email-check-error', {
level: 'error',
messages: "There was an error!",
autoClose: false
});
callback(null, fields, errors);
})
});
},
})
Obviously, this isn't a fully working example but it should get you most of the way there. Hope this helps!