Receive commands from a specific channel - mongodb

How can I make the bot receive commands from specific channels, and if there is no channel, it is received from all channels and it is connected to mongoDB?
I can do the receiving command from a specific channel using channel ID, but I want via the command:
!setChannel #ID_CHANNEL OR mention
I tried these codes
let channel = message.mentions.channels.first()
if(!args[0]) return message.channel.send('Please Mention Channel');
if(!channel) return message.channel.send('Please Mention Vaild Channel');
/*-----------------------------in mongedb add Guild id + channel id------------------------------
in quick.db it is like this -->
db.set("commands_channel_"+ message.guild.id + channel.id, true)*/
message.channel.send(`Commands Channel: ${channel}`);
let CommandsChannel = db.get("commands_channel_"+ message.guild.id + channel.id)
if(!CommandsChannel) return
//-------------------------------//
if(CommandsChannel = true) {
// else command code //
}

wrong with the code
(node:4456) UnhandledPromiseRejectionWarning: Error: `commands_channel_708596988995829762709436321805893753` is an invalid option.
at Mongoose.set (/rbd/pnpm-volume/34e95e32-ea3c-4e44-8fb4-6f803dcbc088/node_modules/.registry.npmjs.org/mongoose/5.10.15/node_modules/mongoose/lib/index.js:179:48)
at Object.run (/app/commands/admin/setchannel.js:19:10)
at module.exports (/app/events/message.js:152:17)
at processTicksAndRejections (internal/process/task_queues.js:88:5)
(node:4456) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Related

How to deal with HTTP connection timed out crashes in Flutter

So I have a method that uses the Flutter HTTP library and is responsible for calling HTTP requests to the server with code like this:
Future<List<DataModel>> fetchData() async {
try {
var url = Uri.parse('${baseUrlParse}myapipath');
var request = await http.get(url);
var data = jsonDecode(request.body);
return data;
} catch (e) {
print('Catch ${e}');
rethrow;
}
}
This code runs fine and has no issues.
It got to the point where when I have no internet connection or server connection fails, the app freezes, and an error file appears (if you're debugging in VS Code), called http_impl.dart, and the error snippet goes something like this:
onError: (error) {
// When there is a timeout, there is a race in which the connectionTask
// Future won't be completed with an error before the socketFuture here
// is completed with a TimeoutException by the onTimeout callback above.
// In this case, propagate a SocketException as specified by the
// HttpClient.connectionTimeout docs.
if (error is TimeoutException) {
assert(connectionTimeout != null);
_connecting--;
_socketTasks.remove(task);
task.cancel();
throw SocketException(
"HTTP connection timed out after $connectionTimeout, "
"host: $host, port: $port");
}
_socketTasks.remove(task);
_checkPending();
throw error;
});
I have tried to implement from this source and this, but when I make a request but have no connection, this error still occurs.
How to deal with this problem?
What I want is, if there is a problem with HTTP either there is no connection, or it fails to contact the server, then I can make a notification..
Is there something wrong with my code?
Please help, thank you
You re throw the exception in your code,
You need to catch exception where you call to this method like this.
try {
await fetchData();
} catch (e) {
// TODO: handle exception
}
You can stop VS Code catching unhandled exceptions from this way
https://superuser.com/a/1609472

ERR_UNHANDLED_REJECTION

node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 403".] {
code: 'ERR_UNHANDLED_REJECTION'
}

(node:2072) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined Discord js | Mongoose | MongoDB

I am trying to make a simple welcome message on discord js with an event handler. It would work if I do it on the main file, but it does not work when I try it here. Code Below:
const profileModel = require('../../database/models/profileSchema');
let WelcomeSchema = require(`../../database/models/welcomeSchema`)
const Discord = require(`discord.js`)
const mongoose = require(`mongoose`)
module.exports = (client, member, GuildMember) => {
WelcomeSchema.findOne({ guildID: member.guild.id}, async (err, data, user) => {
console.log(member.guild.id)
if(!data) return;
const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
channel.send(`Welcome ${member}, ${data.WelcomeMsg}`)
})
}
Below Is My Event Handler (keep in mind the code above had the file name of, guildMemberAdd)
fs.readdirSync(`./events`).forEach(dirs => {
const events = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith(`.js`))
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${dirs}/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
}
});
Below Is The Full Error
(node:2072) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at E:\Software\Github Repository shit\EA-BOT\events\Other\guildMemberAdd.js:15:13
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:2072) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2072) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Below Is Line 15 (where the error was at)
(line 14) const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
(line 15) channel.send(`Welcome ${member}, ${data.WelcomeMsg}`)
The error is self-explanatory. Cannot read property 'send' of undefined you are attempting to invoke .send() method of something undefined - meaning channel is undefined. If we take a look at line 14, the logical explanation is that there is no channel, for which
x.id === `${data.WelcomeChannel}`
is true.
The line if (!data) return; for your purposes is not specific enough. It appears data exists, but either data.WelcomeChannel does not, or IDs don't much.
Try to use line if (!data.WelcomeChannel) return; and see if this exits your code. Then double-check data.WelcomeChannel is a correct channel id (and if it's actually an id, not channel object).
Instead of using this:
const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
to get your Discord.channel, try doing this:
const channel = await client.channels.cache.get(data.WelcomeChannel)
Note: I can't test the fix myself because I'm currently in school, but this may fix your issue.

Protractor isDisplayed has no .catch, leading to UnhandledPromiseRejectionWarning

Then "Thenable" returned by ElementFinder.isDisplayed has no catch.
let promise = element(by.css('donut')).isDisplayed();
console.log(promise.then); // => (fn, errorFn) => ...
console.log(promise.catch); // => undefined
If I use try-catch in an async function:
try {
await e.isDisplayed();
} catch (e) {
console.log(e);
}
I do catch the exception, but then I get an UnhandledPromiseRejectionWarning from Node, with a deprecation warning:
(node:12296) UnhandledPromiseRejectionWarning: NoSuchElementError: No element found using locator: By(css selector, donut)
...
(node:12296) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
How can handle that promise rejection? I can't use .catch on the value returned by isDisplayed, and apparently using a try-catch in an async function isn't enough.
NOTE: I'm aware that I can use e.isPresent() to find out in advance if e.isDisplayed() will throw, but the question is not how to avoid this error, but why it cannot be caught.

flutterBlue.connect(device, timeout: const Duration(seconds: 10),).listen(null); in flutter

sorry,I am a beginner and my English is very bad
i have a trouble in Flutter.
i reference https://pub.dartlang.org/packages/flutter_blue
I want to use flutter to communicate with the ear thermometer device.
when i reopen bluetooth and it can work,but I reopen app and excute second it show error.
i guess bluetooth gatt cahce is causing a error.
how can i solve it?
my code
deviceConnection = flutterBlue.scan(timeout: const Duration(seconds: 5),).listen((scanResult) async {
device = scanResult.device;
deviceConnection2 = await flutterBlue.connect(device, timeout: const Duration(seconds: 10),).listen(null);//this line error is error 1
deviceStateSubscription = device.onStateChanged().listen((s) async {
await device.discoverServices().then((s) async {//this is error 2
.........
}
}
}
it show these error
error 1
Dart Error: Unhandled exception:
PlatformException(already_connected, connection with device already exists, null)
error 2
Dart Error: Unhandled exception:
PlatformException(get_services_error, no instance of BluetoothGatt, have you connected first?, null)
Error 1
Dart Error: Unhandled exception: PlatformException(already_connected, connection with device already exists, null)
Since the app detected that a bluetooth device is already connected, one workaround is check for any connected device disconnect it. You can create a function that does this like the one in this GitHub thread:
What you can do here is that you check for any connected devices and
then disconnect them. I have written a function that does just that,
here it is:
checkConnectedDevices() async{
connectedDevices = await flutterBlue.connectedDevices.whenComplete((){
print(connectedDevices);
for(int i = 0; i < connectedDevices.length; i++){
connectedDevices[i].disconnect();
}
});
}
Error 2
Dart Error: Unhandled exception: PlatformException(get_services_error, no instance of BluetoothGatt, have you connected first?, null)
Since there is an error connecting to the device, you will not be able to call the discoverServices(). Because you need to be connected to a device before you can call this function. Check the following GitHub discussions related to this error:
connected ' discoverServices ' is't get #426
discoverServices is broken #535