Local notification isn't shown - javascript

I need to show a simple local notification, just to understand how does it work. Fro this purpose I wrote this code:
askPermissions = async () => {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
return finalStatus === 'granted';
};
sendNotificationImmediately = async () => {
const notificationId = await Notifications.presentLocalNotificationAsync({
title: 'This is header',
body: 'This is body',
});
console.log(notificationId);
};
And called this method in a such way:
componentDidMount() {
if (this.askPermissions()) {
console.log('Permission presents');
this.sendNotificationImmediately();
} else {
console.log('Denied');
}
}
To wrote this code I used this tutorial. But when I run the app notification isn't shown, but permission presents. So, what's the reason of the problem and how can I solve it?

You can try this,
askPermissions = async () => {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
} else if (finalStatus === 'granted') {
Notifications.presentLocalNotificationAsync({
title: 'This is header',
body: 'This is body',
});
}
componentDidMount() {
this.askPermissions();
}
Hope this helps.

Related

SQS messages are coming back to DLQ?

I have written the following script to move messages from DLQ to MainQ.
'use strict'
import { readFileSync } from "fs";
import {
DeleteMessageCommand,
SQSClient,
GetQueueUrlCommand,
SendMessageCommand,
ReceiveMessageCommand,
GetQueueAttributesCommand
} from '#aws-sdk/client-sqs';
const REGION = 'us-east-1';
const sqs = new SQSClient({ region: REGION });
async function getMessageCount(queueUrl) {
const params = { AttributeNames: ['ApproximateNumberOfMessages'], QueueUrl: queueUrl };
try {
const data = await sqs.send(new GetQueueAttributesCommand(params));
// console.log(data);
return data.Attributes.ApproximateNumberOfMessages;
} catch (err) {
console.error(err);
}
}
async function reprocessMessages(dlqQueue, mainQueue) {
try {
const response1 = await sqs.send(new GetQueueUrlCommand({ QueueName: dlqQueue }));
const response2 = await sqs.send(new GetQueueUrlCommand({ QueueName: mainQueue }));
const dlqQueueUrl = response1.QueueUrl;
const mainQueueUrl = response2.QueueUrl;
const messageCount = await getMessageCount(dlqQueueUrl);
console.log(`Message count ${messageCount}`);
const visibiltyTimeout = Math.ceil(messageCount / 100) * 2;
let count = 0;
while (count <= 50) {
count += await moveMessage(mainQueueUrl, dlqQueueUrl, 5);
}
console.log(`Moved ${count} messages`);
return "Completed";
} catch (err) {
console.error(err);
}
}
async function moveMessage(mainQueueUrl, dlqQueueUrl, visibiltyTimeout) {
try {
const receiveMessageParams = {
MaxNumberOfMessages: 9,
MessageAttributeNames: ['All'],
QueueUrl: dlqQueueUrl,
VisibilityTimeout: visibiltyTimeout,
WaitTimeSeconds: 1
};
const receiveData = await sqs.send(new ReceiveMessageCommand(receiveMessageParams));
// console.log(receiveData);
if (!receiveData.Messages) {
// console.log("finished");
return 0;
}
const messages = [];
receiveData.Messages.forEach(msg => {
messages.push({ id: msg.MessageId, msgAttributes: msg.MessageAttributes, body: msg.Body, receiptHandle: msg.ReceiptHandle });
});
const sendMsg = async ({ id, msgAttributes, body, _ }) => {
const sendMessageParams = {
MessageId: id,
MessageAttributes: msgAttributes,
MessageBody: body,
QueueUrl: mainQueueUrl
};
const sentData = await sqs.send(new SendMessageCommand(sendMessageParams));
// console.log("Success, message sent. MessageID: ", sentData.MessageId);
return 'Success';
};
const deleteMsg = async ({ id, receiptHandle }) => {
const deleteMessageParams = {
MessageId: id,
QueueUrl: dlqQueueUrl,
ReceiptHandle: receiptHandle
};
const deleteData = await sqs.send(new DeleteMessageCommand(deleteMessageParams));
// console.log("Message deleted", deleteData);
return 'Deleted';
};
const sent = await Promise.all(messages.map(sendMsg));
console.log(sent);
const deleted = await Promise.all(messages.map(deleteMsg));
console.log(deleted);
console.log(sent.length);
return sent.length;
// return 1;
} catch (err) {
console.log(err);
}
}
function main() {
const queues = readFileSync('queues.txt', 'utf8').split('\n');
queues.map(async elem => {
const [dlqQueue, mainQueue] = elem.split(' ');
console.log(`Moving messages from ${dlqQueue} to ${mainQueue}`);
const response = await reprocessMessages(dlqQueue, mainQueue);
console.log(response);
});
}
main()
This script moves the message from DLQ to MainQ and shows the new count of the DLQ decreased by the number of messages. However, when those messages in MainQ fail they again come back to DLQ thus keeping the count same as before reprocessing. But, after a while I see that the messages in DLQ increase by the same amount as the number of messages processed.
For instance for the below case I moved 54 messages and the screenshots for the queue counts are attached after each stage.

Why is my discord bot taking so long to research videos

Basically my bot is taking too long to send me the results for the video research he made on youtube. I do believe that the problem is in this for loop, but I'm not sure about it
for(var i = 0; i <= 4; i++){
//Search for video
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > (i + 1)) ? videoResult.videos[i] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
searchResults.push(video)
} else {
searchResults.push('No video results found');
}
}
This is the entire code to the play command:
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search');
const { User } = require('discord.js');
const { accessSync } = require('fs');
module.exports = {
name: 'play',
description: "Plays video from youtube on a earrape mode",
async execute(client, message, args){
const voiceChannel = message.member.voice.channel;
//Check if person is in voice chat
if(!voiceChannel) return message.channel.send('You need to be in a voice chat to execute this command');
//Check person permissions
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT' || 'SPEAK')) return message.channel.send('You dont have the permission to execute this command');
//Check if message has arguments
if(!args.length) return message.channel.send('You need to send some keywords')
var searchResults = [];
//Bot join VC
const connection = await voiceChannel.join();
for(var i = 0; i <= 4; i++){
//Search for video
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > (i + 1)) ? videoResult.videos[i] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
searchResults.push(video)
} else {
searchResults.push('No video results found');
}
}
let filter = m => m.author.id === message.author.id
var whichVideo = null;
await message.channel.send({embed: {
color: 3447003,
title: "Select your music:",
fields: [
{
name: `1.`,
value: `***[${searchResults[0].title}](${searchResults[0].url})***`
},
{
name: `2.`,
value: `***[${searchResults[1].title}](${searchResults[1].url})***`
},
{
name: `3.`,
value: `***[${searchResults[2].title}](${searchResults[2].url})***`
},
{
name: `4.`,
value: `***[${searchResults[3].title}](${searchResults[3].url})***`
},
{
name: `5.`,
value: `***[${searchResults[4].title}](${searchResults[4].url})***`
}
],
footer: {
icon_url: client.user.avatarURL,
text: "Timeout in 30 seconds"
}
}
})
.then(() => {
message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
.then(message => {
message = message.first();
if (message.content == '1' || message.content == '2' || message.content == '3' || message.content == '4' || message.content == '5'){
whichVideo = parseInt(message.content) - 1;
message.channel.send(`:musical_note: added ~ ***${searchResults[whichVideo].title}*** ~ to the queue`);
try{
message.channel.send(`:loud_sound: :notes: Now Playing: ~ ***${searchResults[whichVideo].title}*** ~`);
//Get only the audio of the video
const stream = ytdl(searchResults[whichVideo].url, {filter: 'audioonly'});
//Bot joins plays music
connection.play(stream, {seek: 0, volume: 1})
//Leave when music ends
.on('finish', () =>{
voiceChannel.leave();
});
} catch (e){
console.log(e);
voiceChannel.leave();
}
} else {
message.channel.send('');
}
})
.catch(collected => {
message.channel.send('');
});
})
}
}
I am not 100% sure, but I think the issue is in this part:
for(var i = 0; i <= 4; i++){
//Search for video
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > (i + 1)) ? videoResult.videos[i] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
searchResults.push(video)
} else {
searchResults.push('No video results found');
}
}
You are launching 4 searches (?)
Try using this library instead:
var search = require('youtube-search');
var opts = {
maxResults: 4,
key: 'Your YouTube API V3 key'
};
search('video title', opts, function(err, results) {
if(err) return console.log(err);
console.dir(results);
});
This way you can search for 4 results at the same time, this should speed up your process.

Bot doesn't edit role permissions for each channel

I'm trying to make an anti-spam and when the bot is supposed to edit the muted role's permission for each channel nothing happens.
So first I create the role
const mute_role = message.guild.roles.cache.find(r => r.name == "Muted");
if (!mute_role) {
try {
mute_role = await message.guild.roles.create({
data: {
name: "Muted",
color: "#000000",
permissions: []
}
})
Then i edit the role's permissions on all guild's channels
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(mute_role,
{
SEND_MESSAGES: false,
ADD_REACTIONS: false,
}
);
});
} catch (e) {
console.log(e.stack);
}
}
And after doing this it should continue to the rest of the code but it seems to skip that part because it continues to the anti-spam and adds the role if spam is triggered
Here is the full code for the anti-spam
bot.on('message', async message => {
if (message.author.bot) return;
const mute_role = message.guild.roles.cache.find(r => r.name == "Muted");
if (!mute_role) {
try {
mute_role = await message.guild.roles.create({
data: {
name: "Muted",
color: "#000000",
permissions: []
}
})
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(mute_role,
{
SEND_MESSAGES: false,
ADD_REACTIONS: false,
}
);
});
} catch (e) {
console.log(e.stack);
}
}
if (usersMap.has(message.author.id)) {
const userData = usersMap.get(message.author.id);
const { lastMessage, timer } = userData;
const difference = message.createdTimestamp - lastMessage.createdTimestamp;
let msgCount = userData.msgCount;
console.log(difference);
if (difference > DIFF) {
clearTimeout(timer);
console.log('Cleared timeout');
userData.msgCount = 1;
userData.lastMessage = message;
userData.timer = setTimeout(() => {
usersMap.delete(message.author.id);
console.log('Removed from RESET');
}, TIME);
usersMap.set(message.author.id, userData);
}
else {
msgCount++;
console.log(msgCount)
if (parseInt(msgCount) === LIMIT) {
message.member.roles.add(mute_role);
message.channel.send(`${message.author} has been muted for spamming`);
setTimeout(() => {
message.member.roles.remove(mute_role);
message.channel.send(`${message.author} has been unmuted`);
}, TIME);
}
else {
userData.msgCount = msgCount;
usersMap.set(message.author.id, userData);
}
}
}
else {
let fn = setTimeout(() => {
usersMap.delete(message.author.id);
console.log('Removed from map');
}, TIME);
usersMap.set(message.author.id, {
msgCount: 1,
lastMessage: message,
timer: fn
})
}
})
Okay so I just found out why it was not working
Instead of using
const mute_role = message.guild.roles.cache.find(r => r.name == "Muted");
I just had to use
let mute_role = message.guild.roles.cache.find(r => r.name == "Muted");
Now it works and overwrites the channels permissions

How could I save the new server name with an guildUpdate with mongoose? | discord.js

How can I replace the oldguild(old server's name) to a new one when server updated? I tried with GuildID(discord server id) and everything but nothing seem to work. When the bot saves it, then looks like this in the MongoDB Compass: Screenshot, and for example this is how it looks like in MongoDB Compass normally: Old name server, but I want it look like this New name server.
This is my code.
client.on("guildUpdate", (oldguild, newguild) => {
var name = [oldguild.name, newguild.name];
if(name[0] == null) {
name[0] = oldguild.name
}
if(name[1] == null) {
name[1] = oldguild.name
}
if(oldguild.name !== newguild.name)
{
async function guildUpdated() {
const servername = new setprefixModel ({
_id: mdb.Types.ObjectId(),
GuildID: setprefixModel.GuildId,
Guild: oldguild.name,
Prefix: setprefixModel.Prefix
});
const reqservername = await setprefixModel.findOne({ Guild: oldguild.name });
if(!reqservername) {
return await servername.save();
}
else {
const updatedDocument = await setprefixModel.findOneAndUpdate(
{ Guild: oldguild.name },
{ Guild: newguild.name },
{ new: true }
);
updatedDocument;
}
}
guildUpdated();
}
})
client.on("guildUpdate", (oldguild, newguild) => {
var name = [oldguild.name, newguild.name];
if(name[0] == null) {
name[0] = oldguild.name
}
if(name[1] == null) {
name[1] = oldguild.name
}
if(oldguild.name !== newguild.name)
{
async function guildUpdated() {
const servername = new setprefixModel ({
_id: mdb.Types.ObjectId(),
GuildID: String,
Guild: oldguild.name,
Prefix: String
});
const reqservername = await setprefixModel.findOne({ Guild: oldguild.name });
if(!reqservername) {
return await servername.save();
}
else {
const updatedDocument = await setprefixModel.findOneAndUpdate(
{ Guild: oldguild.name },
{ Guild: newguild.name },
{ new: true }
);
updatedDocument;
}
}
guildUpdated();
}
})
Changed at const servername.

Discord.js YouTube Search and Play

I am trying to make discord bot that will play some music but I can't manage to make search command correctly ( Now I need to type command .f press enter and then put that what I want to search and I want it to just .f [what i want to search]) but doesn't know how to. I tried many guides but still nothing, also I would like to have that after searching and choosin what to I meant to play bot automatically join and play it (I made it buut in weird way and I know there is easier way but I am dumb for it.
TL;DR: Search command that will search and play with ".f [what to search]".
Whole code if it wil help:
const { Client } = require("discord.js");
const config = require('./config.json')
const Discord = require("discord.js");
const ytdl = require('ytdl-core');
const search = require("youtube-search")
const opts = {
maxResults: 25,
key: config.YOUTUBE_API,
type: 'video'
}
const queue = new Map();
const client = new Client({
disableEveryone: true
});
client.on("ready", () => {
console.log(`ŻYJE I JAM JEST ${client.user.username} `);
});
client.on("message", async message => {
console.log(`${message.author.username} mówi: ${message.content}`)
});
client.on("message", async message => {
if (!message.content.startsWith('.')) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`.p`, '.play', '.pla', '.pl')) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`.s`, '.skip', '.sk', '.ski')) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`.l`, '.leave', '.le', '.lea', '.leav')) {
stop(message, serverQueue);
return;
};
if (message.content.toLowerCase() === '.f') {
let embed = new Discord.MessageEmbed()
.setColor("#00FE0C")
.setDescription("Czego szukasz? Opowiedz mi dokładniej.")
.setTitle("Wyszukiwarka")
.setThumbnail('https://i.imgur.com/vs6ulWc.gif')
let embedMsg = await message.channel.send(embed);
let filter = m => m.author.id === message.author.id;
let query = await message.channel.awaitMessages(filter, { max: 1});
let results = await search(query.first().content, opts).catch(err => console.log(err))
if(results) {
let youtubeResults = results.results;
let i =0;
let titles = youtubeResults.map(result => {
i++;
return i + ") " + result.title;
});
console.log(titles);
message.channel.send({
embed : {
title: "Wybieraj mordo",
description: titles.join("\n")
}
}).catch(err => console.log(err));
filter = m => (m.author.id === message.author.id) && m.content >= 1 && m.content <= youtubeResults.length;
let collected = await message.channel.awaitMessages(filter, { max: 1 });
let selected = youtubeResults[collected.first().content - 1];
embed = new Discord.MessageEmbed()
.setColor("#00FE0C")
.setTitle(`${selected.title}`)
.setURL(`${selected.link}`)
.setDescription(`${selected.description}`)
.setThumbnail(`${selected.thumbnails.default.url}`);
message.channel.send(embed)
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
await message.channel.send(`.p ${selected.link}`).then(d_msg => { d_msg.delete({ timeout: 1500 })})
}
};
};
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"No wbij Mordunio na kanał najpierw!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"Dawaj klucze do kantorka to wbije!"
);
}
const songInfo = await ytdl.getInfo(args[1]);
const song = {
title: songInfo.title,
url: songInfo.video_url
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
return message.channel.send(`**${song.title}** został do kolejeczki dodany Byku!`);
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Nie zatrzymasz mnie! Ciebie tu nie ma!"
);
if (!serverQueue)
return message.channel.send("A co miałabym pominąć");
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Musisz tu byyyyć byyyyyku!!"
);
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song, message) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id)
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(song.url))
.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Gram: **${song.title}**`);
};
client.login(config.TOKEN);

Categories