#discord-bots
1 messages Ā· Page 507 of 1
@client.command()
async def ban(message, member: discord.Member, *, reason=None):
await message.send("hmm")
await member.ban(reason=reason)
await message.send('A member has been banned')
error?
It's not even sending the message
No
theres no such thing as no error
why is there message in the command tho
use ctx for commands
and use certain params for events
def check(reaction, user):
if (str(reaction.emoji == emoji_yes) and client.user != user):
return reaction.users()
reaction, user = await client.wait_for('reaction_add', check=check)
I use this to handle players that react on an embed.
@client.event
async def on_message(ctx, message, member):
for i in range(len(Filter)):
if Filter[i] in message.content:
for j in range(1):
await member.ban(reason='filter')
await message.send('A member has been banned')
WHY is there ctx in an event
on_message only takes message
Ok ok I will remove it
remove member too
If im not mistaken, am i supposed to use on_reaction_remove in the same way and just have another wait_for? This part is puzzling me
@client.event
async def on_message(message, member):
for i in range(len(Filter)):
if Filter[i] in message.content:
for j in range(1):
await member.ban(reason='filter')
await message.send('A member has been banned')
``` I have to go now
How do I do this?
Those hidden messsage thingys.
i'd rather use on_raw_reaction_remove
correction... message.channel.send
message in his function is used as is message object
not context
what??
that would ban the person who triggerd the command
bruh
yeah? we already knew that
okay then why are u sayng member.author?
message.author*
On raw reaction remove? I did try that but couldnt get it to work, all i got it to tell me was that there was no member, users wasnt an option either as it is in reaction_add
@boreal ravine if u say so .-.
yes i said that
its payload for raw_on_reaction_remove
also u need reaction intents to make sure it actually works
the param for it is only payload
.-.
there is intents for almost every thing that cant be stored on a internal cache when its offline
The lib has more but most of them are enabled by default
!d discord.Intents.default
classmethod default()```
A factory method that creates a [`Intents`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents "discord.Intents") with everything enabled except [`presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members").
That feels so weird
I usually just do discord.Intents.All() so I dont have to worry about the ones disabled
Same
So i dont need intents to handle when someone reacts on the embed, but i need them for when someone removes their reaction?
u need them for anytime u use raw events
not just those 2
like raw_on_message_delete or smth
think that's should be the name
There's also reaction intents iirc
there is a whole section for it in the api reference
Hmm, if there is a reaction_add, why isnt there just a reaction_remove
!d discord.Intents.reactions
Whether guild and direct message reaction related events are enabled.
This is a shortcut to set or get both guild_reactions and dm_reactions.
This corresponds to the following events...
Okay so step 1,get all intents so all gateway events are available
Then i need a new async def for the on raw reaction remove with payload as its only parameter
Can i create that locally within the command or does it have to be completely separate
You can use wait_for if you want it to be in a command
Well it is wait_for, so if you can show us what you tried we can help
def check(reaction, user):
if (str(reaction.emoji == emoji_yes) and client.user != user):
return reaction.users()
reaction, user = await client.wait_for('reaction_add', check=check)
I use this to handle players that react on an embed.
And it works, i can update the embed
Check needs to return True / False
check return bool
wait_for will only give you your value back when check returns true
and look str(reaction.emoji == emoji_yes)
that's wrong too
str(reaction.emoji) == emoji_yes
show what you did
Does anyone know how to set an activity status?
def check(reaction, user) :
if(str(reaction.emoji) == emoji_yes and client.user! = user):
return True
while True:
reaction, user = await client.wait_for('reaction_add', check=check)
Do you guys know what library do you need for activity command
you don't need a library
!d discord.Activity
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
⢠[`Game`](https://discordpy.readthedocs.io/en/master/api.html#discord.Game "discord.Game")
⢠[`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
I dont understand the check, it works when i return reaction.users()
client = commands.Bot(command_prefix='.')
Filter = ['giant', 'hi', 'hello', 'monke', 'bye', 'balance']
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle, activity=discord.Game('Hello there!!'))
print('Bot is ready')
print('Bot is now Online')
@client.event
async def on_message(message, member):
for i in range(len(Filter)):
if Filter[i] in message.content:
for j in range(1):
await member.ban(reason='filter')
await message.send('A member has been banned')
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send('A member has been Kicked')
@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
await ctx.send("hmm")
await member.ban(reason=reason)
await ctx.send('A member has been banned')
@client.command()
async def setdelay(ctx, seconds: int):
await ctx.channel.edit(slowmode_delay=seconds)
await ctx.send(f"Set the slowmode delay in this channel to {seconds} seconds!")
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
@client.command()
async def delete(ctx, message):
await ctx.channel.delete(message)
No command is working
Not a single one
add py await client.process_commands(message) at the end of the on_message event
Ok lemme try
That's truthy. Fix your indentation and return a default value..
Im on a scuffed setup where i can only have discord on my phone, any indentation or misspelling is from me manually typing it in my phone. But i did try returning true and false after the if statement. It didnt work
Returning true or false in the check*
hey
there is a problem
when I run my code in VS Code
it's working fine
but when I run my code on replit it starts giving me errors
This shows error
subreddit=reddit.subreddit("memes")
top=subreddit.top(Limit= 5)
for submission in top:
print(submission.title)```
shows no limit found
shld i use praw or async praw
async if you can
you must
So i have my bot running some moviepy things, some video converting things and general tools, when these finish running, im left with quite a high memory usage, is there a way to clear this?
alright
Hi, im using async praw to get memes and it works...
but its too slow what can i do?
Raw GET requests with aiohttp
that sounds like a memory leak
well its probably because the scripts that im using are meant to run once then terminate. Can i clear them out of my bot?
idk how to do tht, isnt praw easier?
without a subprocess if at all possible
Here is my code
@commands.command(aliases=['Meme'])
async def meme(self,ctx):
subreddit=await reddit.subreddit("memes")
all_subs = []
top=subreddit.top(limit= 50)
async for submission in top:
all_subs.append(submission)
random_sub=random.choice(all_subs)
name=random_sub.title
url=random_sub.url
em=discord.Embed(title=name,color=discord.Color.random())
em.set_image(url=url)
await ctx.send(embed=em)```
you just want to get one meme?
It should get terminated the point the program ends, is there something which is keeping it alive
I dont think so
import gc
then gc.collect()? or something else?
Yeah
No
just it just get yionked
It unloads the weakx and other objects with 0 refs from the memory
ok cool, i dont want it saved.
It doesn't work like that
i think it helped a little but im not sure if thats just a placebo
Hmm yeah idk then
hi
thanks anyway
np
Please do not request help with NSFW services here
hey so i am trying to make a search command for my bot of a site using selenium but the site is not having a search url site and search button its just search website and you have type and you will get result
there are the codes
driver = webdriver.Chrome()
driver.get('link/search')
searchbox = driver.find_element_by_xpath('/html/body/div/div/div/div[7]/nav/div/div[3]/div/div[1]/input')
this ok?
idk what to do anymore because selenium docs have search.button
It's alright. I would suggest learning this on a site more appropriate then applying it elsewhere, so you can actually get decent help
meaning I cannot request help here?
You can, but without linking or providing any evidence of what site (to comply with our rules about sfw content). And by doing that, you're likely to have issues actually solving your issue.
I see
I want to make search command for my discord of a site using selenium
(site doesnt have search result url site or search.button)
codes:
driver = webdriver.Chrome()
driver.get('link/search')
searchbox = driver.find_element_by_xpath('/html/body/div/div/div/div[7]/nav/div/div[3]/div/div[1]/input')
now?
Uhh That's not related to discord bots so ig best place to ask wud be #web-development
i want to make the search command for my discord bot
sorry I forgot to mention that
But still, your chances of getting help here regarding non dbot topics (like that) is very low, you should ask in #web-development
hm okay
thank you
np
Does anyone definitively know if wait_for can handle on_reaction_remove?
1 random meme
why are you looking through the top 50 then
is there a way to automatically get the missing permission required by the bot?
in on_command_error
the bot missing perms or you
bot
!d discord.ext.commands.BotMissingPermissions
exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)```
Exception raised when the botās member lacks permissions to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
in commands.botmissingpermission, how do i get the Permission that is required?
just send the error
the perm name
hm
just a second , ill ping you when i reply
sure
its error.missing_perms , it will return a list
can a bot owner use commands for which he does not have guild permission?
if there is has_persmissions check - no
eh
def owner_or_permissions(**perms):
original = commands.has_permissions(**perms).predicate
async def extended_check(ctx):
if ctx.guild is None:
return False
return bot.owner_id == ctx.author.id or await original(ctx)
return commands.check(extended_check)```
like this @waxen granite
there is more examples in next message @waxen granite
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
How do I delete the authors message?
error.missing_permissions* . It was changed in 2.0 iirc
ctx.message.delete
it always was missing_permissions
Thank Youu
Oh okay. Could be I was wrong
Hey guys,
I am making a discord.py bot. The problem is that, whenever I run it, an error comes up. The error is -
SyntaxError- await outside function
not in 1.7.3
oh , i was not aware about that since i shifted to hikari
Thought so
Ah, okay
you have await something in def function or outside the function
outside the function
await can be called only in async def function.
ok
that's python syntax
Question: Is there a BOT version of this?? member: discord.Member
or will this do for all
what do you mean
bot version?
you want the user to mention a bot only?
you can use py if not member.bot: return
before_invoke would do I think
Hm
inside the command
Okay thank you
Hey guys, Iām trying to make like a queue of some sorts. So players can use !q, and then the q will remember the player and become 1/6, then another player will q and it will become 2/6.. etc.
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
F
what are you trying to do?
So I want to add a temprole
can you be more specific about the term 'temprole'
which gets removed after some time?
for how long? if its for a short time py asyncio.sleep() will work
you would be using a database
a db, with tasks.loop
ohh
to store time when to remove the role
I don't have a data base
make one
then get one
its not that hard
How do I make one?
use aiosqlite probably
wtf
you dont make a db, you use one

!h discord.ext.commands.Command.call
Need to sleep
they understand the point, dont they?
dunder methods arent documented
they are?
oh
Any ideas guys iām kinda struggling, donāt know where to find help.
!d discord.ext.commands.Command.call
await __call__(context, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls the internal callback that the command holds.
Note
This bypasses all mechanisms ā including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.
New in version 1.3.
Hi I have a bot that I'm using to change permissions for a role when a channel is created. However my bot runs into forbidden 403 error. When I explicitly enable the manage permissions for everyone role my bot is able to execute the command (I'm using a listener for channel edits as well). My bot has manage channel permissions serverwide and I'm using discord.py.
Well 403 literally means the bot cannot do the thing you requested
it doesnt have the perms to do it
yes I know but it does have the permissions for it
but i get discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
It discord returns 403 it literally says no permission, canāt do it at all, no matter what you think it can do
when I enable manage permissions explicitly it works
I know that
but it shouldn't
Well that is obviously needed to change channel permissions
is that available for the role permissions?
def check(reaction, user):
Ā Ā Ā Ā Ā return str(reaction.emoji) == emoji_yes and client.user != user
while True:
Ā Ā Ā Ā Ā Ā reaction, user = await client.wait_for('reaction_add', check=check)
Ā Ā Ā Ā Ā reaction, user = await client.wait_for('on_reaction_remove',
check=check)
When the last line is added everything stops working. Anyone that knows the proper way to make both actions work?
on the roles page
Manage roles is required to edit roles of a channel
You donāt use wait_for them but a proper event
ah i see thanks
is there an event that triggers when the bot get shutdown/killed?
you can just dispatch your own event in bot.close
on_disconnect, keep in mind that the bot is already disconnected and you will NOT be able to send messages to discord anymore
ok thx š
@valid niche its all being handled inside of a command
it can be called during a reconnect
definetly not a domain
What VPS do you use to host BOTs?
im local hosting my bot as of rn
trying to find a good but cheap vps
idk tbh
Public server use
F
Pebble seems nice as I can run my code there and everything is online. But they recommend not using that
I need to talk to some experts here
Pebble is $3 a month
is there a way to make it a prefix if the bot gets mentioned
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host API:443 ssl:True [SSLCertVerificationError: (1, '[SSL:
CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123)')]
Yo anyone here knows about this error when I try to connect to my API? (aiohttp)
It worked till yesterday and is still working on my main bot
how do i get the member.name from role.members?
use a loop
Maybe this will help
#discord-bots message
member.name for member in role.members like this?
its a list you can iterate through it
Yea I was seeing that only haha. Thanks!
sure
<generator object Fun.list.<locals>.<genexpr> at 0x000001DFF262D900> gives this
list() it
elif option.lower() == "bt": role = discord.utils.get(guild.roles, name = "BankTime") await ctx.send(member.name for member in role.members)
or just directly [member.name for member in role.members]
ok
no
or wait
would that work?
no, and yes
no, it will print generator object
use [] instead of (). () will return a generator
','.join(member.name for member in role.members) it works
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
Why is clear command not working
Errors?
why do u always not have errors?
typehint the amount parameter with int
I am not checking rn but there were not errors before
you should use a list comp instead of a generator
list comp is faster
Are you just telling me the error
no.
what is list comp?
list comprehension
this one
But I didn't understand
oh
Well I just tested the command
is there a link for it?
It works. So how did urs not work?
Ya that was fast
Idk This is happening maybe after I have hosted it
Lemme check again
It's not working
And That happened after I hosted my bot on replit.com
replit is not even a hosting service
@tropic briar did u restart ur bot
broken indent?
nope
they said they didnt get any errors
@client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)```
his indents big tho
2 times lol
yes and python is quite strict with indents
probably an 8 space indent 
it isnt
an indent problem
Probably
- He didnt restart the bot
- Permissions
in on_guild_role_update , how can i log the permission that was updated?
after.permissions I think
do i need to do the difference of before and after perms?
arguments given will be strings but channel.purge only takes in integers not strings so typehint the amount parameter with int
or just afterperms will work?
Anybody got on_member_join channel msg code pls, that works in py pls?
AttributeError: 'NoneType' object has no attribute 'is_playing'
just make your own
Tried that, but only works on dm Join.
When members join, it sends a welcome msg lol
selfbot 
the trick is to blackmail discord staff members to add your bot to a group chat
š¤£
ez

@visual islandwhat about the text channel perms?
voice_client = ctx.guild.voice_client
try:
await voice.connect()
except:
pass
if voice_client.is_playing():
do something```
Ya I did
What is wrong?
PS C:\Users\AntiWTap> & C:/Users/AntiWTap/AppData/Local/Programs/Python/Python39/python.exe c:/Users/AntiWTap/Desktop/Bot.py
Traceback (most recent call last):
File "c:\Users\AntiWTap\Desktop\Bot.py", line 118, in <module>
async def warn(ctx, member : discord.Member, *, reason=None):
AttributeError: 'Command' object has no attribute 'Member'
PS C:\Users\AntiWTap>
@bot.command()
async def warn(ctx, member : discord.Member, *, reason=None):
if ctx.author.permissions_in(ctx.channel).ban_members:
embed=discord.Embed(title="Warned", description=f"Du hast {member} gewarnt", color=0xff6600)
await ctx.send(embed=embed)
user = await bot.fetch_user(870241231555399692)
await user.send(f"[{member}] wurde von [{ctx.author}] wegen [{reason}] gewarnt")
Np I will try to fix it on my own
why doesn't it work
.overwrites maybe
@slate swan pls help
is vultr okay for hosting?
can you show your file tree?
embed.add_field(name = "old perms", value=before.permissions) embed.add_field(name = "new perms", value=after.permissions) whats wrong?
what do you mean by tree
voice_client = ctx.guild.voice_client
try:
await voice.connect()
except:
pass
if voice_client.is_playing():
do something```
AttributeError: 'NoneType' object has no attribute 'is_playing'
your files
ok
just put the if statement inside try block
why?
you should do from cogs.server_setup import ...
oh
@visual island
hm actually, it should work. How if you put your voice_client = ... after the except block?
i will try
@visual island
.pair it?
Don't use globals.
why not
before.permissions.pair?
!globals
mhm
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
oh
AttributeError: 'Permissions' object has no attribute 'pair'
but how do i fix this
try discord.Permissions(after.permissions.value)
where did you use it
use what?
the var
same as before
bruh wait
this is in server_setup.py
.all it maybe?
!botvar then
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
oh
embed.add_field(name = "old perms", value=discord.Permissions(before.permissions.all))
File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\permissions.py", line 99, in init
raise TypeError('Expected int parameter, received %s instead.' % permissions.class.name)
TypeError: Expected int parameter, received method instead.
noo, revert it to the first code
this one
embed.add_field(name = "old perms", value=before.permissions.all) embed.add_field(name = "new perms", value=after.permissions.all) like this then?
bruhhh
if i add/remove 1 or more perms, i want only those perms to be listed
I think you should convert it to PermissionsOverwrite
to?
so i got to list all the perms seperately?
mm, maybe? not sure
you can iterate through a Permissions object
dpy 2.0a has support for lists and buttons?
and slash commands too?
if not what lib do you guys prefer for the above
how do i check if the perm is True or False?
yes, but not slash commands
oh then what do you prefer for slash
if perm: or if not perm:
Bruh
How i can send file
Is it python a game, or food?
?
?
programming language
Thanks.
!file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
snake.
haha, im joke, i know what python is
I know 
if before.permissions != after.permissions:
diff = list(set(after.permissions).difference(set(before.permissions)))
for changed_perm in diff:
if changed_perm[1] == True:
embed.add_field(name = "Added Permission(s):", value = changed_perm[0], inline = False)
elif changed_perm[1] == False:
embed.add_field(name = "Removed Permission(s):", value = changed_perm[0], inline = False)
await logChannel.send(embed = embed)```
when i add multiple perms it add multiple fields in the embed, how do i add them under a single field?
how do change the for line
idk
!join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
FFmpegPCMAudio how to install
'\n'.join(str(changed_perm[0]) for changed_perm[0] in changed_perm) like this bro?
What's changed_perm?
.
the perm i add/remove
cant you just do for perm, value in diff
and check value?
and send perm if value is True
for perm, value in diff:
if value == True:
embed.add_field(name = "Added Permission(s):", value = perm, inline = False)
elif value == False:
embed.add_field(name = "Removed Permission(s):", value = perm, inline = False)```
@hasty ironlike this?
sure
does it work?
also you dont need to do list(...)
diff = list(set(after.permissions).difference(set(before.permissions))) here
then?
a set is an iterable
like a list
diff = set(after.permissions).difference(set(before.permissions)) is enough
hey i need help here
well yes?
@bot.event
async def on_message(message):
f = open("badwords.txt" , "r")
liness = f.read()
if message.content.lower() in liness:
await message.delete()
await message.channel.send("You Cant Say That")
await bot.process_commands(message)```
read your code
this code works but if i say a word in the badwords file it only remove the msg that have only the word
make 2 lists, one for the removed permissions and the other for the added
and then add_field and join the list
Isn't that what u want?
also you arent closing the file which is bad
lets say the badwrods file have mom word there if someone type i love mom it wont remove it it only work if i say mom
Ah
like list1 = []
list2 = []?
yes, and if value is True append perm to list1, otherwise append to list2
if any(word for word in lines if message.content.lower() == word): should work
what happen if i didnt close it it take more storage ? and make the bot more lagy right
where i should but this ?
remove the if msg content.lower right
As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually
Yea
and replace it with that one
okay but if i close it will it still work ?
yes?
use the context manager
with open(...) as file:
that will automatically close the file for you
why is this not displaying the image?
embed = discord.Embed(title="Drake Hotline Bling", color=ctx.message.author.color) embed.set_image(url="attachment://Drake Hotline Bling.jpg")
indentation
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='š„'),
discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='š©'),
discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='š¦')
]
super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')
class DropdownView(discord.ui.View):
def __init__(self, ctx):
super().__init__()
self.ctx = ctx
# Adds the dropdown to our view object.
self.add_item(Dropdown())
async def interaction_check(self, interaction: discord.Interaction) -> bool:
if interaction.user.id != self.ctx.author.id:
await interaction.response.send_message(
embed=discord.Embed(description=f"{utily.error} Sorry, you can't use this! This interaction belongs to {self.ctx.author.mention}.",color=0xffffff), ephemeral=True)
return False
return True
@commands.command()
async def drop(self, ctx):
await ctx.send('Pick your favourite colour:', view=DropdownView())
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/owner.py", line 208, in drop
await ctx.send('Pick your favourite colour:', view=DropdownView())
TypeError: __init__() missing 1 required positional argument: 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/jishaku/features/invocation.py", line 146, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'ctx'
this one doesnt work
indentation
Any error?
he didnt indent š , i told him twice before
no no no lkook
Hey @hollow mortar! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
can u give an example? i am not able to do it
i closed my eyes and didnt see
@bot.event
async def on_message(message):
f = open("badwords.txt" , "r")
liness = f.read()
if any(word for word in liness if message.content.lower() == word):
await message.delete()
await message.channel.send("You Cant Say That")
await bot.process_commands(message)```
haha lmao i restarted it now
look this one doesnt work
message.delete doesnt work and also if u write any message it will be deleted
i tried using txt files to store words too, it wont work
no it work
umm okay š
but the only problem with me is my old code it only remove words when you type it single without anything with them
look any try by your self
i see
@bot.event
async def on_message(message):
f = open("badwords.txt" , "r")
liness = f.read()
if message.content.lower() in liness:
await message.delete()
await message.channel.send("You Cant Say That")
await bot.process_commands(message)
this one work but like this
so basically im making a discord bot that will say random shit like "cheese dick" and i have everything setup but idk what to put here:
await message.channel.send("")
lets say mom word in one of the badwords line if you type youur mom it doesnt get deleted it only delete when type mom
use random module for different words
did u try to print liness
i explained pretty clearly, have 2 lists, when iterating through diff check if value is True, if it is append param to the first list and if it is false append param to the second list, after the for loop you're going to add two fields which are the removed and added permissions, lets take the first list being the added and the second list being the removed ones, you're going to do embed.add_field(name="Added Permission(s):", value=", ".join(first_list), inline=False) and embed.add_field(name="Removed Permission(s):", value=", ".join(second_list), inline=False)
`import discord
import os
import random
with open("fade.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
print(random.choice(words))
with open("fade.txt", "r") as file:
data = file.read()
words = data.split()
word_pos = random.randint(0, len(words)-1)
print("Position:", word_pos)
print("Word at position:", words[word_pos])
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send("")
client.run(os.environ['TOKEN'])`
trying now
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
okee
import os
import random
with open("fade.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
print(random.choice(words))
with open("fade.txt", "r") as file:
data = file.read()
words = data.split()
word_pos = random.randint(0, len(words)-1)
print("Position:", word_pos)
print("Word at position:", words[word_pos])
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send("")
client.run(os.environ['TOKEN'])```
it give you the words in badwords.txt
any extra spaces?
try using message.channe.purge once
also
@hollow mortar split the words to make a list too
i didnt understand anything from you
ok so, first read the file and then split the string to make it into a list
i have the words in the file line by line same as this
then try to use string comprehension
i understood
i cant use it like line by line every word ?
and im not good at lists and that shit
list1 = []
list2 = []
if before.permissions != after.permissions:
diff = set(after.permissions).difference(set(before.permissions))
for perm, value in diff:
if value == True:
list1.append(perm)
embed.add_field(name = "Added Permission(s):", value ='\n'.join(list1), inline = False)
else:
list2.append(perm)
embed.add_field(name = "Removed Permission(s):", value ='\n'.join(list2), inline = False)
await logChannel.send(embed = embed)``` is this correct?
u can, but i am saying that split the string
how ?
why are you still adding the fields?
i said after the for loop add them
list1 = []
list2 = []
if before.permissions != after.permissions:
diff = set(after.permissions).difference(set(before.permissions))
for perm, value in diff:
if value == True:
list1.append(perm)
else:
list2.append(perm)
embed.add_field(name = "Added Permission(s):", value ='\n'.join(list1), inline = False)
embed.add_field(name = "Removed Permission(s):", value ='\n'.join(list2), inline = False)
await logChannel.send(embed = embed)```
ok sorry :#
works thanks
but
when i only add perm or only remove perms it doesnt work
i did
async def on_timeout(self) -> None:
self.children[0].disabled = True
self.children[0].label = 'Closed'
await self.message.edit(view=self)
``` it did not work
why isnt this displaying the image š„²
embed = discord.Embed(title="Drake Hotline Bling", color=ctx.message.author.color)
embed.set_image(url="attachment://Drake Hotline Bling.jpg")
since there is no value for other field @hasty iron
to disable a dropdown
im trying to make a bot that says either of these things but its saying all of the phrases
i already did set it up so it would be random but its not saying the random words
import os
import random
with open("fade.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
print(random.choice(words))
with open("fade.txt", "r") as file:
data = file.read()
words = data.split()
word_pos = random.randint(0, len(words)-1)
print("Position:", word_pos)
print("Word at position:", words[word_pos])
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi'):
await message.channel.send(words)
client.run(os.environ['TOKEN'])```
await message.channel.send(", ".join(words))
Yea
async def on_timeout(self) -> None:
self.children[0].disabled = True
self.children[0].label = 'Closed'
await self.message.edit(view=self)
```its not disabling the dropdown
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3.10/library/exceptions.html#IndexError "IndexError").
Hi
thats already in the code
How to make command classes
where is random.choice(words) like you claim in your code?
thatll just print it
and what do you want to do?
make it a variable or put it in your send method
then do it as await ctx.send(random.choice(words))
or word = random.choice(words)
await ctx.send(word)
async def on_timeout(self) -> None:
self.children[0].disabled = True
self.children[0].label = 'Closed'
await self.message.edit(view=self)
```its not disabling the dropdown
Hey
if u did that, just await message.channel.send(word)
plus there is an extra ) at the end of your code
@bot.command()
async def tts(ctx,*, text:str):
global gTTS
language = "es-us"
user = ctx.author
speech = gTTS(text=text,lang=language,slow=False)
speech.save("audio.mp3")
channel = user.voice.channel
print(channel)
vc = await channel.connect()
print(vc)
sc = discord.FFmpegPCMAudio("audio.mp3")
voi = vc.play(sc)
voi.start()``````
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found.
How to fix?
Import ffmpeg
just fix your indentation
@bot.command()
async def tts(ctx,*, text:str):
global gTTS
language = "es-us"
user = ctx.author
speech = gTTS(text=text,lang=language,slow=False)
speech.save("audio.mp3")
channel = user.voice.channel
print(channel)
vc = await channel.connect()
print(vc)
sc = discord.FFmpegPCMAudio("audio.mp3")
voi = vc.play(sc)
voi.start()```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found.
How to fix?@slate swan
Install ffmpeg and import
this should work fine maybe
import discord
import os
import random
with open("fade.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
print(random.choice(words))
with open("fade.txt", "r") as file:
data = file.read()
words = data.split()
word_pos = random.randint(0, len(words)-1)
print("Position:", word_pos)
print("Word at position:", words[word_pos])
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
word = random.choice(words)
if message.content.startswith('hi'):
await message.channel.send(words)
client.run(os.environ['TOKEN'])
@slate swan py from discord import FFmpegPCMAudio
did u installed?
i tried
Pip ?
Yes
Indentation *
@bot.event
async def on_message(message):
counter = 0
with open("spam.txt","r+") as file:
for lines in file:
if lines.strip("/n") == str(message.author.id):
counter+=1
file.writelines(f"{str(message.author.id)}/n")
if counter > 5:
await message.guild
await message.author.add_role(##id of my role )```
Ohh idk what then
i have this code i dont think it will work cuz the await message.author.add_role
and help
import discord
import os
import random
with open("fade.txt", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
print(random.choice(words))
with open("fade.txt", "r") as file:
data = file.read()
words = data.split()
word_pos = random.randint(0, len(words)-1)
print("Position:", word_pos)
print("Word at position:", words[word_pos])
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith('hi'):
word = random.choice(words)
await message.channel.send(word)
client.run(os.environ['TOKEN'])
try this maybe, plus u should learn basic python before attempting to make a bot
nice
dope
hey any idea how to fix this problem and if it can be fixed
i have 2 on_message events
the bot can make the both work only 1 that can work
any idea how to make them both work ?
okai thanks alot
np
please learn basic python before asking hundreds of simple questions
pls tell me i forgot when i am calling a function it is giving some function codes i want to take the prefix which im returning
I don't understand what you're asking?
like i have
load prefix is a func
if youre trying to use a function then you need () after the name
is this in a command?
it'd be load_prefix()
How to install ffmpeg in phone
i learnt db today i saw yt he also didn't put ()
is it in a command
no
then where
you can put help above async def
yes
@bot.command()
""" Help String """
async def c(ctx):
# lol
this?
hello guys I know how to send DM with events can someone tell me how to send it with commands?
ctx.author.send()
^
thnnk you
u need to call it
how to show what the function is returning?
load_prefix()
what this will do a yt person did this so i also did
this will call the function
Confused to as how you will even pass the message parameter for your function
As where it is has no access to one
?
ii used ()
Your function clearly shows two parameters
but now i can pass parameters
Bot and message
yes and i cannot pass them
so what should i do :/
i cannot convert this ??
<function load_prefix at that integer>
load_prefix(<discord.Message>)
to what the function is returning
?
Your thinking about this wrong, if you think about it the help command gets fired with the prefix used
There you would set the prefix message
oh wait, a Bot arg as well
but it is not in any command
?
bot.command_prefix(message)
is there any way to get a prefix of bot in different servers?
yes that's what im saying
On_member_join command is not working why ?
:/
can u show the whole code?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Burra
did u enable them?
just i started database today
whole code-
Hmm
so i trying to make custom prefix
Is it for tronex
why not send it in text instead of screenshot
and this
you must have a discord.Message
to target some lines too :/
where?
you better do that inside the command so you'd use ctx.message
hmm
what if i get the guild id in on_ready
it will give guild id?
of each servers?
:/
um seems like it's your function for command_prefix
It can not be asynchronous.
like
guild_ids = {}
@bot.event
async def on_ready()
guild_ids[message.guild.id] = "prefix"
```??
yes
message isn't defined
hmm
How many server it is now running
you can cache prefix in json btw
pls we will talk later
K
bot.cached_prefixes[guild.id] = "prefix"
in the get_prefix
if the server isn't cached
what is this?
cached_prefixes is a dict you'll make
hi
this much is only related with it :/
...
i heard some where that we can change <function load_prefix at 0x0000029B7F9DE3A0>
so i have a discord music bot which i am hosting at heroku but in the logs it says "no such file directory" the name of the file is correct
can we ?
aaaaaaaaaaaaa
oh okay
how do you send a file through a discord reply from button click
:/
TypeError: reply() got an unexpected keyword argument 'file'
can I really not send a file through replies
Do i need to make a sep folder with song files so that the repo be cleaned?
@buttons.click
async def first_but(ctx):
A = Scholarship()
A.get_site_info(A.ordered_scholarship_set_3x5[2][2])
for _ in range(3):
await ctx.reply(file=discord.File(f"{_ + 1}.png"))
what library is that?
@bot.command(name='asd')
async def name(ctx) -> None:
await buttons.send(
content="something here", channel = ctx.channel.id, components = [
ActionRow([
Button(
style = ButtonType().Primary,
label = "asdasdasd",
custom_id = "first_but",
emoji = {"name": "mage",
"id": "625891304081063986"
}
),
will it work? because in pycharm i did the same by making a sep sound folder but the it showed no such file or directory
@neon cradle
I put the folder in the project folder
along with ffmpeg.exe files and the other venv
oh like
C:/desktop/bot/sounds
show the cwd listing
C:\Users\Admin\Desktop\sauceyy
cwd listing? sorry i dont know about that
current working directory
there are the codes
@bot.command()
async def test(ctx: commands.Context):
voice_channel: discord.VoiceChannel = ctx.author.voice.channel
print(voice_channel.name)
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio("cumming.mp3"))
while vc.is_playing():
time.sleep(.1)
await vc.disconnect()
await ctx.send('blah')
oh
so i put it in the mid of the codes?
yes
alr
pls help i just want a value on calling a function :/
thank you so much
that will block the whole bot
time.sleep is blocking
use asyncio.sleep
or you could use a Future, and set_result in the after argument
someone can help me ?
cuz it is outside the function too
i just want to get the servers prefix
you dont need global when something is outside your function
??? what??
you use fetchrow or whatever for that, not globals
ping = await collection.find_one({'user_id': str(), 'reaction': str()}) Lets say thats a certain line to check if its in the db I need to able to check for the user_id in the message.content and then get the reaction which is stored in the same document
Considering this is a example of a document
Image
So I need to able to have something in user_id: str(xyz) and something in reaction: str(xyz)
Your problem still not solve
no :/
Hmm
The prefix that was used to invoke the command.
await ctx.send(ctx.prefix) ??
what..
how to use that?
ok so why are you doing f'{load_prefix}...'
and this variables below every commands
that wont send the prefix
it will send the repr of the function
thats why i said to use ctx.prefix
since you wont have to call anything
better discord š
no
no š
Why bot send offline if i have status online? py @bot.command() async def test(ctx): await ctx.send(ctx.author.status)
LMAO
how do i get the bot to test whether or not someone has reacted to it's message?
shiiii
reaction?
Message.reactions?
intents
with this bot if you use a command it shows a reaction below its message, and if you click it it deletes the message
how does that work?
this bot as in @unkempt canyon
hey so ik i am asking this after 20 mins
but the file directory is it has to be the one in pc or github?
i am making a discord music bot
and what does github have to do with that?
Hi, can I ask how do I make the code so that my discord bot doesn't delete 14-day-old messages?
let me explain the full issue pls
i have almost like 30 sound files i want them to be organized thats why i put the sound files in a folder named sounds so according to zimblox he said to put r'file directory' so i have to put the directory of the project folder of my pc or github?
because when i put the directory of github bot joins and leave
i dont get why are you putting github into your sentences
what does github do to you?
i have to use github to host my discord bot
have you use heroku? or heard about it
i have
yes
and its bad for discord bots
so you have to connect github with heroku
my bot doesnt have much a LOT commands so its ok for me
and i will see if any problems arise in future
dont use it
why?
-
Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
-
Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
-
Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
-
Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
-
Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
So I have this command which is giving me two errors.```py
@commands.command(description = "Lets users locate a specfic suggestion via it's message ID or link.", usage = "sug <[messsage link|ID] | [phrase]>", aliases = ["find", "find-sug", "search", "search-sug"])
async def test_sug(self, ctx, search: Union[discord.Message, str]):
suggestions = self.bot.get_channel(id = self.suggestions)
if search is discord.Message:
await ctx.reply(embed = search.embeds[0].copy(),)
else:
with ctx.typing():
matches = 0
output = " "
messages = await suggestions.history(limit = None, before = None, after = None, around = None, oldest_first = None).flatten()
for message in messages:
if search in message.embeds[0].description:
matches += 1
output = (output + f"{message.embeds[0].title()}")
embed = Embed(title = f"I found `{matches}` suggestions matching `{search}`.", description = output)
await ctx.reply(embed = embed)```I am getting the following error if I provide a msg link```py
ERROR:cogs.error_handler:TypeError: 'in <string>' requires string as left operand, not Message (In test_sug)
Traceback:
File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/modmail/cogs/some_commands.py", line 24, in test_sug
if search in message.embeds[0].description:and this error if i provide a phrasepy
ERROR:cogs.error_handler:IndexError: list index out of range (In test_sug)
Traceback:
File "/home/snowyjaguar/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/modmail/cogs/some_commands.py", line 24, in test_sug
if search in message.embeds[0].description:```
if search is discord.Message: this wont work
!e ```py
class Obj:
pass
obj = Obj()
print(obj is Obj)
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
False
should it be py search == discord.Messagethen
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3.10/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3.10/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union).
or you could do if type(obj) is class:
so it's py if isinstance(search, discord.Message):i think
yes
what is better hosting?
and also this if search in message.embeds[0].description, search is a Message object and description is a string, ofc this wouldnt work
well I have the if statement checking if the input is a union of discord.Message or str, does this mean it needs to be Union[str, discord.Message] bc that's not working, also the commands accepting msg links but not msg ID's, the link/ID i'm giving it is for a message not in the ctx channel
presence intent
i have
i have
Hi guys, I have a problem, I want that when a command is invoked the bot sends in a special channel which command the user used.
I did the command, except that with client get channel does not someone know how to help me?
here the code: @ client.command () async def slowmode (ctx, seconds: int): await ctx.channel.edit (slowmode_delay = seconds) await ctx.send (f "I have set the slowmode in this channel for {seconds} seconds!") await ctx.send (f "Command log <@ {ctx.author.mention}> used the slowmode command in <# {ctx.channel.id}> ") channel = client.get_channel (mychannel)
@bot.command()
async def test(ctx):
await ctx.send(ctx.author.status)``` Bot send offline why?
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="g!", help_command = None, intents=intents)
does anyone knows where i can learn discord py with some examples?
do intents = discord.Intents.all() to enable them all
the docs
i'm reading it but i cant understands exactly what it is
for example, when_mentioned()
you'd need python knowledge to understand it
need some help
you don't have to do that after each command
there's on_command(ctx) event
and on_command_completion if no errors in the command
that's what you're looking for
I want that when a user uses a command it causes a log in a specific channel of what he did, but as already said client get channel does not go

it looks like you're doing that after each command in here
what's the problem
I am making a chat bot and a server utility bot
I wanna know how to keep it online 24Ć7
@bot.command('help')
async def help(ctx=None, message=None):
embed = discord.Embed(
title='Help Menu:',
description=('This is the help menu, where you can see the list of commands the bot can use.'), colour=0x1fc2ff)
embed.add_field(name="__**Fun Commands:**__", value="** **", inline=False)
embed.add_field(name=";diceroll", value="** **", inline=True)
embed.add_field(name=";ping", value="** **", inline=True)
embed.add_field(name=";coinflip", value="** **", inline=True)
embed.add_field(name=";8ball [question]", value="** **", inline=True)
await ctx.send(embed=embed)
why wont this command work?
you could just do something like this and it'll work for all commands ```py
@bot.event
async def on_command_completion(ctx):
print("{} used {}".format(ctx.author, ctx.command.name))
lemme try
buy a vps
that's the only way
anyone there?
i need help in making a leave a message cmd in my bot
recommend a better one thn
i saw that
lmao too
same
i already mentioned that
guess what
Hmm
then?
self declarence by u
help
can u help me?
:/
i need help in making a leave a message cmd in my bot
leave message command, whats that?
it works, but I want the log to be sent in a dedicated channel not in the terminal.
error?
no error, it just wont work
just get the channel and send the message there
no error pops up when i run the command, no red line under the code, nothing
i tried with get channel client but it doesn't work
i dont know how to do taht
*that
how it doesn't work
error?
if I enter the channel, and I try to use a command in another channel the bot sends. the message in the channel in which I ran the command and not in the one requested by me
means if someone is inactive type cmd (prefix+person+ pop up message)
thn the next time the mentioned person sends a text the pop up message will be sent from the bot
ah i got it, show the code you did
i understand now and idk how that works
maybe you used ctx.send instead of TextChannel.send
async def on_command_completion(ctx):
await ctx.send("{} used {}".format(ctx.author, ctx.command.name))
client.get_channel(mychannel)

