Purge command discord.js [duplicate] - discord.js

This question already has answers here:
How do you bulk delete messages excluding the pinned messages?
(2 answers)
Closed 1 year ago.
I am trying to create a purge command and it works, but I want the bot to not delete the pinned messages when I use the command. What do I include in the code to prevent it from delting the pinned messages? Currently this is the code -
if(message.content.toLowerCase().startsWith("s!purge")) {
let arg = message.content.split(" ")
message.delete()
let clear = arg[1];
if(!clear) return message.channel.send(`:x: | \`Incorrect usage of command you need to provide an amount of messages to Clear.\`
**Example:** \`s!purge 50\` `)
if(isNaN(clear)) return message.channel.send(":x: | ``Please Put a Valid Number to Clear messages.``")
if(clear > 100) return message.channel.send(":x: | ``I can't Clear more than 100 messages.``")
if(clear < 1) return message.channel.send(":x: | ``You cannot Clear less than 1 message.``")
message.channel.bulkDelete(clear)
message.channel.send(`:white_check_mark: | \`Succesfully cleared ${clear} messages! \` `)
.then(message =>
setTimeout(()=> message.delete(), 2000)
)
}

There is a method to check if a message is pinned or not. Which is message.pinned.
And do
if (!message.pinned) {
// delete the message
}
I hope that solves your issue!
or else you can do const nonPinnedMsgs = await message.channel.messages.fetch({ limit: thePurgeAmount }).filter(m => m.pinned) and bulk delete (nonPinnedMsgs)

Related

unexpected token in mssql/tedious

I want to use mssql in a vue-electron project.
I installed mssql with npm.
When i want to run the app, i get the following error:
ERROR Failed to compile with 2 errors
error in ./node_modules/mssql/lib/tedious/connection-pool.js
Module parse failed: Unexpected token (39:63)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| cfg.options.database = cfg.options.database || this.config.database
| cfg.options.port = cfg.options.port || this.config.port
> cfg.options.connectTimeout = cfg.options.connectTimeout ?? this.config.connectionTimeout ?? this.config.timeout ?? 15000
| cfg.options.requestTimeout = cfg.options.requestTimeout ?? this.config.requestTimeout ?? this.config.timeout ?? 15000
| cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4'
# ./node_modules/mssql/lib/tedious/index.js 4:23-51
# ./node_modules/mssql/index.js
# ./src/modules/db.js
# ./src/background.js
# multi ./src/background.js
error in ./node_modules/mssql/lib/tedious/request.js
Module parse failed: Unexpected token (446:15)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const req = new tds.Request(command, err => {
| // tedious v15 has started using AggregateErrors to wrap multiple errors into single error objects
> (err?.errors ? err.errors : [err]).forEach((e, i, { length }) => {
| // to make sure we handle no-sql errors as well
| if (e && (!errors.length || (errors.length && errors.length >= length && e.message !== errors[errors.length - length + i].message))) {
# ./node_modules/mssql/lib/tedious/index.js 6:16-36
# ./node_modules/mssql/index.js
# ./src/modules/db.js
# ./src/background.js
# multi ./src/background.js
Can someone please help me?

How do I delete only 10 messages if the user provided 20 messages (older than 14 days) for bulk deleting in discord.js

I'm new in Discord.js I've recently made a "purge" command and it looks like this-
if (message.content.toLowerCase().startsWith(prefix + "purge") || message.content.toLowerCase().startsWith(prefix + "clear")) {
const args = message.content.split(' ').slice(1); // All arguments behind the command name with the prefix
const amount = args.join(' '); // Amount of messages which should be deleted
if (message.channel.type === "DM") return message.reply('Cannot run command inside DMs.')
if (!message.member.hasPermission('MANAGE_MESSAGES') || !message.member.hasPermission('ADMINISTRATOR')) return message.channel.reply('You do not have enough permissions to run this command')
if (!message.guild.me.hasPermission('MANAGE_MESSAGES') || !message.guild.me.hasPermission('ADMINISTRATOR')) return message.reply('I do not have permission to delete messages.')
if (!amount) return message.reply('You haven\'t given an amount of messages which should be deleted!'); // Checks if the `amount` parameter is given
if (isNaN(amount)) return message.reply('The amount parameter isn`t a number!'); // Checks if the `amount` parameter is a number. If not, the command throws an error
if (amount > 99) return message.reply('You can`t delete more than 99 messages at once!'); // Checks if the `amount` integer is bigger than 100
if (amount < 1) return message.reply('You have to delete at least 1 message!'); // Checks if the `amount` integer is smaller than 1
message.channel.messages.fetch({
limit: amount
}).then(messages => { // Fetches the messages
message.channel.bulkDelete(messages) // Bulk deletes all messages that have been fetched and are not older than 14 days (due to the Discord API)
message.channel.send(`Deleted ${amount} messages. Messages purged by ${message.author.username}`)
});
}
}
So the thing is, when I tested my bot in an old server with older messages, there was 23 new messages and 44 old messages. I tried to delete 50 messages. All it did was log the error in the console and send a message that 50 messages was deleted. It didn't really delete 50 messages but it sent a message it did delete. Is it possible to delete only the maximum number of messages that can be deleted and then send a message of how many messages are actually deleted, it'll be helpful. I'll tell an example- I want to delete 50 messages but 10 are under 14 days and the rest are over 14 days. The bot will delete 10 messages (the maximum it can delete just like Carl bot does.)
To delete number message you just need to provide number message into .bulkDelete method. And you need to wait until delete is complete with .then instead send it immediately after you delete like provide code
Example code
if (message.content.toLowerCase().startsWith(prefix + "purge") || message.content.toLowerCase().startsWith(prefix + "clear")) {
const args = message.content.split(' ').slice(1); // All arguments behind the command name with the prefix
const amount = args.join(' '); // Amount of messages which should be deleted
if (message.channel.type === "DM") return message.reply('Cannot run command inside DMs.')
if (!message.member.hasPermission('MANAGE_MESSAGES') || !message.member.hasPermission('ADMINISTRATOR')) return message.channel.reply('You do not have enough permissions to run this command')
if (!message.guild.me.hasPermission('MANAGE_MESSAGES') || !message.guild.me.hasPermission('ADMINISTRATOR')) return message.reply('I do not have permission to delete messages.')
if (!amount) return message.reply('You haven\'t given an amount of messages which should be deleted!'); // Checks if the `amount` parameter is given
if (isNaN(amount)) return message.reply('The amount parameter isn`t a number!'); // Checks if the `amount` parameter is a number. If not, the command throws an error
if (amount > 99) return message.reply('You can`t delete more than 99 messages at once!'); // Checks if the `amount` integer is bigger than 100
if (amount < 1) return message.reply('You have to delete at least 1 message!'); // Checks if the `amount` integer is smaller than 1
message.channel.bulkDelete(amount).then(messages => { // Fetches the messages
message.channel.send(`Deleted ${messages.size} messages. Messages purged by ${message.author.username}`)
});
}
There is a filterOld parameter in TextChannel.bulkDelete(). Here is how you implement it:
<TextChannel>.bulkDelete(100, true);
//<TextChannel> just means instance of TextChannel, like message.channel

How to have discord.py bot look for a message from a specific user recently?

I have a bot in writing in python and I want to incorporate a number game into the bot. The game code is below. (nl is a variable to say os.linesep)
secret_number = random.randint(0, 100)
guess_count = 0
guess_limit = 5
print(f'Welcome to the number guessing game! The range is 0 - 100 and you have 5 attempts to guess the correct number.')
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess > secret_number:
print('Too High.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess < secret_number:
print('Too Low.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess == secret_number:
print("That's correct, you won.")
break
else:
print("Sorry, you failed.")
print(f'The correct number was {secret_number}.')
So I want to be able to use that in the discord messaging system. My issue is that I need the bot to scan the most recent messages for a number from that specific user that initiated the game. How could I do so?
To simplify my question how can I say this:
if message from same message.author = int():
guess = that^
The solution here would be to wait_for another message from that user. You can do this with:
msg = await client.wait_for('message', check=message.author == PREVIOUS_SAVED_MSG_AUTHOR_AS_VARIABLE, timeout=TIMEOUT)
# You don't really need a timeout but you can add one if you want
# (then you'd need a except asyncio.TimeoutError)
if msg.content == int():
guess = msg
else:
...

unable to extra/list all event log on watson assistant wrokspace

Please help I was trying to call watson assistant endpoint
https://gateway.watsonplatform.net/assistant/api/v1/workspaces/myworkspace/logs?version=2018-09-20 to get all the list of events
and filter by date range using this params
var param =
{ workspace_id: '{myworkspace}',
page_limit: 100000,
filter: 'response_timestamp%3C2018-17-12,response_timestamp%3E2019-01-01'}
apparently I got any empty response below.
{
"logs": [],
"pagination": {}
}
Couple of things to check.
1. You have 2018-17-12 which is a metric date. This translates to "12th day of the 17th month of 2018".
2. Assuming the date should be a valid one, your search says "Documents that are Before 17th Dec 2018 and after 1st Jan 2019". Which would return no documents.
3. Logs are only generated when you call the message() method through the API. So check your logging page in the tooling to see if you even have logs.
4. If you have a lite account logs are only stored for 7 days and then deleted. To keep logs longer you need to upgrade to a standard account.
Although not directly related to your issue, be aware that page_limit has an upper hard coded limit (IIRC 200-300?). So you may ask for 100,000 records, but it won't give it to you.
This is sample python code (unsupported) that is using pagination to read the logs:
from watson_developer_cloud import AssistantV1
username = '...'
password = '...'
workspace_id = '....'
url = '...'
version = '2018-09-20'
c = AssistantV1(url=url, version=version, username=username, password=password)
totalpages = 999
pagelimit = 200
logs = []
page_count = 1
cursor = None
count = 0
x = { 'pagination': 'DUMMY' }
while x['pagination']:
if page_count > totalpages:
break
print('Reading page {}. '.format(page_count), end='')
x = c.list_logs(workspace_id=workspace_id,cursor=cursor,page_limit=pagelimit)
if x is None: break
print('Status: {}'.format(x.get_status_code()))
x = x.get_result()
logs.append(x['logs'])
count = count + len(x['logs'])
page_count = page_count + 1
if 'pagination' in x and 'next_url' in x['pagination']:
p = x['pagination']['next_url']
u = urlparse(p)
query = parse_qs(u.query)
cursor = query['cursor'][0]
Your logs object should contain the logs.
I believe the limit is 500, and then we return a pagination URL so you can get the next 500. I dont think this is the issue but once you start getting logs back its good to know

How can i get the logs of past months in postgres DB .

Issue :
Someone has added a junk column in one of my table.I want to figure it out from the logs as when and from where this activity has been performed.
Please Help regarding this issue.
Make sure enable logging in postgresql.conf
1.log_destination = 'stderr' #log_destination = 'stderr,csvlog,syslog'
2.logging_collector = on #need restart
3.log_directory = 'pg_log'
4.log_file_name = 'postgresql-%Y-%m-%d_%H%M%S.log'
5.log_rotation_age = 1d
6.log_rotation_size = 10MB
7.log_min_error_statement = error
8.log_min_duration_statement = 5000 # -1 = disable ; 0 = ALL ; 5000 = 5sec
9.log_line_prefix = '|%m|%r|%d|%u|%e|'
10.log_statment = 'ddl' # 'none' | 'ddl' | 'mod' | 'all'
#prefer 'ddl' because the log output will be 'ddl' and 'query min duration'
If you don't enable it, make sure enable it now.
if you don't have log the last attempt is pg_xlogdump your xlog file under pg_xlog and look for DDL

Resources