Get Number from Slash Command and put it on a link - discord

So, if a user says /GetProfile (EnterNumberHere)
The Number from that command should go at the end of a link
for example, i said /GetProfile 1 the number "1" should go at the end of this link
"http://cubestoria.ezyro.com/User/?id="
So, then the bot will respond with http://cubestoria.ezyro.com/User/?id=1
https://i.stack.imgur.com/dYCU0.png
I want to look like this but their is a option (like the diet in the photo) that you can put a number in.

Use ${variable} to put variable in string:
// ...
.addNumberOption(option => option.setName('diet').setDescription('...'))
const number = interaction.options.getNumber('diet')
interaction.reply(`http://cubestoria.ezyro.com/User/?id=${number}`)

Related

React router with regex - inserting a number in middle of the path

I get my current path by using useLocation() hook.
I have several buttons and want them to navigate me to the current path combined with that concrete list ID.
Lets suppose its https://localhost:3000/list/3/items
How to insert that ID (here is 3) in between - list/{id}/items - with regex?
const navigate = useNavigate();
const location = useLocation();
// location.pathname - getting current path
// pinned to each button
const handleListChange = (listId: number) => {
// navigate(...);
};
I cant achieve that with just navigate("/list/{listId}/items") because /items can differ depending on what subpage im currently at ("/list" stays the same). So it can be for example list/{listId}/itemsSubpage/.../.... I just want to stay at the current page when navigating and only let id change.
Why not simply redirect starting from the root? I don't see the need for a regular expression here.
navigate(`/list/${listId}/items`);
or am I missing something?
Post Edit answer:
There are a few ways to achieve what you want but I'll just go ahead and post the one that came to me first, you can adjust it to your needs.
const exp = /(\/list\/)\d{1,}(\/?.+)?$/i;
const currentUrlMock = 'https://test.com/list/240/items/subpage/2/doesnt-matter'
const replaceId = (newId) => currentUrlMock.replace(exp, `$1${newId}$2`)
console.log(replaceId(3));
// logs: https://test.com/list/3/items/subpage/2/doesnt-matter
How this works is that the regular expression contains two capture groups:
(\/list\/) that matches the /list part
(\/?.+)?$ that matches everything that appears after your ID
Between them there's a \d{1,} that will capture all digits, it's not a capture group though - it has no parentheses around it ().
Replace method on string accepts regex as a first param and in the second param you can access captured groups by using dollar signs and group number, $1 to capture first group, $2 to capture the second group and so on.
By using $1${newId}$2 $1 will be replaced with fist captured group - /list and $2 will be replaced with second captured group - (\/?.+)?$. Between these a new ID which is passed in a function param will be inserted.
You should add more checks to make sure there's a proper match, I also tested the regular expression only for these URLs:
https://test.com/list/4
https://test.com/list/4/
https://test.com/list/120
https://test.com/list/120/
https://test.com/list/120/items
https://test.com/list/120/items/240
https://test.com/list/120/items/240/
and it works for these but your real use case might be different.

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.

How to add line to a txt file in discord.js

I have a logging txt file for my bans and kicks to keep track of them in my dc bot.
The log file gets really messy after the first ban because i do not know how to yet the logs to separate lines in the file.
Does anyone know how to do that?
Okay so as you have not provided any code, I can just guess how you are doing it. Lets say you have a variable let str = "" where you add your bans to. In this case you can simply do:
str += `Banned/Kicked ${user.tag}, because ${reason}.\n`;
\n would add a new line for each new ban/kick. Let's say we have two banned users. The name of the first one is Example#0001 and the reason was Test. The name of the second user is Example#0002 and the reason was Test2. This would be the output:
Banned/Kicked Example#0001, because Test.
Banned/Kicked Example#0002, because Test2.

how to pass variable argument to context.execute_steps in python-behave

I want to execute certain step before executing my function. The step takes variable as an argument. I am not able to pass it in context.execute_steps.
eg.
call1 = "version"
call1_method = "get"
context.execute_steps('''When execute api{"method":call1_method, "call":call1}''')
however this does not work. I get error in argument parsing because variables are not in quotes. I don't see any such example in behave documentation. Any help would be really appreciated.
There's a bunch of stuff that could be going on. I found here that if you're using python 3 you need to make it unicode by including a u in front of '''. I also was a bit tripped up that you have to include when, then or given as part of execute step command (not just the name of the step), but your example seems to be doing that. I'm kind of confused by what the way you're passing variables but can tell you this how you use execute_steps and works in python 2 & 3 with behave 1.2.5.
#step('I set the Number to "{number:d}" exactly')
def step_impl(context, number):
context.number = 10
context.number = number
#step('I call another step')
def step_impl(context):
context.execute_steps(u'''when I set the Number to "5" exactly''')
print(context.number)
assert context.number == 10, 'This will fail'
Then calling:
Given I call another step
When some not mentioned step
Then some other not mentioned step
Would execute when I set the Number to "5" exactly as part of the when I call another step.
Hard to say for your exact example because I'm unfamiliar with the other step you're trying to execute but if you defined the previous step with something like:
#step('execute api "{method}" "{version}"')
def step_impl(context, method, version):
# do stuff with passed in method and version variables
you should the be able to use it like so in another step.
#step('I call another step')
def step_impl(context):
context.execute_steps(u'''When execute api "get" "version1"''')
If your problem is just passing information between steps. You could just use context to pass it between them.
#step('I do the first function')
def step_impl(context):
context.call1 = "version"
context.call1_method = "get"
#step('I call another step')
def step_impl(context):
print(%s and %s are available in this function % (context.call1, context.call1_method)
And then call the steps in a row
When I do the first function
And I call another step
...

How to print username as path in Drupal 7

I'm trying to give every registered user a unique url shown on their user page which they can copy and paste...promoting their page.
I had this working using Pages and Tokens...but now I've ditched Panels/Pages for a custom user-profile.tpl.php
I've tried this:
print ($user->name);
But this returns the user name as Hillay Swag instead of hillary-swag
How can I print the url version of the user name instead of the human version?
$link = drupal_get_path_alias('user/' . $user->uid);
print $link;
That will print out users/admin. Further, if you only want the username part of the path (no users/) you could cut it with PHP's substr() function.

Resources