How to mention mentioned users in a message? - discord

I've been trying to figure this out in a while but honestly i can't seem to wrap my head around it, I've figured out that u can add roles to users by doing a simple add_roles with message.mentions[0] but i can't seem to figure out how to mention a mentioned user in a message, Here is my current code Any help would be great!
if message.content.lower().startswith('/slap'):
mention = message.mentions[0]
await bot.send_message(message.channel, mention + "got slapped by {0.author.mention}".format(message))

message.mentions returns a list of discord.Member objects. You can ping those members by using member.mention
So to ping the person you'd need
member = message.mentions[0] # Probably in a try block
content = "{0.mention} ... {1.author.mention}".format(member, message)
await bot.send_message(..., content)
or to get a list of mentions, you can probably get away with
# After checking the length of the list (2 or more)
mentions = [m.mention for m in message.mentions]
mention_list = ", ".join(mentions[:-1]) + " and " + mentions[-1]

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.

Ask. How to mention the sender and the person they mentioned (discord py.)

I tried to do it in different ways, but none gave the desired result. I need to use it in an embed.
I am new to this area and have not found any information.
Screenshot translation:
#name spit #name
Try to explain your question a bit more and show code you have tried, you can use {ctx.author.mention} to mention the member that used the command and {member.mention} to mention the member that was # make sure to call the member by useinf member :discord.Member in your async def ( )
Example:
async def hi(ctx, member : discord.Member):
await ctx.send(f"{ctx.author.mention} said hi to {member.mention}")

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.

GqlQuery Results Only for Session?

My app, Datastore, webapp2, and form-specific "responses" are all working :) but I need the page to load without displaying previous visitor's query results. I need query results only for current form-submitter, after they submit form. Is this a session or headers solution, or can I edit the GqlQuery to accomplish this?
messages = db.GqlQuery("SELECT * "
"FROM Visitor "
"ORDER BY date DESC LIMIT 1") #obviously shows previous form submit
for message in messages:
if message.name == "" or message.mood == "":
self.response.out.write("<div class='textright'>Type name and select.</div>")
self.response.out.write("</body></html>")
elif message.mood == "bad" and message.name != "":
self.response.out.write("<body><html>")
self.response.out.write("<div class='textright'>Stay the course
^ ^ this last section is my "response" that needs to appear only after current visitor submits form.
I would strongly recommend you to go through the Getting Started and especially the templates section, until you will understand how it works.
But you if you just want to see your example in action try this (read more):
class Process(webapp.RequestHandler):
def post(self):
name = self.request.get("name")
mood = self.request.get("mood")
if mood == "bad" and name != "":
self.response.out.write("<html><body>")
self.response.out.write("<h1>Welcome to the Internet!</h1>")
self.response.out.write("<p>My mood is %s and my name is %s</p>" % (mood, name))
self.response.out.write("</body></html>")
else:
self.response.out.write("<html><body>")
self.response.out.write("<h1>Welcome to the Internet anyway!</h1>")
self.response.out.write("</body></html>")
Also never use print in your GAE applications, use the logger instead for debugging and more.
If you want to emit values for debugging purposes, particularly if you want that before an <html> tag is written, try
self.response.out.write("<!-- name: %s -->" % self.request.get("name"))
Otherwise, the browser might get confused.
print from a handler will never to what you expect.
In your snippet, you haven't shown where var7 and var9 come from.
I do realize that post/.put form values to Datastore automatically redirects user to new page
I think you misunderstand. You haven't shown us where your code does a put() or a redirect. A post() handler does not automatically do either.
Which tutorial are you looking at? Perhaps we need to tighten up vague wording.

Google Datastore problem with query on *User* type

On this question I solved the problem of querying Google Datastore to retrieve stuff by user (com.google.appengine.api.users.User) like this:
User user = userService.getCurrentUser();
String select_query = "select from " + Greeting.class.getName();
Query query = pm.newQuery(select_query);
query.setFilter("author == paramAuthor");
query.declareParameters("java.lang.String paramAuthor");
greetings = (List<Greeting>) query.execute(user);
The above works fine - but after a bit of messing around I realized this syntax in not very practical as the need to build more complicated queries arises - so I decided to manually build my filters and now I got for example something like the following (where the filter is usually passed in as a string variable but now is built inline for simplicity):
User user = userService.getCurrentUser();
String select_query = "select from " + Greeting.class.getName();
Query query = pm.newQuery(select_query);
query.setFilter("author == '"+ user.getEmail() +"'");
greetings = (List<Greeting>) query.execute();
Obviously this won't work even if this syntax with field = 'value' is supported by JDOQL and it works fine on other fields (String types and Enums). The other strange thing is that looking at the Data viewer in the app-engine dashboard the 'author' field is stored as type User but the value is 'user#gmail.com', and then again when I set it up as parameter (the case above that works fine) I am declaring the parameter as a String then passing down an instance of User (user) which gets serialized with a simple toString() (I guess).
Anyone any idea?
Using string substitution in query languages is always a bad idea. It's far too easy for a user to break out and mess with your environment, and it introduces a whole collection of encoding issues, etc.
What was wrong with your earlier parameter substitution approach? As far as I'm aware, it supports everything, and it sidesteps any parsing issues. As far as the problem with knowing how many arguments to pass goes, you can use Query.executeWithMap or Query.executeWithArray to execute a query with an unknown number of arguments.

Resources