How to make "this command cannot found" discord.js - discord.js

I'm a bot developer and I own a music bot. I want to make this: how to make this command cannot found discord.js (I mean if someonee enter a command like m!pla then bot will say "U mean this? m!play")

You can use the npm package meant. It uses the Levenshtein Difference algorithm to find the most likely match given a string and an array of strings to compare it to.
const meant = require('meant');
const result = meant('foa', ['foo', 'bar', 'baz']) // => [ 'foo' ]
All you need is an array of your command names, and the command the user tried to execute.
const meant = require('meant');
const [result] = meant(commandName, commandNames);
// Did you mean ${result}?

Related

making discord bot command to store message content (python)

So this is my first time coding an actual project that isn't a small coding task. I've got a bot that runs and responds to a message if it says "hello". I've read the API documentation up and down and really only have a vague understanding of it and I'm not sure how to implement it.
My question right now is how would I go about creating a command that takes informationn from a message the command is replying to (sender's name, message content) and stores it as an object. Also, what would be the best way to store that information?
I want to learn while doing this and not just have the answers handed to me ofc, but I feel very lost. Not sure where to even begin.
I tried to find tutorials on coding discord bots that would have similar functions to what I want to do, but can't find anything.
Intro :
Hi NyssaDuke !
First of all, prefer to paste your code instead of a picture. It's easier for us to take your code and try to produce what you wish.
In second, I see an "issue" in your code since you declare twice the bot. You can specify the intents when you declare your bot as bot = commands.Bot(command_prefix="!", intents=intents)
Finally, as stated by #stijndcl , it's against TOS, but I will try to answer you at my best.
filesystem
My bot needs to store data, like users ID, language, and contents relative to a game, to get contacted further. Since we can have a quite big load of requests in a small time, I prefered to use a file to store instead of a list that would disappear on crash, and file allow us to make statistics later. So I decided to use pytables that you can get via pip install pytables. It looks like a small DB in a single file. The file format is HDF5.
Let say we want to create a table containing user name and user id in a file :
import tables
class CUsers (tables.IsDescription) :
user_name = StringCol(32)
user_id = IntCol()
with tables.open_file("UsersTable.h5", mode="w") as h5file :
groupUser = h5file.create_group("/", "Users", "users entries")
tableUser = h5file.create_table(groupUser, "Users", CUsers, "users table")
We have now a file UsersTable.h5 that has an internal table located in root/Users/Users that is accepting CUsers objects, where, therefore, user_name and user_id are the columns of that table.
getting user info and storing it
Let's now code a function that will register user infos, and i'll call it register. We will get the required data from the Context that is passed with the command, and we'll store it in file.
#bot.command(name='register')
async def FuncRegister (ctx) :
with tables.open_file("UsersTable.h5", mode="a") as h5file :
tableUser = h5file.root.Users.Users
particle = tableUser.row
particle['user_name'] = str(ctx.author)
particle['user_id'] = ctx.author.id
particle.append()
tableUser.flush()
The last two lines are sending the particle, that is the active row, so that is an object CUsers, into the file.
An issue I got here is that special characters in a nickname can make the code bug. It's true for "é", "ü", etc, but also cyrillic characters. What I did to counter is to encode the user name into bytes, you can do it by :
particle['user_name'] = str(ctx.author).encode()
reading file
It is where it starts to be interesting. The HFS5 file allows you to use kind of sql statements. Something you have to take in mind is that strings in the file are UTF-8 encoded, so when you extract them, you have to call for .decode(utf-8). Let's now code a function where a user can remove its entry, based on its id :
#bot.command(name="remove")
async def FuncRemove(ctx) :
with tables.open_file("UsersTable.h5", mode="a") as h5file :
tableUser = h5file.root.Users.Users
positions = tableUser.get_where_list("(user_id == '%d')" % ctx.author.id)
nameuser = tableUser[positions[0]]['user_name'].decode('utf-8')
tableUser.remove_row(positions[0])
.get_where_list() returns a list of positions in the file, that I later address to find the right position in the table.
bot.fetch_user(id)
If possible, prefer saving ID over name, as it complicates the code with encode() and decode(), and that bots have access to a wonderful function that is fetch_user(). Let's code a last function that will get you the last entry in your table, and with the id, print the username with the fetch method :
#bot.command(name="last")
async def FuncLast(ctx) :
with tables.open_file("UsersTable.h5", mode="r") as h5file :
tableUser = h5file.root.Users.Users
lastUserIndex = len(tableUser) - 1
iduser = tableUser[lastUserIndex]['user_id']
member = await bot.fetch_user(iduser)
await ctx.send(member.display_name)
For further documentation, check the manual of discord.py, this link to context in particular.

Discord.js random number

If you don't mind me asking, I've been trying to find out a way to have a discord user say (prefix)randomnumber and then 2 parameters like 1 10 and it picks a random number such as 7. Does anyone know of a way to do this in java script?
You can do like
Math.floor(Math.random()*second_parameter)+first_parameter
and if we take the full code
const args = message.split(' ')
if(args[0] === `${prefix}randomnumber`){
message.channel.send(Math.floor(Math.random()*parseInt(args[2]))+parseInt(args[1]))

How to find a role by name and add a user to it (discord.js)

So I'm trying to create a bot that is more universal and can be added to more than one server. I've managed to reformat commands like announce or join messages etc. by using .find("name", "announcements").
My problem is that the same does not work for roles.
I've tried what little I could find on the internet, such as member.guild.roles.find("name", "Member") or member.guild.roles.find(role => role.name === "Member") but none of these work. A variety of different ways return different errors, but they usually say something along the lines of it not being an integer (I think) or snowflake.
This is the function that I am currently wrestling with:
client.on('guildMemberAdd', (member) => {
var joinResponse = ("Hello **" + member.displayName + "**, welcome to **" + member.guild.name + "**!")
let role = member.guild.roles.find("name", "Member");
member.addRole(role).catch(console.error);
member.guild.channels.find('name', 'general').send(joinResponse);
In short summary, what I'm looking for is the ability to get a role by name and add a user to it.
(I'm nearly certain it's possible, since popular bots like Dyno are capable of using commands to add roles to users.)
client.on('guildMemberAdd', (member) => {
const joinResponse = `Hello **${member.user.username}**, welcome to: **${member.guild.name}**!`
let role = member.guild.roles.get('Member');
if(!role) return console.log("Role doesen't exist.");
member.addRole(role);
const ch = member.guild.channels.get('general');
if(!ch) return console.log("Channel doesen't exist.");
ch.send(joinResponse);
});//You didn't have closing brackets (Could've been a problem)
First of all your string joinResponse was a function and you completely messed up merging it, I recommend using Template literal.
I used get function since it's a lot easier to use and cleaner, you only pass ID or name as a string.
To check if channel exists I used if statements and exclamation mark which means doesen't exist/false.
If I helped you please mark this as answer, thanks <3. If you need anything add comment to answer or message me on Discord (You can find my discriminator on my stack overflow profile).
For further explanation click on Blue words.

Await Buffer.from(String) turns out to numbers (Javascript)

i am trying desperately to solve the following problem. I researched a lot already but nothing really solved the problem (the used language is Javascript with Node.js and react-bootstrap library).
I want to write the following Array to Buffer and save it to IPFS in a way, that i can read it out later.
Nevertheless, the IPFS.Add() Method demand a buffer object, so i struggle to create the buffer object.
Here the array:
const line_supplier = new Array({
Lieferant: "Yello" ,
Postleitzahl: "13752" ,
Arbeitspreis: "5" ,
Grundpreis: "10" ,
Email: "email"
});
Sounds pretty easy, i know. If i do it like this, the console shows me a an empty buffer.
const line_buffer = await Buffer.from(line_supplier);
console.log(line_buffer);
I also tried ..line_supplier[0], or the recommendations with ..'UTF-8' as offset. I also declared the array directly in Buffer.from(declaration).
Either way, i get an error or just a couple of numbers out. Maybe this is already the mistake. I expect the buffer to be readable like a string?
So i converted the line supplier to a string with
const line_string = JSON.stringify(line_supplier);
But even with this string injected in Buffer.from(), i only get a Uint8Array(84) Object out with a lot of numbers.
I dont know what i am missing. It must be something very small. I read all the description of the methods already, but cant find it.
Thanks in advance!!!
The solution is, the following:
const line_string = JSON.stringify(line_supplier);
console.log(line_string);
const line_buffer = await Buffer.from(line_string);
console.log(line_buffer);
await ipfs.add(line_buffer, (err, ipfsHash) => {
console.log(err,ipfsHash);
Hence you get an array saved the way you want!

puppet hiera array, loop and hash

I have currently an issue between hiera/puppet:
In my hiera I have:
mysql_user_mgmt:
- mysql_user: 'toto#localhost'
mysql_hash_password: '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29'
mysql_grant_user: 'toto#localhost/*.*'
mysql_user_table_privileges: '*.*'
- mysql_user: 'test#localhost'
mysql_hash_password: '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29'
mysql_grant_user: 'test#localhost/*.*'
mysql_user_table_privileges: '*.*'
In my puppet, I'm trying to make a loop to get data from hiera:
$mysql_user_mgmt = hiera('mysql_user_mgmt',undef)
define mysql_loop () {
$mysql_hash_password = $name['mysql_hash_password']
notify { "mysql_hash_password: ${mysql_hash_password}": }
}
mysql_loop { $mysql_user_mgmt: }
but I'm getting some weird errors. Can someone help me to figure out how to make the loop?
Resource titles are strings. Always.
You are trying to use the the title of a mysql_loop resource to feed a hash to the type definition. That does not work. A stringified version of the hash will end up being used instead, and your later attempts to retrieve components by hash index will fail, likely with some kind of type error.
You have a few options:
You could restructure your definition and data a bit, and pass the aggregate data as a hash parameter. (Example below.)
You could restructure your definition and data a bit, and use the create_resources() function.
If you've moved up to Puppet 4, or if you are willing to enable the future parser in Puppet 3, then you could use one of the new(ish) looping functions such as each().
Example of alternative (1):
Reorganize the data to a hash of hashes, keyed on the user id:
mysql_user_mgmt:
'toto#localhost':
mysql_hash_password: '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29'
mysql_grant_user: 'toto#localhost/*.*'
mysql_user_table_privileges: '*.*'
'test#localhost':
mysql_hash_password: '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29'
mysql_grant_user: 'test#localhost/*.*'
mysql_user_table_privileges: '*.*'
Modify the definition:
define mysql_user ($all_user_info) {
$mysql_hash_password = $all_user_info[$title]['mysql_hash_password']
notify { "mysql_hash_password: ${mysql_hash_password}": }
}
Use it like so:
$mysql_user_mgmt = hiera('mysql_user_mgmt',undef)
$mysql_user_ids = keys($mysql_user_mgmt)
mysql_user { $mysql_user_ids: all_user_info => $mysql_user_mgmt }
(The keys() function is available from the puppetlabs-stdlib module.)

Resources