#discord-bots
1 messages ยท Page 738 of 1
if ctx.message.channel.name == "mod-chat":
closest thing i can find to that
That's not the problem.
Somewhere you've overwritten the message variable.
And did message = ...
ill try finding where because pretty sure i didnt do it on purpose
outside that block of code there isnt anything that necessarily overwrites message
or inside it
There definitely is
or anywhere in the code look ill send
from discord.ext import commands
print(discord.__version__)
client = commands.Bot(command_prefix=",,")
TOKEN = "tokenishere"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
else:
if message.content.lower() == "hello":
await message.channel.send(f"hello {message.author.name}!")
elif message.content.lower() == "hi":
await message.channel.send(f"hello {message.author.name}!")
elif message.content.lower() == "bye":
await message.channel.send(f"goodbye {message.author.name}!")
elif message.content.lower() == "goodbye":
await message.channel.send(f"goodbye {message.author.name}!")
await client.process_commands(message)
@client.command()
async def ping(ctx):
await ctx.channel.send(f"In milliseconds: {round(client.latency * 1000)}")
@client.command()
async def say(ctx, *, message=None):
if message is None:
await ctx.send("Argument error")
await ctx.message.delete()
await ctx.send(f"{message}")
@client.command()
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
mes = await ctx.send("Argument error")
return
await ctx.send(f"<@&role-id>, `{message}`")
if message.author == client.user:
if "<@&role-id>," in message.content:
await message.add_reaction(":thumbsup:")
else:
return
else:
return
else:
return
client.run(TOKEN)
Well, message is a parameter.
You probably want to use ctx.message everywhere instead of message in your poll command.
Besides when you need the argument you give.
Example here:
There you need to keep it
it seems to not add reactions still
Hi I am "trying" to make an event for when ** only I** sends an int in a specific message the bot adds on a number then sends the message, so bassically just counting back and fourth between me and the bot. This is what I have so far but I 99% it is incorrect.
@bot.event
async def on_message(message):
counting_channel = await bot.fetch_channel(822931755681841162)
if message.channel.id == 822931755681841162 and message.author.id == 396620060531228672 and message.context is int:
await counting_channel.send(message.context+1)
and i did use the raw emote
No you did not, at least not in here.
It should appear like that
await message.add_reaction("๐")
and not like that
await message.add_reaction(":thumbsup:")
.
The code your sent proves the opposite.
message.content will always be a string, use try/except and convert the message content to an integer using int()
Well, are you sending <@&role-id>?
Could I do this?
async def on_message(message:int):
You can try, it's not a good solution though.
yeah because later ill replace it with the actual role id so i dont have to keep pinging
if thats what youre meaning
Well then it's normal it won't work now xD
Both works tho
Ok, do you actually pay for winrar...
it does send the message without flaws it just doesnt add reactions
For handling errors it's better to try to convert it by yourself, especially if you want to do more things in that event later.
You're checking if the author of the message if your bot. It will never be true.
The message author when executing a command is always you.
oh. i tried to make it detect it's own message so it adds the reaction to that
So
if ctx.message.author == client.user
will always return False
What difference discord py and nextcord
discord.py is no longer being developed, nextcord continues development and has updates.
Should I use it
Your choice, not ours.
Ok I will use js
Sounds good
Js*
@slate swan any idea if possible and how i can make the coonsole runnig bot have partcial dynamic messages, and like a banner that is static ... atm all prints just go up n up
Well, never did it as it's flooding the terminal for no reason. But you probably need to always clear and send the banner with the text.
hello?
hm
i am new to the server
Leave
what?
Nothing
like is this the place for bots?
For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.
Yea
ok
how do i communicate with bots then?
am i supposed to ping em?
Use #bot-commands
Go there, use commands and do something with them.
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
mes = await ctx.send("Argument error")
return
else:
await ctx.send(f"<@&role-id>, `{message}`")
if "<@&role-id>," in ctx.message.content:
await ctx.message.add_reaction(":thumbsup:")
else:
return
else:
return```
what's wrong now?
it's not sending the embed when i use the mute command nor give it the role.
@bot.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
if member == ctx.author:
em = discord.Embed(
description=f"**you** cannot `mute` yourself", colour=discord.Colour.red()
)
await ctx.send(embed=em)
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
await member.add_roles(mutedRole, reason=reason)
else:
em1 = discord.Embed(
description=f"{member.mention} has been `muted` for **{reason}**",
colour=discord.Colour.green(),
)
await ctx.send(embed=em)
em2 = discord.Embed(
description=f"**you** have been `muted` for **{reason}**", colour=0
)
await ctx.send(embed=em1)
await member.send(embed=em2)
list_of_muted_members.append(member)
print(list_of_muted_members)
@bot.command()
@commands.has_permissions(kick_members=True)
async def unmute(ctx, member: discord.Member, reason=None):
if member == ctx.author:
em = discord.Embed(
description=f"**you* cannot `unmute` yourself", colour=discord.Colour.red()
)
await ctx.send(embed=em)
else:
em2 = discord.Embed(
description=f"{member.mention} has been `unmuted` for **{reason}**",
colour=discord.Colour.green(),
)
em3 = discord.Embed(
description=f"**you** have been `unmuted` for **{reason}**", colour=0
)
mutedRole = discord.utils.get(ctx.guild.roles, name="muted")
await member.remove_roles(mutedRole)
await member.send(embed=em3)
await ctx.send(embed=em2)```
Are you adding an argument when executing the command and do you mention the role? And have you changed the role id?
Because your indentation is wrong.
nah i figured out why
TF He pay for Winrar
i will only add the role id when i make it add reactions, i did manage to make it ping before
!ot for other random talks please
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
And how do you execute your command?
As you need to execute your command, for example, like this:
!poll <@&585529568383860737>, something else here
,,poll (what the poll is about)
did you really ping all the nitro boosters lol
No, I don't have permissions.
oh yeah
Ok... I don't get this error...
@frail notch your add_to_guild function
u want the code to it?
Mhm
How do I make the bot send a message if I want it to do so in a on_message event?
the parameter doesn't have ctx, so I am confused.
depends on where you want to send it to and on what condition
you need to pass 3 arguments, you only passed 2
oh
I just want it to reply to the message given in the parameter of the on_message() event
se let's say I do this
!shit
hello I'm the bot and this is shit
so add_to_guild(code, userid) becomes add_to_guild(code, guild_id, userid)?
Nonono
Not that, I am not referring to a command
you just want to send a message in the same channel that message was sent in?
Yep.
correct
I don't have the ctx parameter, I am asking how to do it in a on_message event
imma send my code
nah, just give me the line like you would send in a command
I'll give it to you via event
@dreamy sluice u can simply do ctx = await bot.get_context(message)
no
@bot.event
async def on_message(message):
r = open("trigger_words.json", 'r')
read = json.load(r)
r.close()
for i in read:
if i["id"] == str(message.guild.id):
dict = i["triggers"]
for keys in dict:
if str(message.content) == keys:
#I want it to reply to the message in the paramater with dict[keys] here
This will get u the ctx object of the message
Really?
!d discord.ext.commands.Context for more information
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
:o
he can just do await message.channel.send("hi")
then that gives me this error... {"code": 50035, "errors": {"guild_id": {"_errors": [{"code": "NUMBER_TYPE_COERCE", "message": "Value \"<function guild_id at 0x0000000001D02C20>\" is not snowflake."}]}}, "message": "Invalid Form Body"}
he doesn't need the context in an event
!d discord.ext.commands.Bot.get_context for more information
await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
My bad, this is the correct one
Will it work if I replace send with reply?
Dude I just told him the way he's comfortable with
U can do message.reply
that's just you sending an incorrect api request... ๐คทโโ๏ธ
Ok then, lemme try
Damn, this works.
Thanks :D
ctx.send is an alias, it's basically ctx.channel.send, if that clears some stuff up for you
what do i need to write to make a bot add reactions? i tried await await ctx.message.add_reaction("raw emoji") but it doesn't seem to work in any way.
I know.
is there like a one line code that removes roles from a member that have send_messages permissions? (discord.py)
so you didn't need ctx, you just needed the channel object, given a message object
oneliners aren't always faster, you can make some simple for loops...
we need errors and concrete code to fix your issue
no errors. the code that runs the command is
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
mes = await ctx.send("Argument error")
return
else:
await ctx.send(f"<@&role-id>, `{message}`")
if "<@&role-id>," in ctx.message.content:
await ctx.message.add_reaction(":thumbsup:")
else:
return
else:
return```
Actually no. It's a subclass of abc.Messageable, which is an abstract class, containing the send method
it sends the message, just no reactions
are you sure it even reaches the else statement?
nope
start debugging then
your if statement is just wrong
I'll give you the if statement
What do u wanna do
if role_id in ctx.message.raw_role_mentions:
,,poll topic
@ping, topic (+ ๐ and ๐ reaction)
and only able to run in the mod-chat
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
This is cleaner
Oh, they remade it
?
They remade the tag
Ok, I've got a new problem with my bot. I tried it's commands in different servers, and now it ceases to respond to other commands
It's a lot different now
O
@maiden fableCan you help?
Do you have an on_message
Yep
With bot.event deco?
Yessir
@bot.event
async def on_message(message):
r = open("trigger_words.json", 'r')
read = json.load(r)
r.close()
for i in read:
if i["id"] == str(message.guild.id):
dict = i["triggers"]
for keys in dict:
if str(message.content) == keys:
await message.reply(dict[keys])
This one
Change the deco to bot.listen()
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
mes = await ctx.send("Argument error")
return
else:
await ctx.send(f"<@&role-id>, `{message}`")
if role-id in ctx.message.raw_role_mentions:
await ctx.message.add_reaction(":thumbsup:")
else:
return
else:
return```
smth like this? please dont laugh at me lol
Mkay
you should use command checks, it'll save you a lot of time and problems
Didn't I tell that only rn
Why not just assign the message to a variable and add the reaction like that?
@client.command()
async def toggleDM(ctx, status):
user_id = ctx.author.id
if status == "disable":
noDM_list.remove(user_id)
await ctx.reply("You can now recieve dm's from me.")
elif status == "enable":
noDM_list.append(user_id)
await ctx.reply("You can no longer recieve dm's from me.")
else:
await ctx.reply("Please put either `disable` or `enable`")
@client.command()
async def dm(ctx, user:discord.Member,*,message=None):
user_id = ctx.author.id
if user in noDM_list:
await ctx.reply("That user has diabled the ability for me to send them a dm. Send it yourself.")
return
else:
await user.send(f"{message}\n\nSent by <@{user_id}>")
await ctx.send("DM sent.")
that is my code.
when I do
toggleDM enable
dm cibere test
I get the dm, and when I do
toggleDM disable
dm cibere test
i also get the dm
why doesnt it block the dm, and how can i fix it? Please ping in reply
Wait, u asked the same question yesterday too, right?
user: discord.Member
Pep8 
yes but i didnt get a reply, or i did i never saw it cuz i never got a ping
Well I told u the issue
how do i make it know that the variable is that message?
how do I get the user mentions on on_message event?
well i cant fint my message or any responces so... yeah
message.mentions
but where do i put that...?
U r adding user IDs to the list but checking for user objects in the list...
So, uhhh
By assigning it. I.e
var = await ctx.send(...)
Like you have already done
he's just referring to the fact that you call a Member object a user, they're different things
oh
No
PEP 8 is the style guide for Python
ty guys! it works now
The person just means that he should add spaces after the :
what i meant is that, how do i assign the correct message? Do i need to fetch the ID?
!pep 8 for more information (:
What you're trying to do is add reactions to the message your bot sent, correct?
right
and that's for user mentions only?
No
then how do I get user?
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
Then do what I said above and add the reaction to it i.e
var.add_reaction(...)
Don't use the naming I used. It might shadow some built in names
vars([object])```
Return the [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute for a module, class, instance, or any other object with a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute.
Objects such as modules and instances have an updateable [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute; however, other objects may have write restrictions on their [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attributes (for example, classes use a [`types.MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType "types.MappingProxyType") to prevent direct dictionary updates).
Without an argument, [`vars()`](https://docs.python.org/3/library/functions.html#vars "vars") acts like [`locals()`](https://docs.python.org/3/library/functions.html#locals "locals"). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised if an object is specified but it doesnโt have a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute (for example, if its class defines the [`__slots__`](https://docs.python.org/3/reference/datamodel.html#object.__slots__ "object.__slots__") attribute).
I mean readability would still be bad
Ah, gotcha
also how do i do command checks? i searched it and it doesn't show anything
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
How can I fix dis
how do I get my full tag through member object?
message.author
through member object
ah
so message.member?
str(member)
thanks
we already told you that you're just sending a bad API request
show me the code and I'll tell you what's wrong with it
chances are, you're passing a function as an argument instead of an actual guild_id
Or u ain't calling a function
def add_to_guild(access_token, guild_id, userid):
url = f"{API_ENDPOINT}/guilds/{guild_id}/members/{userid}"
data = {
"access_token" : access_token,
}
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
response = requests.put(url=url, headers=headers, json=data)
print(response.text)
code = exchange_code(excode)['access_token']
add_to_guild(code, guild_id, userid)
now show us where you defined guild_id
bingo
what is the event for reactionadd?
just rename that function to get_guild_id
then do guild_id = get_guild_id(guild_invite)
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnโt require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
there are other flaws in that code
for example
your first line in that method is defining a data dict, which you never use and simply overwrite
how exactly do i check commands? i didnt really understand this because im stupid
Wdym by defining data dict
member.timeout(time)
you're defining data = but never doing anything with it at the beginning, you overwrite it with
data = shit.json() a few lines later
this won't give you errors tho, but it's impractical
is there like a one line code that removes roles that have send_messages permissions? (discord.py)
alright...
we already answered that...
|| no, not in one line, unless you want to make it unreadable ||
like a mute command?
i also looked through the docs. it's still unclear for me
Check commands as in?
custom checks
i don't even really understand what theyre for but apparently i have to know and i dont know where i can learn them properly
eh, ill just give up at this point
What kind of check are you trying to make
Discord.py has pretty much of inbuilt checks
i don't know i just got told to make a command check
Your main intention?
like a poll feature which only users with some permissions can use right?
It's a poll feature for a mod chat in a server I'm in
ah , so u want that to work only for that channel?
for making decisions
yep
i tried using if/else to make sure it only works in the right channel
async def cmd(...
if ctx.channel.id == <mod channel ID>:
# do stuff```
This should work
!custom-checks
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
And this is the check method to do that
Damn , the example is exactly what u need lol
Hahaha that's why I showed him the tag
follow naming conventions
twice
show me the full error/code
managed to fix it by using () instead of ==
๐
async def poll(ctx, *, message=None):
if ctx.channel.id(821116917753839627):
if message is None:
mes = await ctx.send("Argument error")
return
else:
await ctx.send(f"<@&821111383939743754>, `{message}`")
if 821111383939743754 in ctx.message.raw_role_mentions:
await message.add_reaction(":thumbsup:")```
somethings wrong
The channel ID.
it's an attribute, not a function
do i have to add ctx or no?
got it
what
it's right till this part
then you should just check if it's the right id
if ctx.channel.id == 821116917753839627:
you cant call an integer

if 821111383939743754 in ctx.message.raw_role_mentions: this is also wrong
!d discord.Message.raw_role_mentions
you know what
forget it
eh, i should just give up when i finish this
I know I am kind of late to this, but what is a good alternative for discord.py since it's being shut down?
di๐
I prefer disnake
'Message' object has no attribute 'json'
wth
are there any major changes from discord.py to disnake?
absolutely none
looks prettyu much the same lol
well slash commands
No, just all instances of discord change to disnake
but slash commands aren't a change, just an upgrade
ok, well, I was recommended pycord but I'll use disnake, thank you for the help :D
np
help
don't do what you did
that worked
now i just need to find a way to add reactions which doesn't seem to work
Lets see the code
bruh
with open('premium.json','r') as f:
data = json.load(f)
if f"{ctx.author.id}" in data:
I don't think this is where you get the error
Give the full traceback
he's gone
does anyone know how to add reactions to a message your bot just sent?
save the message in a variable
Hello everyone! Can somebody help me? I would take a liking to it to make, that if impress onto a button on the message, let him not send one then yet, but let him modify the message
using what? it's ID? geniuenly i don't know
send() doesn't only send the message, but it returns it
anybody?
meaning you can save it to a variable with the send() method
message = await ctx.send(...)
I'm using send() already
I'll try it
it's saved, now what can I write to make it add the reaction?
await message.add_reaction(...)
do i use the raw emote or ::, and do i make it a string?
nobody?
is it an emoji in your server? or is it a basic emoji?
basic
Didn't I already explain this to you?
i don't remember actually
is there a way to add to a message?
Similar to edititing it but i want to keep the original message before it?
my memory sucks
Can I see your current code?
async def poll(ctx, *, message=None):
if ctx.channel.id == 821116917753839627:
if message is None:
mes = await ctx.send("Argument error")
return
else:
mes2 = await ctx.send(f"<@&821111383939743754>, `{message}`")
await message.add_reaction(":thumbsup:")```
@client.command()
async def poll(ctx, *, message=None):
if ctx.channel.id == 821116917753839627:
if message is None:
mes = await ctx.send("Argument error")
return
else:
mes = await ctx.send(f"<@&821111383939743754>, `{message}`")
await mes.add_reaction(":thumbsup:")```
try?
is it possible to get the custom user banner in a guild (the one we can edit in every single guild through server profile if we have the 10$ nitro)
Because i sent a http request but could only get the custom server avatar
๐
copy this
await mes.add_reaction("๐")
wait no
remove the else
and deindent the last two lines
your logic is kinda illogical
Also you could do
if ctx.channel.id == 821116917753839627 and message is not None:```
bad habit of using actual emojis
it work
I use
modeeasy
memory spared
code readable
what the
how did I put a hecking book there
Why set message to None if you're making it a required argument?
hello]
does anyone know how to host a discord bot on https://platform.sh?
There are steps but I need some help
I can list them and you can help me
I use PyCharm btw
host on a vps
such as?
vultr
I need a free trial atm
The first step is add your SSH key
What is that? I've never used one to run my bot on PyCharm
SSH is secure shell
how do I get it?
you can use PuTTY
@commands.Cog.listener("on_message_delete")
async def on_message_delete(self, message)
``` anyway to see if message was from a command being executed or simple message
that has been deleted*
\n newline add text
like py new_message "I wanna add this!" new_content = message.content+"\n"+new_message
how do i make so when you invite a bot it sends a welcome message saying like "thanks for inviting"
!d discord.on_member_join @summer lynx
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
!d discord.ext.commands.Bot.get_context use this on the message variable, it returns a Context object. You would then use Context.valid to see if it contained a command invocation
await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
!d discord.ext.commands.Context.valid
property valid: bool```
Checks if the invocation context is valid to be invoked with.
perfect ddude thanks
so the bot is the member?
how do i set it up?
i tried that before and it just showed when the member joined a guild and it was spamming the channel. im saying the bot joining the guild like it will send something like this
no
client bad ๐
and also itโs member 
they want something to happen when the bot joins
not when a member joins
you spelt member as memeber ๐
did i
and bot is better
lol
๐
yes i did, but this is incorrect, neither matters, it's just a variable assignment
ok
Is it possible to use a file for an embed thumbnail instead of a url?
This doesn't work
ban_embed.set_thumbnail(file="./img/ban_hammer.png")
@slate swan
filename = bla.png
file = discord.File(filename)
embed.set_thumbnail(url=f"attachment://{filename}")
await ctx.send(embed=embed, file=file)```
if server_channel_admin_logs_message_id == 0:
channel = client.get_channel(server_channel_admin_logs)
await channel.send(f'``fix\nAdministrator: {admin} - {date} - {time}\n{command}``')
else:
channel = client.get_channel(server_channel_admin_logs)
msg = await channel.fetch_message(server_channel_admin_logs_message_id)
await msg.edit(content=f"``fix\n{msg}\nAdministrator: {admin} - {date} - {time}\n{command}``")
Anyone know why this isnt working? im getting no errors
?
what do you expect to happen vs what's actually happening?
error says it all "improper token has been passed"
@potent spear Im trying to edit the message already in the channel and update it with a new line.
Nothing is actually happening ๐
well, are you sure it executes the else statement?
do you have any error handlers?
No ๐ฆ
show me your whole command
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this is a function you run in a command?
because that doesn't seem like a command to me
@potent spear Yeah i run it from a command for now just for testing. once its working it will go on a loop
you're also hiding stuff from me
you put all the stuff in a try block, but where did you except it?
I've been away from discord.py awhile, what fork should I goto that supports the newest features of discord and is most stable??
@potent spear https://paste.pythondiscord.com/ezuqucunah.py my bad, thats the only thing missing
alright, remove the try catch and the errors will present themselves
okay 2 secs ๐
@potent spear still no errors
the channel_id and the msg_id i store in a SQL Database as ints? would this be affecting it anyway?
that's how it should be
ahh good ๐
make sure when you fetch them, they actually get returned as integers too
let me print them just in case
the types, not the values
yeah
@client.command()
async def toggleDM(ctx, status):
user_id = ctx.author.id
if status == "enable":
noDM_list.remove(user_id)
await ctx.reply("You can now recieve dm's from me.")
elif status == "disable":
noDM_list.append(user_id)
await ctx.reply("You can no longer recieve dm's from me.")
else:
await ctx.reply("Please put either `disable` or `enable`")
@client.command()
async def dm(ctx, user:discord.Member,*,message=None):
user_id = ctx.author.id
if user in noDM_list:
await ctx.reply("That user has diabled the ability for me to send them a dm. Send it yourself.")
return
else:
await user.send(f"{message}\n\nSent by <@{user_id}>")
await ctx.send("DM sent.")
this is my code. when you run toggleDM disable, it adds your user id to the list, but it doesnt block ppl from dm @you message
how can i fix this
PLEASE I BEG YOU, PING IF YOU ARE RESPONDING TO ME OR I MIGHT ASK AGAIN
@potent spear Yeah theyre definitly Ints
well, last resort is:
where you run the function, you've put a try except again
what is the goal of the command
@potent spear ill try that now
what does it do
i want toggleDM disable to add your user id to a list, then when you do dm cibere hi, if my user id is on the list i dont want it to send the dm to me.
I highly recommend using a botvar for this
then toggleDM enable removes your user id from the list, then it lets ppl dm you using hte bot
it's because you're storing ID's in the list, and you're looking for objects in the list instead of the ID
basically you dont want people to dm you if you are in the list
how can i fix this?
@potent spear still no errors
hello, can I get the username of a discord user who invokes?
just send me your whole code
ctx.author is the Member object
context.author.id or whatever
ah, thank you :D
in your case, context.author.display_name
Heya, how can I make a checker in my bot which checks if the inputted token, client ID, etc... is valid?
I have this ticket system and it works for the most part but when i react to a ticket it gives me this error and it doesnt make a new channel called ticket 1
this is the full file https://mystb.in/HideAvonCrm.python
And this is what happened when I reran the bot
a check like @has_permissions?
no... more like check character count, check for client id if its only numbers...
do you know how i can fix it?
ofc, everything's possible
this just gives me a long string of number D:
if user_id in noDM_list instead of if user in noDM_list
Just i wanna make it so it checks all these and if any of them are wrong, it changes it from [+] to [-] (and changes the colour ofc)
Can someone help
but when I do that, it still doesnt work
that's not really dpy related
you can't convert "spam" to an int
is it possible to get the name and not the id?
No... its not... ur right actually... the only reason i sent it here is cuz its part of a discord bot code.
Pretty much any user can add it to their server and get it to work in their serv by downloadin the code and inputting those
Then what do I do
fix your split stuff, it's wrong
check what it outputs before converting
idk what you're trying to do with that +1 stuff
which channel would u recommend i use?
any of the help channels #โ๏ฝhow-to-get-help
oh like #help-cake ?
Ok ty
oh alr
@potent spear So ive just done some more testing this is whats happened.
<Message id=929842242200408194 channel=<TextChannel id=929841976495456278 name='adminlogs' position=15 nsfw=False news=False category_id=929017222473592884> type=<MessageType.default: 0> author=<Member id=918225442480201818 name='Scum Bot' discriminator='8076' bot=True nick=None guild=<Guild id=847327487058247712 name="Poochington's server" shard_id=None chunked=True member_count=6>> flags=<MessageFlags value=0>>
Administrator: Screech - 2022.01.07 - 21.42.17
Command: 'listplayers'```
and then the last 2 lines change, instead of adding a new line.
I can't help you without any code
but when I do that, it still doesnt work... is there anything else i can try?
sure there is, make a botvar out of it
channel = client.get_channel(server_channel_admin_logs)
msg = await channel.fetch_message(server_channel_admin_logs_message_id)
await msg.edit(content=f"``fix\n{msg}\nAdministrator: {admin} - {date} - {time}\n{command}``")```
botvar................?
bot.no_DM_list = ...
ok
that way, you can always get the list
bot.noDM_list = []
yes
ok
that's what comes right under where you defined your bot
then you can easily access that botvar through any command
shouldn't it be client.noDM_list = []?
ofc
cuz i use client instead of bot
bot, client, shit, those are all variable names for the same object
kk
nothign different happened
@client.command()
async def toggleDM(ctx, status):
user_id = ctx.author.id
if status == "enable":
client.noDM_list.remove(user_id)
await ctx.reply("You can now recieve dm's from me.")
elif status == "disable":
client.noDM_list.append(user_id)
await ctx.reply("You can no longer recieve dm's from me.")
else:
await ctx.reply("Please put either `disable` or `enable`")
@client.command()
async def dm(ctx, user:discord.Member,*,message=None):
user_id = ctx.author.id
if user in client.noDM_list:
await ctx.reply("That user has diabled the ability for me to send them a dm. Send it yourself.")
return
else:
await user.send(f"{message}\n\nSent by <@{user_id}>")
await ctx.send("DM sent.")
@client.command()
async def noDmList(ctx):
await ctx.reply(f"""{noDM_list}""")
ok
@client.command()
async def toggleDM(ctx, status):
author_id = ctx.author.id
if status == "enable":
client.noDM_list.remove(author_id)
await ctx.reply("You can now recieve dm's from me.")
elif status == "disable":
client.noDM_list.append(author_id)
await ctx.reply("You can no longer recieve dm's from me.")
else:
await ctx.reply("Please put either `disable` or `enable`")
@client.command()
async def dm(ctx, member: discord.Member, *, message=None):
# I told you to change this if statement half an hour ago
if member.id in client.noDM_list:
await ctx.reply("That user has disabled the ability for me to send them a dm. Send it yourself.")
return
await member.send(f"{message}\n\nSent by {ctx.author.mention}")
await ctx.send("DM sent.")
@client.command()
async def noDmList(ctx):
await ctx.reply(f"""{client.noDM_list}""")```
yes, all the indentation is correct
when did you tell me to change that statement....
I fixed a lot of variable names too, you were confusing yourself with it
then i said when i did that, it didnt work
doesn't matter, everything should work now
yeah i do that alot lol, i have a hard time naming stuff, so i end up naming stuff like toggleDMvar1,toggleDMvar2, etc
it's not hard naming things, you just have to tell what it is..
oof okay I'm asking a lot of questions :P
How can I get my discord bot to wait for a reaction to then execute another bit of code
in the docs, there's a bot.wait_for method with examples
could you link that perhaps, because I can't find that
what have you tried? to find it
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Docs for wait_for
How can I make it so that the user can input a list separated by commas and once inputted, the code will repeat add_to_guild with each id seperately?
[...]
userid = input("UserID> ")
[...]
def add_to_guild(access_token, guild_id, userid):
url = f"{API_ENDPOINT}/guilds/{guild_id}/members/{userid}"
data = {
"access_token" : access_token,
}
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
response = requests.put(url=url, headers=headers, json=data)
print(response.text)
code = exchange_code(excode)['access_token']
[...]
add_to_guild(code, get_guild_id, userid)```
wdym
a wrapper is a library that simplifies the connection between the web services and local code
i mean how much would it simplify it?
A lot
like what would that chunk of code turn into
well you should probably look into nextcord and find that out yourself
how do i randomly add invisible characters to a string
@frail notch oh, you're creating a self bot
But you were trying to get help about creating a self bot only 2 days ago, correct?
yes and that was 2 days ago...
dm me ill show u the full code
I'm not interested
then stop assuming its a selfbot
how would i delete a message if it contains a specific word
Then whats you're reasoning behind not using a wrapper?
cuz i got the start of the code from a tutorial
I'm going to assume its in an on_message event. Am I correct?
ye
await message.content.delete()?
await message.delete()
i mean like say it contained the word fuck how would i delete it
if "word" in message.content:
# delete
that makes so much sense i don't understand why i didn't think of that
Have you learnt python basics yet?
.bm
yes but for some reason it just did not come to my head
I still dont know how to get those numbers like <t:197482927:f>
<t:197482927:f>
<t:197482927:R>
It's a timestamp
!e
import time
print(int(time.time()))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1641764974
how do i check if a user has a specific role in an on_message event
<t:1641764974> - <t:1641764974>
message.author.roles returns a list of all roles the user has.
:R
How you check it's up to you.
โข Using a for loop
โข Using discord.utils.get()
โข Using if x in list
<t:1641764974:R>
:R, not R:
<t:1641764974:R>
would the list contain the ids of the roles or the names?
class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
A list of these objects.
You can still do something like
for x in y:
print(f"{x.name} / {x.id}") # Will print role name / role ID
is there a way to make discord bot where when you type to it directly it will answer, without needing the commands like !bot
like where you dm the bot with text without commands
right now i only know how to import bot to servers, but is there a way to just have a bot that you share directly and people dm even when they don't own a server?
right now afaik the only way to get a discord bot from someone is either you have the share link, you own/admin a server and you import it there and then dm it, or you see the discord bot in someone else's server, is there a way to skip that step?
I mean you could just set every letter as a command prefix? That could end poorly however
Not that im aware of. The only way to dm someone is if they're in a mutual guild or you have them friended and you cannot send a friend request to bots
ok
is there a way to make discord bot where when you type to it directly it will answer, without needing the commands like !bot
the TeXit bot seems to do it
there is no bot prompt just dump text to it
through dm
i don't get it
<1641764974:R>
<t:1641764974:R> <t:1641764974:R>
<t:1641764974:R>
<t:1641764974:R>

<t:9991766184:R>
<t:12368712387:R>
It would be nice if discord showed a preview of what it looks like before you send it
dm yourself is the equivalent
What?
oh nvm
How does one DM himself?
sorry i didn't realize it's impossible
Can you make a group and kick the other person from it making it empty?
That would be close to dming yourself
At that point just make a private server lol
A custom tag command is surprisingly easy
possible to make a server then dm it
How do bots create custom commands though?
Do they just use an on_message and filter from there?
custom...commands?
I mean in a nutshell that is a command prefix as well
Commands specific to individual servers
I get what you mean
custom commands would be more difficult with slash though
uh...on message I guess
nvm you mentioned it
MEE6 has some
idk if you can add arguments to your custom command though :pepegigascared:
nah mee6 has only messages etc and some build in things
With slash args would be more plausible.
Premium version of Gaius also has custom commands
๐ณ
pip freeze doesnt work
uh
ig space
Convert to a list and index?
how do you count how many members are in your server
to a custom command
yeah, ty
With or without bots?
how do i get my bot to know that
!d discord.Guild.member_count
property member_count: int```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
I...I....I.....
o
but with custom commands I guess
intellisense is a god send
...??
@bot.listen()
async def on_message(message):
if message == "!foo"
args = []
for word in message.split()
args.append(word)
# extract stuff from json file ig?
with open("commands.json", "r") as f:
loaded = json.load(f)
# shit
# stuff
in command prompt
This is not discord bot related, i recommend a #โ๏ฝhow-to-get-help
custom commands with arguments ig
panda confirm pls ๐ณ
technically it is cause i need it to host my discord bot on 24/7 but ok
ew json
i type print(discord.Guild.member_count)
and i get <property object at 0x0000024E4DB1F830>
any better options?
You need a guild object
Just because you are making a bot with it doesn't mean everything you are doing is related to Discord. What relation does pip have with Discord?
discord.guild.member_count ?
Almost
any ideas of stuff without command
@bot.listen()
async def on_message(message):
return message
would this work?
Custom commands
guild.member_count
That what im about to do
i'm trying to do without command
I mean this won't do anything.
Custom commands are done with a on_message
like for DM the bot since no need command
but i've seen bots do weird things like TeXit seems to be able to just instantly do stuff without command (but it parses every message to see if it has $)
TeXit somehow solves this?
Maybe I just wont add arguments to the custom commands
Agreed
ok i'll try idk
print(guild.member_count)
print(guild.member_count)
NameError: name 'guild' is not defined```
Should I allow a permissions restriction?
I kind of expected this error, i recommend getting to know more about regular Python. This is a pretty complex library to just dive in.
Can I see your current code?
Honestly learning sql was the best decision of my programming life
I literally learnt it in like 2 days
๐ฅณ ๐ฅณ I always tell ppl this.
always
I know right and it saves such a headache.
!pypi pandas
sql+pandas=legend
Me and sql is indeed a good combo.
help me pls, i need an command to send two embeds, HOOW
this was what ive imported
import discord
from discord.ext import tasks, commands
import asyncio
import secure```
(secure is another python file ive made)
What do you got so far?
What's stopping you from just slapping another .send under the first one?
It does not work
Code?
No i'm asking to see your code.
I haven't done anything ๐
But my presence can be quite special
This is all you have so far?
True
what is the most efficient way to keep a bot written in python online 24/7?
see the pins?
thanks and how do i avoid my commands from putting the bot offline
Why would they do that?
they're repeating commands consistently every minute and it crashes the bot eventually
im hosting the bot locally not sure if that's the issue
When it crashes do you get any error or does the process just stop?
How can I ping the author in my ctx.send statement?
ctx.author.mention
thank you
thank you
No, thank you
it's your code, not your pc probably
just the process
i never receive any errors and my wifi has an amazing uptime so it's definitely not that
most likely yeah ill probably have to rewrite the entire thing and make it more efficient
worth it
How can I make it so that the user can input a list separated by commas and once inputted, the code will repeat add_to_guild with each id seperately?
[...]
userid = input("UserID> ")
[...]
def add_to_guild(access_token, guild_id, userid):
url = f"{API_ENDPOINT}/guilds/{guild_id}/members/{userid}"
data = {
"access_token" : access_token,
}
headers = {
"Authorization" : f"Bot {botToken}",
'Content-Type': 'application/json'
}
response = requests.put(url=url, headers=headers, json=data)
print(response.text)
code = exchange_code(excode)['access_token']
[...]
add_to_guild(code, get_guild_id, userid)```
that would be a .txt
Just want to confirm, getting the content of a message returns the content with all the markdown correct?
wdym
reading the content of a text file then for each line you check them using the code you sent above
if you pasted all those guild ids it would be multiple inputs
You should really check out a proper tutorial such as: https://tutorial.vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
alr
Dang just using the raw api huh
Thats what Water_Gazes said 2 xD
I mean Ideally I'd like to keep it all in one file...
do u have any idea if thats possible?
You can do it in one line for all python cares
They were trying to get help with a self botting library 2 days ago and was told it was patched so I'm assuming they're just trying to do it themselves
I assumed as such with this code.
bro before this morning i couldnt remember how to do
x = input("Input your username: ")
print("Hello " + x)
Use f-strings please aaaa
how do u expect me to write a library or whatever on my own xD
With a lot of help
is an f-string something like print(f"Hello {x}")?
Yes
And people create libraries with a lot of other people.
true... but i'd probably go on an alt if i was going on an insane massive selfbot thing
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
And as of now there is not one perfect Discord wrapper.
ig its up to you to make one
ยฏ_(ใ)_/ยฏ
disnake
๐งโโ๏ธ
pff way too much coding lool
oki doki
Yes Andy i'm also too lazy ๐
Making a successor to lefi writing an entire new codebase ๐
I'll use lefi
Don't
Just bought a vps ๐ฅณ
Just insult him and you're good
okay so I have this
def check(reaction, user): return str(reaction.emoji) == ':thumbsup:' try: await bot.wait_for('reaction_add') except asyncio.TimeoutError: await channel.send(':thumbsdown:') else: channel = bot.get_channel(929823408684953642) await channel.send(ctx.author.mention + "Your order has been confirmed.")
but when I react with any emoji, it still works, can I get it so I need to react with the โ emoji?
I... don't know D;
I'm trying to get a basic order confirmation thing, when someone types !order, and it'll send what was ordered to another private chat
then the person (shop keeper) can reply with a โ
or โ to either confirm the order or deny it
I uh... must've fucked up something along the way ๐ค
how can I go along fixing this mess o.o;
okay so I was using code from the docs
do I just use await bot.wait_for like this here?
async def order(ctx,*,message):
await ctx.send("please wait for Becka to confirm your order.")
channel = bot.get_channel(929837471469015090)
await channel.send(str(ctx.author.name) + " ordered " + message)
await bot.wait_for('reaction_add')```
When using try except how can i make it so that it checks if botToken = over 20 characters long ?
len()
Also camelCase 
i figured... but how can it go to except if it's under a 20 chars
You don't. Use an if statement
The point of using a try except block is to catch errors and deal with them
Its a function
where is the :
Also that
how can I use bot_for for confirmation D:
There are some examples in the docs
I've been reading the docs, that's what I've been using as reference but it didn't work
Lets see your code then
async def order(ctx,*,message):
await ctx.send("please wait for Becka to confirm your order.")
channel = bot.get_channel(929837471469015090)
await channel.send(str(ctx.author.name) + " ordered " + message)
def check(reaction, user):
bot.wait_for('reaction_add')```
is what I have rewritten rn
When somebody uses !order, it'll take the message and send it to another chat where the person in charge of the shop (because thats what its being used for) can use the โ reaction to confirm the order
I'm new to programming, whats that?
Would there be a way for me to check the ID of all users who authorised my bot's app (in their authorised apps)?
It's the python module you use to communicate with discord web applications, like nextcord or enhanced-dpy
it should be rather recent, I think
who wants to make discord bots
how can I check it
like collab
Looks to be a discord.py fork, if you installed it with pip it should be the latest version
my point is, pass_context has been deprecated a long time ago, and is no longer required
you may remove it from the order function definition line
as for your initial question;
I remember when i made a reaction roles thing, you had to wait for add reaction and then get the reactions
I used that from something I found that on stack overflow
wait_for expects you to give it a check function,
yeah, you can remove it
alright
In this case the criteria for the check function on the "on_reaction_add" event is if the owner of the reaction just added equals the person in charge of the shop
do you follow so far?
uh I lost you at "just added equals the person in charge of the shop"
You want to make it so only whoever is in charge of the shop can confirm an order by clicking the reaction, yes?
yes
Then, when any reaction is added to the message, your code has to check if whoever added that reaction is the shop's owner.
but I want it to be so they have to react to the message sent to their chat specifically for that
ah okay
I phrased this really weirdly
Ah, I see that command is supposed to only run in a DM, right?
but a different message is sent to a specific channel that the shop's owner can see
yes
and they'll react there
indeed
okay, that ever so slightly complicates things
instead of a dm though, its a "checkout" chat
on the same server
that's just how they wanted it D:
uh, ig
You may store details for a message that has not yet been sent, i'll explain
If you write
message = await ctx.send('Hello!')
You may later on, (in the same command) reference something such as message.id
as long as the message was sent without an error
okay ๐ค
So, when a user adds a reaction our check function has to check for the following:
- This message that this reaction was added to, Is it the correct message in the correct channel?
- This user that reacted, is this the shop's owner?
Get it so far?
uh, I think so yes
So here's what we are going to do first:
message = await channel.send(str(ctx.author.name) + " ordered " + message)```
As I explained earlier, this will save details regarding the specific message later on, so we can use it
okay :o
async def order(ctx,*,message):
await ctx.send("please wait for Becka to confirm your order.")
channel = bot.get_channel(929837471469015090)
message = await channel.send(str(ctx.author.name) + " ordered " + message)
Since I haven't practiced discord.py for a while, i'm going to spin up a test bot just to ensure i'm not saying something wrong. Please hold
alright :o
Sorry for the wait, i just finished doing the above
had to set up a server and everything lol
oof
alright, just quickly testing if this code works, just a bit more
@weary mirage you still there, little man?
yes :D
alright, let's go over the following code together
@bot.command()
async def order(ctx,*,message):
await ctx.send("please wait for Becka to confirm your order.")
channel = bot.get_channel(929892204347015178)
user_id = 847834751230148618
message = await channel.send(str(ctx.author.name) + " ordered " + message)
await message.add_reaction("โ
")
#wait for the user to react, check if the user reacted with the correct emoji, check if the users id equals user_id and check if its the right message
def check(reaction, user):
return user.id == user_id and str(reaction.emoji) == "โ
" and reaction.message.id == message.id
try:
reaction = await bot.wait_for('reaction_add', check=check)
except Exception as e:
await ctx.send("Order failed, please try again.")
else:
await ctx.send("Your order has been placed.")
await channel.send("Order confirmed.")
first, remember to replace the channel ID in the channel = line
same thing for the user_id line, replace that with becka's user ID
um okay
thats some poorly written code.
wrote it for free just to show him how it works, feel free to take over. I have covid and I am tired.
it doesnt follow pep8, and, why are you catching the exception as e if you arent doing anything with it?
regardless, the check function i did checks for the criteria we previously went through, including checking if the added reaction is the proper one.. which I forgot to mention we should do
forgot to raise that
:o
anyway, the check function checks if the user.id of who reacted equals the user_id variable, it checks if it is the correct message and the correct emoji as well
then we have a try block for convenience, and the wait_for line
add raise e
below the order failed line
I got this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
did you remember to change the channel ID
ooh maybe
the channel isnt in the bots cache, perhaps the wrong ID.
and you understand how the code functions?
yus :D
in case the bot goes down while an order is awaiting confirmation
i must make it clear that when the bot goes up again it will not confirm
because of the way wait_for works it isn't persistent between bot restarts
you would need to go through some more code to make that work
should be fine as long as it doesn't go down too often
ah I expected that, though that shouldn't be much of an issue at all
in case it does go down it'll send a "order failed" message
the thing snow talked about earlier, pep8
is a list of rules your code is supposed to follow, a style guide we call it
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
โข PEP 8 document
โข Our PEP 8 song! :notes:
you don't need to follow pep8, but it is reccomended for convenience
and ease of readability for code
would it be possible to have it so it can accept both โ for confirmation and โ for order denial?
yes
ay, I'll look into it :D
thank you for your help, you've been most kind :D
wrench, are there no cases where you think raising a timeout would be necessary?
i'd imagine raising a timeout would be pointless as the shop's owner would probably take a while to confirm the order
owner may be offline when a user attempts to order something
yes, so the shop owner is European in a mostly American server so it's not unlikely for time zones to get in the way there
i see.
alright that's about all I can offer now,
thank you! :D
you're welcome, i shall hibernate in my bed now
happy coding!
@client.command()
async def fga(ctx):
members = ctx.guild.members
for member in members:
print(member)
local variable 'guild' referenced before assignment
guild aint defined idk why
you're trying to make a b4u service?
b4u?
uh no?
discord.py dead but it still working forever ?
Just because it isn't maintained doesn't mean it instantly dies.
l
Is there a way to restrict the roles that pop up when using option 8? Option 8 makes all roles show up - i could assign choices to the option but it would take a really long time, because i want to include a long list of roles .
which thing?
So
I want to make a bot
but i am tryna figure out the message
part
like if you say ;hunt
i dont exactly understand your question
then the bot will reply
a command
a command is just a function
thats the old way of doing things
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

If the guy says ;hunt
yes ik
@slate swan https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
The bot will say someone caught a rabbit
good tutorial which might help you
I'm using pycharm
^
You also hate math?
your indentations are wrong
nice
ofc
anyone?
you're leaving a lot of data for us to figure out
like what you have
what you're trying to do,...
i'm using pycharm
what im trying to do, as i stated here (#discord-bots message) is restrict the roles that pop up when using slash command option 8
!source pypi
Provide information about a specific package from PyPI.
well, you never mentioned slash commands