#discord-bots
1 messages · Page 219 of 1
Oh I can only have one on_message for my entire bot?
Or is this the issue cogs would solve?
yes, either that or use listeners
@bot.listen() instead of @bot.event
ahhhhh
Ok let me verify the functionality with that but I think it would be best for me to just move everything into cogs as we discussed
ok
!d discord.Client.user
property user```
Represents the connected client. `None` if not logged in.
bot.user.mentioned_in
Weird, I swore I had tried that and it gave me a different error yesterday, but it wasn't using "listen" so lets seeeee
Success!
Now to move everything to cogs 🙂
umm can anyone tell is it important to learn python first to learn discord.py??
yes it is
umm can i cant just hop on to discord.py??
no thats like you would ask can i drive a car without getting a drivers licence
still a person can drive tho
ok so how am i supposed to learn python from tuts on youtube
??
yes you can try but you gonna be on this channel every day asking for basic stuff this will annoy you and helpers
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ya thats why i wanna learn
how do i send message in another channel
you need to get that channel object using bot.get_channel and use await channel.send(content)
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
@client.command()
async def send_message(ctx, channel_id: int, message: str):
if ctx.author.permissions.manage_messages:
channel = client.get_channel(channel_id)
if channel is None:
await ctx.send(f"Channel with ID {channel_id} not found.")
return
await channel.send(message)
await ctx.send(f"Message sent to {channel.name}")```
i mean like do a command and await message in another channel
await message? what do you mean by that
send
you already do that here?
thats annother thing that i get an error on
show error then
no attribute to permissions
cause Member object has no attrbute permissions
you prolly want this
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
thanks
bro can i explain to you a bit more what i want on the other thing
@client.command()
async def clear(ctx, amount=5):
"""
Clears a specified amount of messages in the current channel.
The default amount is 5.
"""
await ctx.channel.purge(limit=amount+1)
if amount > 10:
await ctx.send(f"All messages __cleared__ by {ctx.author.mention}, **_(Message will auto delete)_**")
time.sleep(6)
await ctx.channel.purge(limit=1)
elif amount <= 10:
await ctx.send(f"{amount} messages __cleared__ by {ctx.author.mention} **_(Message will auto delete)_**")
time.sleep(6)
await ctx.channel.purge(limit=1)```
i want when it purges messages to send a message in another logs channel
time.sleep is blocking. Use asyncio
!d asyncio.sleep ^
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
How can i do like:
if they dont have permissions then print you dont have required perms?
@client.command()
@has_permissions(manage_messages=True)
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount+1)
if amount > 10:
await ctx.send(f"All messages __cleared__ by {ctx.author.mention}, **_(Message will auto delete)_**")
await asyncio.sleep(6)
await ctx.channel.purge(limit=1)
elif amount <= 10:
await ctx.send(f"{amount} messages __cleared__ by {ctx.author.mention} **_(Message will auto delete)_**")
await asyncio.sleep(6)
await ctx.channel.purge(limit=1)
@client.event
async def on_member_join(member):
guild = member.guild
membercount = discord.utils.get(guild.categories, name='Member Count')
if membercount:
botcount = sum(m.bot for m in guild.members)
total_members = discord.utils.get(guild.channels, name=lambda n: n.startswith("🔢"), category=membercount)
await total_members.edit(name=f'🔢┃Total Members: {guild.member_count}')``` results in an error saying nonetype has no attribute edit
this means that it could not find channel with name that starts with the emoji you provided
I know for a fact that it exists though
try getting it via id then
import discord
from discord.ext import commands
from discord import app_commands
class Displaymembers(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(name="displaymembers", description="Create a new category to display member count.")
async def displaymembers(self, interaction: discord.Interaction):
guild = interaction.guild
if interaction.user.guild_permissions.administrator:
await interaction.response.send_message("Attempting to create member count category...", ephemeral=True)
botcount = sum(member.bot for member in guild.members)
category = await guild.create_category("Member Count", position = 0)
await guild.create_voice_channel(f'🔢┃Total Members: {guild.member_count}', category=category, user_limit=0)
await guild.create_voice_channel(f'🤖┃Bot Users: {botcount}', category = category, user_limit=0)
await guild.create_voice_channel(f'😀┃Humans: {guild.member_count - botcount}', category=category, user_limit=0)
await interaction.followup.send("Member count channels created successfully.", ephemeral=True)
await category.edit(position = 0)
async def setup(client):
await client.add_cog(Displaymembers(client))
``` command cog that makes the chnanel
I don't know the id
my bot is in multiple servers
Hi! Basically my welxome message is sending really late. Its sending like 10 secs after someone join and im wondering why
send your code
Will do 5 mins plz
only the on_member_join function
@blazing flint https://paste.pythondiscord.com/opimicuvud
the problem seems to be more dependent on the server you are running it on
because you are generating an image and it's probably slow
So there’s no way of making it faster?
@smoky sinew can you help me with my problem
running on a better server
My pc is perfectly fine dude
vscode
that's not it
well it could be the problem in some situations
Oh right I read that wrong
I mean... you can try hosting on replit or something
My pc stays open 24/7 theres no servers
you are just using a weird library i guess, i have had no problem with regular PIL
they have pretty good servers
stop bruh
no they don't
replit isn't even made for running a discord bot it gives you a web server to work with
I use it to host my bots 24/7
lol
and it is in five servers
they give you 512 mb of ram to work with
free version is 1 gig of ram
no
hacker repl is 2
no
boosted repl is 4
stop recommending replit
i don't know what it is
scroll up
so what's the problem
Any free servers I can use? Or is it all paid stuff
i think you meant to use discord.utils.find
discord.utils.get does not use a lambda for filtering
oh
that's not the problem though
Bro I host it with my pc open I need a server lol
!d discord.utils.find @blazing flint
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.11)") due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s.
So do u know any
you can remove the image if you want it to be fast
💀
Why tf would I do that
you can get an oracle vm for free i think
That’s good?
it's better than replit
Lolll
why is this not playing the sound i need it to do... Its always saying it isnt connected despite being in a vc with me atm:
user=interaction.user
voice_channel=user.voice.channel
# only play music if user is in a voice channel
if voice_channel is None:
await interaction.response.send_message('User is not in a channel.')
return
guild = interaction.guild
voice_client: nextcord.VoiceClient = nextcord.utils.get(bot.voice_clients, guild=guild)
print(voice_client)
# check if bot is connected to a voice channel
if voice_client is None or not voice_client.is_connected():
await interaction.response.send_message('Bot is not connected to a voice channel.')
return
# check if bot is in the same voice channel as the user
if voice_client.channel.id != voice_channel.id:
await interaction.response.send_message('Bot is not in the same voice channel as the user.')
return
audio_source = nextcord.FFmpegPCMAudio(f'cottonvoice\{sound}.mp3')
if not voice_client.is_playing():
voice_client.play(audio_source, after=None)
await interaction.response.send_message("Done!")```
when printing the voice_client it always prints none

how did i miss this information
should i go back to dpy
From what
Disnake is good enough and dpy doesn't have major advantages over it
As for javascript it's up to you
With what
disnake
More specifically?
Hi, I need a great videos resources to learn python.
https://www.pythondiscord.com/resources/?type=video
this is the wrong channel see #python-discussion and #❓|how-to-get-help
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
@client.tree.command(name="help", description="A list that contains the bot's commands")
@app_commands.choices(helptype=[
Choice(name='general', value=1),
Choice(name='admin', value=2)
])
async def help(interaction: discord.Interaction, helptype: Choice[int]):
if helptype == 1:
embed = discord.Embed(title="General Commands", colour=discord.Color.blue())
embed.add_field(name="App (slash) Commands", value="-", inline=True)
embed.add_field(name="Commands", value="-")
await interaction.response.send_message(embed=embed)
if helptype == 2:
embed = discord.Embed(title="Admin-Owner Commands", colour=discord.Color.blue())
embed.add_field(name="Admin", value="-")
embed.add_field(name="Owner",value="-")
await interaction.response.send_message(embed=embed)
what have i wrote wrong for my bot to hit me with the "Application did not respond"
helptype is not 1 or 2 i guess
why don't you just use literal?
async def help(
interaction: discord.Interaction,
help_type: Literal["General", "Admin"]
) -> None:
Cause Choice seems easier 😭
literal enforces the arguments
it's not rewriting you're just changing one line of code
yeah i just realized lmao
tysm for helping me, it works now 👍
hey guys
AttributeError: module 'discord' has no attribute 'ext'
anyone has this?
is your file named discord.py by any chance?
no, got it now too
what was it
using cogs why doesn't it reply back to my messages?
?
class Messages(commands.Cog):
def __init__(self, bot):
super().__init__()
self.bot = bot
self.chat_log = []
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot:
pass
elif message.content.startswith("$"):
pass
else:
if isinstance(message.channel, discord.DMChannel):
.......
await message.channel.send(...)
@smoky sinew
do you have the message content intent?
yes but do you have it enabled in code
hmm
btw that == self.bot will never run
since bot is an instance of commands.Bot instead of User
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
if message.content.startswith("$"):
return
if isinstance(message.channel, discord.DMChannel):
await message.channel.send(...)
you could use an early return here
check to see if on_message is running at all
ahh hollup let me try
still doesn't message back
is on_message running though
how do I check should I print the message it receives?
sure
doesn't print
is your cog loaded?
in messages.py (cog)
def setup(bot):
bot.add_cog(Messages(bot))
in main.py
bot = commands.Bot(command_prefix="$", intents=discord.Intents.all(), owner_id=1046920598359638036)
async def load_extensions():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
try:
await bot.load_extension(f'cogs.{filename[:-3]}')
print(f'{filename[:-3]} extension loaded successfully')
except Exception as e:
print(f'Failed to load {filename[:-3]} extension. ({e})')
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(
name="$help", url='https://www.twitch.tv/xxxxxxxx'))
print(f"{bot.user} is online with the ID {bot.user.id}")
async def main():
await load_extensions()
bot.run(TOKEN)
you want me to convert it to async?
yes
async def setup(bot):
await bot.add_cog(Messages(bot))
how do I call it again
just load your extensions in setup_hook
oh right yeah
found it but how do I use it again
it's just an event
@bot.event
async def login(TOKEN):
await bot.setup_hook()
so what goes inside? login()?
what
@bot.event
async def setup_hook():
await load_extensions()
remove the main function
def check(msg):
return msg.content in ['1','2','3'] and msg.author.id==onMove
dont mind anyhignt else but the list. that list is in a loop that runs 3 times and the counter variable is names i. how do i make it so that list generates
['1','2','3'] when i is 0 ['1','2']when i is 1 and ['1'] when i is 2
Can you try explaining that a little better? I'm having trouble understanding
for i in range(3):
s=[something]
print(s)
When I is 0 it prints ['1','2,'3']
When i is 1 it prints ['1','2']
When i is 2 it prints ['1']
I don't want to check each lloop what the i is and then assign some stuff to s
I need it in one like o code something like s=[str(j) for j in range(i)]
But idk how to do ut
That's what I mean @rocky trench
@patent wagon nested lists?
Items = [['1','2','3'],['1','2'],['1']]
Then use the i to iterate over the list
I coded so my bot sends a welcome message on joining but that welcome message seems to be sent when someone joins a server my bot is in and not only my server
Can someone help?
so? just use an if statement
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
data = await self.bot.db.fetchval('SELECT role FROM reactionroles WHERE message = $1 AND emote = $2', str(payload.message_id), str(payload.emoji))
if data:
role = payload.member.guild.get_role(int(data))
await payload.member.remove_roles(role)
Any reason why this wouldn't work?
The on_raw_reaction_add is basically the same, just adds the role and that works.
why are you storing your message id as a string 
why doesn't the bot start?
what host are you using
is there a way to turn a command from a Cog into a slash command?
hybrid commands you mean? what do you mean by "turn"?
like take the command from the cog and have that same command has a slash command
or is there a way to create slash commands inside of classes?
yes??
Is it like
If:
member.guild(#server_id)
await channel.send(blablabla)
else:
return
?
if not member.bot
So what I sent was the right script?
The Discord Component Library could not be downloaded. Please help me ㅜㅜ
dan bot host
if what
I mean if the user is in my server
what library, discord has components built in
yes but it's if <condition>: in python
and you don't have anything after if
and what is member.guild
yeah
Which one
if you are comparing ids
Kk
@smoky sinew bro??
i don't use that
ohk
it's sketchy
then what host you're using
digitalocean
Free clouds are good if u don’t wanna pay
Oracle do 24gb 4 core one
It’s arm though and they sometime shut down ur vps for maintenance
button
I have a big problem when someone joins with no pfp, the bot doesn’t send welcome message as the member.avatar.url or idk is not seen
class MyView(discord.ui.View):
@discord.ui.button(
custom_id="my_button",
label="My Button"
)
async def my_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.response.send_message("hello")
you only need to import discord for this
The library for using the button cannot be downloaded.
use member.display_avatar.url instead
Ty
discord-components has been pulled for a while now (<t:1639458000:D>) so you definitely need to look into discord.py 2.0 or another library
Guys can I get help
Mudkip has been a massive help, but we are unsure why my bot is responding to every command twice. Was wondering if anyone had any ideas?
https://github.com/uncleiansreadyrice/Turlington-Test
Do u have two instances running?
I do not
You're 100% sure? Restart your computer if you're not.
Which command did you run?
moderation.py lines 104 to 117
@commands.Cog.listener()
async def on_message(self, message):
for bad_word in bad_words:
if bad_word in message.content:
print("Banned words scrubbed from chat.")
await message.delete()
await message.channel.send("That terminology is not permitted here.")
channel = self.bot.get_channel(744246685932191805)
embed=discord.Embed(title=f"A censored word has been scrubbed.",description=f"{message.author} has used the censored term, {bad_word}, and it has been scrubbed from the server.", color=0x00FFFF)
embed.timestamp = datetime.datetime.now()
await channel.send(embed=embed)
channel = self.bot.get_channel(1086293466054656100)
await channel.send(f"A censored word has been used by {message.author} and scrubbed from chat.")
await self.bot.process_commands(message)```
wait
You don't need process_commands if you're using a listener()
is it the self.bot.process
Indeed
ahhhhhhhhhhhh
just realizing the only ones I tried were moderation on second thought, so that makes sense
wait actually no it did it on some mc server commands let me check there too

Fixed
Nice!
i appreciate you
Thanks 😁
WELCOME MESSAGE ERROR
The user avatar, name etc is not uploading on the image
That’s the issue, although, no errors is shown up
guys I just cant get this to work
Get what
Hey @sinful thistle!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Music bot
this is main code
if message.content.startswith('!play'):
url = message.content.strip()
url = url[6:]
channel = message.author.voice.channel
if url.startswith('http'):
id_of_vid = url[32:]
else:
id_of_vid = url[24:]
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
vc_Messi = await channel.connect()
print(id_of_vid)
audio_source = FFmpegOpusAudio(f'{id_of_vid}.mp3')
vc_Messi.play(audio_source)
await message.channel.send(f"Playing {url}")
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
kk
then how do you make a music bot?
it says that the file is obus but I am 100000000% sure it is .mp3
Use Spotify or smthing
at this point it doesn't make sense
there's literally a spotify integration in discord
maybe smth like soundcloud
Opus is encoder
hello guys. i have a question. if i use @bot.event command twice on code, it will crash and not working?
It'll override the previous one
ohhh thank you so much
Use @bot.listen() instead
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
thank you !!
partially
dont advertise here against rules
Hey guys, i'm trying to make a discord bot that lets a user flip a coin. Is there a way to prompt the user with either heads or tails when they go to type in the command coinflip? code below:py @tree.command(name="coinflip", description=f"Flip a coin!", guild=guildId) async def self(interaction: discord.Interaction, choice: ):
Left choice blank as I wasn't sure what to fill in 😓
enter image description here
I need to do like this in discord.py slash command and i dont know how to do
Thanks for the reply <33
I just tried implementing this and received this error: TypeError: unknown parameter given: choices. Any idea as to what I might need to do 😅
show code
@tree.command(name="coinflip",
description=f"Flip a coin!",
guild=guildId)
@app_commands.choices(choices=[
app_commands.Choice(name="Heads", value="Heads"),
app_commands.Choice(name="Tails", value="Tails"),
])
async def self(interaction: discord.Interaction,choice: app_commands.Choice[str]):```
was just copying it across haha
cause you named your parameter choice and said choices=[...] either use choice or choices in both places
Oh? In the link you sent it had it exactly like that 👀 . So i'm presuming this'll work better?py @tree.command(name="coinflip", description=f"Flip a coin!", guild=guildId) @app_commands.choices(choices=[ app_commands.Choice(name="Heads", value="Heads"), app_commands.Choice(name="Tails", value="Tails"), ]) async def self(interaction: discord.Interaction,choice: app_commands.choices[str]): ;P
oh nope it didn't 😢
no not in this place
notice how in link i sent you they named parameter choices this matters
OH yeah sorry I follow now my bad
sorry i think i'm a bit tired 💀 thanks for clarifying 
👍
Any chance you also know how to do this for an integer? i'm trying to do a value: int and not allow it to go over 100
idk if that's possible but hoping it is 😅
Um anyone here ? 
yes exactly that! where did you find this? i spent a decent while looking for the documentation 😢
i googled this discordpy app commands choices max value
ah, i was googling stuff similar to discord.py slash command choices less than 100 and stuff like that, clearly need to work on my google skills 💀
Last question before I head off to bed, i'm trying to design this coinflip thing so that it sends a message with a gif, then waits 5 seconds, deletes the gif and then sends the results. This is what i've got so far:py gif = discord.File('Coinflip.gif') await interaction.response.send_message(f"Thinking...", file = gif, delete_after=5) await interaction.response.send_message(f"{results}")
The only issue is that it's already been responded to so it doesn't seem to like that. I tried interaction.followup but it doesn't look as clean as what i'm going for. I see a lot of bots able to just send another message so i'm wondering how I can achieve that
its better to look for general stuff like value between range instead of value between 10 and 100
Yeah i just kinda hoped it would pick up on the main keywords haha
you may edit the message with gif after 5 seconds instead of deleting it
with discord.py in particular, the documentation/github is very often what you should reach to first because with various major changes to the library over its lifetime, there's a ton of now-defunct information about it (for example, pass_context or bot.send_message())
https://discordpy.readthedocs.io/en/stable/interactions/api.html#range
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
yeah basically everything i find is very very broken now 😆 Thanks for the resource <3<3
I take it that's just gonna be interaction.response.edit()?
ah edit_message()
ok lemme drop my ques
what's the difference between using interaction.response and interaction.message? Is message for once the message has been sent?
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
!d discord.Interaction.message
The message that sent this interaction.
This is only available for InteractionType.component interactions.
idk if you guys know we can do some thing like:
btn = discord.ui.Button(...........)
async def callback(inter):
...
btn.callback=callback
my question is how do i access the Button object (without da btn var) tho my current code is not the same
oh so wouldn't that edit the users message rather than the responses?
Slash commands aren't used with messages
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
there is no user message
you need to get the message with this
yeah that's why i'm questioning if it'd work or not
also 💀
nah didn't like it haha
i guess you could give callback a button argument and then wrap it with functools.partial() so it receives the button, but i dont usually find the need for this callback syntax in the first place
i mean my code is now totlly different, but rn its fine
i fixed it by subclassing the button on the view
xD I think I should make fair be even more rare
how do i use discord_slash on pycharm
discord_slash is highly out of date (nearing two years), and the library it comes from was renamed to discord-py-interactions/interactions.py
https://pypi.org/project/discord-py-interactions/
https://github.com/interactions-py/interactions.py
discord.py 2.0 came out last year too which adds support for message components / slash commands
Anyone got a docs for this?
Message sent in the channel is took and is added into the bot’s embed added with an autoreactions and autothreads
https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel
https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.add_reaction
https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.create_thread
So many docs
Actually its easier than u might think
they asked for it 🤷
How
I cant even find it
So u use on_message event to check for messages in the specific channel, use channel.send(embed=...) to send the embed, then use a wait_for to wait for any reactions on the message, and if the reaction happens, then u create a thread using channel.create_thread
The content sent by the user is on the embed message tho
u can access the message content with message.content and u get the message in the on_message event
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
Any docs to help?
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
the on_message docs are above, message.content is this ^
Do you have a docs for afk commands too?
Cant find one
AFK Command?
So when u set the afk message, and when the person goes offline/afk, it will send that message?
When you do ?afk reason user goes in afk and when someone ping them, they will receive arisu is offline : reason. When I comeback to chatting, it says arisu is back in chat! or sum like that
For the second part, u use on_message
You maintain a database of users who are AFK and just change the values as to when to send the message and when to not, and for the command, u can do:
async def afk(ctx, *, message: str):
# message is the message which the bot will send whenever someone mentions the author
And this
Wouldn’t a list work?
It will, sure
Its easier to me lol
!d discord.Message.mentions check this list for author 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.
I see
it won't persist
I saw people doing it with a list tho
if you want it to persist a list won't work
https://paste.pythondiscord.com/afitecosur
I am not getting an error, but my message that I am defining as 'game' is never being edited with the actual board
How do I do an event that times out someone
You mean a command?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Thanks
Can I have an example for this
One sec
import datetime
duration = datetime.timedelta(minutes=5)
await member.timeout(duration)```
Thanks
put imports at the top though
Yeah I know
@smoky sinew
idk
global author_msg_counts
author_id = ctx.author.id
# Get current epoch time in milliseconds
curr_time = datetime.datetime.now().timestamp() * 1000
# Make empty list for author id, if it does not exist
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
# Append the time of this message to the users list of message times
author_msg_times[author_id].append(curr_time)
# Find the beginning of our time window.
expr_time = curr_time - time_window_milliseconds
# Find message times which occurred before the start of our window
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
# Remove all the expired messages times from our list
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
# ^ note: we probably need to use a mutex here. Multiple threads
# might be trying to update this at the same time. Not sure though.
if len(author_msg_times[author_id]) > max_msg_per_window:
duration = datetime.timedelta(minutes=15)
await ctx.send("Stop Spamming")
await author.timeout(duration)
What would I replace the author with at the bottom
what is ctx? you said this was an event?
Wait never mind I got it
Someone pls help me
Add some print statements inside and see to which its getting
I can’t rn I will when I have the chance. Can I dm you?
Nvm
guys help.
Возникло исключение: PrivilegedIntentsRequired
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
discord.gateway.WebSocketClosure: '
During handling of the above exception, another exception occurred:
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 4014
During handling of the above exception, another exception occurred:
File "E:\My Code\tic tock.py", line 14, in <module>
client.run('token my bot)
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
it tells you what to do in the error message
It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Ok
How do I code a discord bot on my phone
you don't have a computer?
I do but not with me I’m not home rn
@client.listen("on_message")
async def coolmessage(message):
if message.author.id == client.user.id:
return
message.content
blockedwords = [
'idiot', 'Idiot', 'IDIOT', 'IDiot', 'dum', 'Dum', 'DUM' ,'DUm', 'DuM', ' stupid', 'STUPID',
'Stupid', 'STupid'
]
if any(word in message.content for word in blockedwords):
await message.delete()
await message.channel.send(
f"Please don't say that {message.author.mention} ", delete_after=5)
normalmsg = ['hi', 'Hi', 'Hello', 'hello']
if any(word in message.content for word in normalmsg):
await message.channel.send(f"Hi {message.author.mention}")
global author_msg_counts
author_id = message.author.id
# Get current epoch time in milliseconds
curr_time = datetime.datetime.now().timestamp() * 1000
# Make empty list for author id, if it does not exist
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
# Append the time of this message to the users list of message times
author_msg_times[author_id].append(curr_time)
# Find the beginning of our time window.
expr_time = curr_time - time_window_milliseconds
# Find message times which occurred before the start of our window
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
# Remove all the expired messages times from our list
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
# ^ note: we probably need to use a mutex here. Multiple threads
# might be trying to update this at the same time. Not sure though.
if len(author_msg_times[author_id]) > max_msg_per_window:
duration = datetime.timedelta(minutes=15)
await message.channel.send(f"No Spamming. {message.author.mention} has been timed out for 15 minutes for spamming")
await author.timeout(duration)
Look on the bottom line
The error is author isn’t defined
How do I code a discord bot on my phone
Idk to code
Oh
Yes
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
sort by beginner
Ok
Thank you 🙏
What do I choose for the type
whatever you want
Can I use python on my phone?
maybe
Anyone?
!d discord.Message.author
How is it not defined tho
because you didn't define it? what do you mean'
Ok
How do I define it here?
just use message.author instead
Then it gives me the error ‘Member’ object has no attribute to ‘timeout’
your discord.py is outdated
switch to 2.0
Oh
huh?
pip install discord.py 2.0
Yes
Ok
Anyone have a code that I can use for a discord bot on replit idk how to make one
Which line?
so maybe learn how to
how do i define MyContext for a custom context?
subclass commands.Context class
^ then override Bot.get_context
can this be done in a cog
this
yeah referring from there
i have a tag class
i added MyContext subclass under that
is that right
since i need the function within that class
How do i remove the [' '] from inside of the embed?
use [0]
after whatever your query is
how do u mean
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
right thats better
use this to join all missing permissions to one string separated by something
show some code
class Tag():
def __init__(self, name: str, author: int, description: str, created_at: datetime):
self.name = name
self.author = author
self.description = description
self.created_at = created_at
class MyContext(commands.Context):
async def get(self, name):
tag_data = await self.database["tags"].find_one({ "_id" : self.guild.id })
if tag_data:
if name in [x["name"] for x in tag_data]:
author=[x["author"] for x in tag_data if x["name"] == name][0]
description=[x["description"] for x in tag_data if x["name"] == name][0]
created_at=[x["created_at"] for x in tag_data if x["name"] == name][0]
return Tag(name, author, description, created_at)
else:
raise commands.BadArgument(f"No tag named {name}")
else:
raise commands.BadArgument(f"No tag named {name}")
okay now you need to tell bot to use this context
!e ```py
permissions = ["ban_members"]
print(", ".join([p.replace("_", " ").title() for p in permissions])
!e ```py
permissions = ["ban_members"]
print(", ".join([p.replace("_", " ").title() for p in permissions]))
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
Ban Members
@vital glacier
Ah I see
in main.py```py
class MyBot(commands.Bot):
async def setup_hook(self):
# stuff
async def get_context(self, message, *, cls=None):
return await super().get_context(message, cls=cls or MyContext)
is that correct
looks like
but then how do I define MyContext
class MyContext(commands.Context):
pass
sure
whats command
!src
this is a command
yeah?
you need to import it
is undefined
thought so but do i import it manually for all the cogs wherever i use a custom context?
from something import MyContext
you only need to import it to the cogs if you want to typehint the ctx
ohhh i import it to the cog not to main.py
right that makes so much sense
wait no
what
undefined name 'MyContext' in main.py
am i supposed to import MyContext from a cog to main.py
what
you don't need to import anything just put MyContext in main.py
it says discord.app_commands.errors.CommandInvokeError: Command 'get' raised an exception: AttributeError: 'Interaction' object has no attribute 'get'
what is interaction.get
yes but Intraction and Context are two other things
doesnt it work for both
no
Interaction is for slash commands while Context is for prefixed commands
interaction is not a type of context
someone told me it works for both in the discord.py server
if you use hybrid commands it will
so cant i use interaction at all with a custom context
maybe they means hybrid command
Guys what version is discord on
probably
When you import discord
2.2.2
you can use interactions but they wont have the methods you defined in custom context
hmmm
Did replit had enough of keep_alive or is it just me?
accept text as argument and send it
thx
it would roughly look like this:
async def echo(ctx, *, message):
await ctx.send(message)```
where is command decorator
thanks
if i want to use slash commands but using cogs how do I do it? (mention me)
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
for cogs its just @discord.app_commands.command() instead of @commands.command() yeah?
sure
async def prefix(bot, message):
data = await bot.db.fetchval('SELECT prefix FROM prefix WHERE guild_id = $1', message.guild.id)
if data:
return commands.when_mentioned_or(data[0])(bot, message)
else:
return commands.when_mentioned_or(',')(bot, message)
Currently I have this and I'm trying to make it so it can also respond to a custom set prefix for the user only, so u would have the guild prefix, a 'self' prefix (which only the author can use if setup), and then the mention.
The guildprefix and mention prefix already work
Just need to add the selfprefix but no idea how to make that work.
and also make it work so it respond to the all 3 if they are issued
"context menus cannot be defined inside a class"
reading was never an option
@app_commands.command(description='Kicks a member')
@app_commands.describe(member='member to kick')
@app_commands.default_permissions(ban_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason:str):
embed = Embed(color=0x003fff)
embed.set_author(name=f"{member} was kicked | {reason}", icon_url="https://cdn-icons-png.flaticon.com/512/6364/6364343.png")
await interaction.response.send_message(embed=embed)
await member.kick(reason=reason)
slash command not showing
did you sync it?
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(
name="/help", url=url))
print(f"{bot.user} is online with the ID {bot.user.id}")
await bot.tree.sync()
make a message command to sync it
wym
@bot.command(name="sync")
async def sync_globally(ctx: commands.Context) -> None:
await bot.tree.sync()
await ctx.send("Synced the bot tree.")
2023-03-26 22:18:54 WARNING discord.http We are being rate limited. PUT https://discord.com/api/v10/applications/1089303273850277928/commands responded with 429. Retrying in 26.09 seconds.
you're syncing too often
synced but slash commands still not showing
Hey, I am getting this error how could I fix this?
nextcord.ext.commands.errors.BadArgument: Converting to "File" failed for parameter "file".
@bot.command()
async def sendfile(user: nextcord.User, *, file: nextcord.File):
"""Send a file to a user."""
try:
with open(file, 'rb') as f:
file = nextcord.File(f)
await user.send(file=file)
await user.send(f"File '{file}' sent to {user.mention}")
except Exception as e:
await user.send(f"An error occurred: {e}")```
This happened after running the command
I am trying to send a message to a specific channel using discord py
However I don't want to start the bot, I just want to send a message.
Sadly the bot is not showing any guilds
async def main():
config = DiscordConfiguration()
client = Client()
await client.login(config.token)
print(client.guilds) # empty
asyncio.run(main())
You need to start the bot to send messages
a bot is not really what you're looking for in that case
Well, actually nevermind
Can you guide me to the right place
But if you're using discord.py you may as well
I think some sort of webhook is what he needs
Discord's built in Webhooks function as an easy way to get automated messages and data updates sent to a text channel in your server.
Think of them as one of those fancy pneumatic tube things you u...
I just want to send a message, the thing shouldn't be interactive
You'd just send a POST request to the appropriate endpoint using something like requests or aiohttp
Thank you I have been banging my head for a while
hi
how can i change these colors
@sick birch srry for ping
can anyone tell me?
i need it to be purple but when i put "PURPLE" it gives me "error traceback"
because there's no purple attribute
how do i fix that?
colorama only supports these iirc
use a library like rich, also check out #❓|how-to-get-help because this isn't the right channel
thank you
wow thank you so much this helped alot!
my slash commands are still not working
try refreshing your discord client and also check if your cog is loaded
Hey @regal perch!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hi Guys, I'm new to bot development with python. I've been creating this bot that has the prefix "-", I'm trying to get the bot to respond "Hello, How Ware you??" when I execute the -greet command. But it only does it when I tag it when doing the command, that is, I say "-greet @bot, so I wanted to know how I can make the bot execute the command without needing to tag it in the message. THANK YOU SO MUCH FOR READING. Below is the code. https://paste.pythondiscord.com/opimezijuq
I don't know how to make the code show up here without the link.
hmm have you tried removing the if statement before process_commands
code looks fine to me
Which of the 2?
At the end of all the code or just the event?
@bot.event
async def on_message(message):
if message.author.bot:
return
if bot.user.mentioned_in(message):
await message.channel.send(...)
await bot.process_commands(message)
Thanks
I'll try the code, now I'll come back
Still the same, it works only when I tag the bot in the message @smoky sinew
you need the message content intent
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
intents=intents,
command_prefix="-"
)
and make sure to enable it in your developer portal as well
Something like that?
yes
It worked. I thank you so much brother.
Hey I havent used discord.py in a while and it seems that my cog commands are not being loaded.
This is how I am loading the cog files
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
Cog looks like this
import discord
from discord.ext import commands
class class(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def command(self, ctx):
. . .
def setup(bot):
bot.add_cog(Help(bot))
But whenever I call that command it comes up as discord.ext.commands.errors.CommandNotFound
Anything i might have missed since last updates? Intents are enabled
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = 's.', case_insensitive = True, intents = intents)
hi sylex
long time no see
bot.load_extension is a coroutine now, so is setup and add_cog
you should do extension loading in Bot.setup_hook
Do u have multiple events tho?
As because i think if you tak the bot, still it needs intent
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
what
the issue is the bot can't see message content unless it's pinged
If the message content intent is not enabled, the content will br always nothing?
How it can see mentions then 
Maybe message.mentions still works ig or no?
Idk maybe i am just not understanding the context, my bad
no,, the bot can see the content if it's pinged
I think discord API works like that? Never tried
yes it does?
the whole content
Demnn, its like bypassing message_content intent 
Discord should remove that i think
no why would they
Yeah
I mean bot should not know the content when the intent is not enabled
what
I am tripping hard 😂

I scraped cogs but it still isn’t working
? scraped?
?
https://paste.pythondiscord.com/maqasaqoto
the print statement in the section where I am trying to define the user allowed to use my select menu is never made so I am wondering what I am doing wrong to set each item in the select menu only available to current_player
question...
so i'ved tried this a few different ways... but i'm stumped...
so i have a random vc generator. when members leave it, the channel deletes, but if a user jumps from that channel to another, it doesn't delete until both temp channels == 0 users... thoughts?
i'm only seeing before.channel initiated when they leave both/all channels.
if (
before.channel is not None
and before.channel.name in self.channel_items
and len(before.channel.members) == 0
):
await self.channel_generator_deleter(before=before, after=after, member=member)
if (
before.channel is not None
and before.channel.id in self.channel_items
):
print("before channel is not none and before channel id in channel info")
print("Before sleep: ", len(before.channel.members))
await asyncio.sleep(1)
print("After sleep: 1", len(before.channel.members))
if len(before.channel.members) == 0:
await self.channel_generator_deleter(before=before, after=after, member=member)
Use after.channel? As because when user moves from different vc so old attributes are like
before.members = old attr
after.members=new attr
so
old_attr will return 1 member while new_attr will return 0
ohhhh
My bad, it will be before.members
As because before, after is already a channel object lol
Can i see the full code?
And are you doing it inside "event"?
sure. 1 sec.
what event u r using? voice_state_update?
yes
ohk lemme check the docs once
okies ty!
i think then it will be
after.channel.members
like u were doing
after.channel.members
my bad lol i thought "before, after" is channel objects
you're good lol
maybe it's the way the channel_info is being accessed...
so what i am gussing, u r trying to like delete channel when the channel's members is 0? right?
right
oh then change all before to after.channel.members:
if before.channel is not None and before.channel.id in self.channel_info:
await asyncio.sleep(1)
if len(before.channel.members) == 0:
await self.channel_generator_deleter(before=before, after=after, member=member)
no need of this imo
if after.channel is not None and after.channel.id in self.channel_info:
await asyncio.sleep(1)
if len(after.members) == 0:
await self.channel_generator_deleter(before=before, after=after, member=member)
if after.channel is not None and after.channel.id in self.channel_info:
await asyncio.sleep(1)
if len(after.channel.members) == 0:
await self.channel_generator_deleter(before=before, after=after, member=member)
this is ok
but why u r using the same if statement two times?
no i must of pasted that line twice :c
ohk lol
so i'm guessing...
if (
after.channel is not None
and after.channel.id in [
channel["voice_id"] for channel in self.channel_info.values()
]
and len(after.channel.members) == 0
):
await self.channel_generator_deleter(before=before, after=after, member=member)
if (
after.channel is not None
and after.channel.id in self.channel_info
and len(after.channel.members) == 0
):
await self.channel_generator_deleter(before=before, after=after, member=member)
one of these...
yeah one of this
but the first if statement is bt different?
what does self.channel_info look like?
self.channel_info = channel_info
chnnel_info isnt defined?
i think u r trying to make it a dictionary?
self.channel_info={}
yes. i use them as a dictionary cause i suck at sql still x.x
channel_info = {
"ChannelGenerator":"",
"best_textstat": "",
"voice_id": "",
"text_id": "",
}
oh xd
then 1st if statement is right
not the 2nd one
What does this error mean
most likely that you are trying to access a varriable that doesnt exist yet
show full code
what when the if is false the varriable muted_role wont exist
What can I do to make it exist
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | print(cat)
004 | ^^^
005 | NameError: name 'cat' is not defined
!scope
A scope defines the visibility of a name within a block, where a block is a piece of python code executed as a unit. For simplicity, this would be a module, a function body, and a class definition. A name refers to text bound to an object.
For more information about names, see /tag names
A module is the source code file itself, and encompasses all blocks defined within it. Therefore if a variable is defined at the module level (top-level code block), it is a global variable and can be accessed anywhere in the module as long as the block in which it's referenced is executed after it was defined.
Alternatively if a variable is defined within a function block for example, it is a local variable. It is not accessible at the module level, as that would be outside its scope. This is the purpose of the return statement, as it hands an object back to the scope of its caller. Conversely if a function was defined inside the previously mentioned block, it would have access to that variable, because it is within the first function's scope.
>>> def outer():
... foo = 'bar' # local variable to outer
... def inner():
... print(foo) # has access to foo from scope of outer
... return inner # brings inner to scope of caller
...
>>> inner = outer() # get inner function
>>> inner() # prints variable foo without issue
bar
Official Documentation
1. Program structure, name binding and resolution
2. global statement
3. nonlocal statement
The condition wasn't true, the variable will not exist
add:
else:
muted_role="something"
Like that
figured it out! ty for the insight!
if (
after.channel is not None
and after.channel.id in [
channel_data["voice_id"] for channel_data in self.channel_info.values() if isinstance(channel_data, dict)
]
and len(after.channel.members) == 0
):
await self.channel_generator_deleter(before=before, after=after, member=member)
good to know :)
or if you only want to handle else revert the if to be negation
Like what?
Also I did intend it properly but it still says wrong
if ......................:
.............
else:
........
await message.author........................
if something:
pass
else:
# do stuff
instead of this ^
do this:
if not something:
# do stuff
well then if it's something then there is no muted_role var ;-;
again raising the error

Yes
Thanks
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
Hey how to make a message disappear itself
@commands.is_owner()
@bot.command()
async def purge(ctx,amount:int):
await ctx.channel.purge(limit=amount)
await ctx.send("Purged",ephemeral=True)
Recently I got to know that ephemeral doesn't work for prefix commands
So what I want is that the message which I sending in the last to disappear itself.
@upbeat otter
What does disappear itself suppose to mean
I mean that
when I use
mb!purge 5 The message that is sent in the last like Purged
should disappear after a limited period of time
@naive briar
will this work if I store the last message in a var and then use msg.delete()
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
you can use the delete_after kwarg ^^
You are a genius
by the way
if I want to look some stuff how can I use this comamnd
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Hello, when I create a @bot.command it works perfectly, but as soon as I create a @bot.event underneath it, it removes my commands from the bot command, do you know why? Thanks in advance
what event is that? show full code
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=".", intents=intents)
@bot.event
async def on_ready():
print ("le bot impact es chaud à faire feu !")
@bot.command()
async def ping(ctx):
await ctx.send("Pong !")
@bot.command()
async def re(ctx):
await ctx.send("nard !")
@bot.command()
async def fruitix(ctx):
await ctx.send("Fruitix es le plus beau des dieux")
@bot.command()
async def quoi(ctx):
await ctx.send("feur")
@bot.command()
async def clear(ctx, amount:int = 5):
await ctx.channel.purge(limit=amount)
@bot.command()
async def creeper(ctx):
await ctx.send("Voici le nombre de spawner a creeper des membres de la faction\n\nFruitix : 15\nTascrulaviecunki : 1\nTartoCerise : 11\nTartoFruit : 17\nSherinoxxx : 92\n")
@bot.command()
@commands.has_permissions(kick_members=True)
async def kick (ctx, member:discord.Member, *, reason=None):
if reason == None:
reason="aucune raison"
await ctx.guild.kick(member)
await ctx.send(f"le joueur {member.mention} a été kick du serveur impact pour {reason}")
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban (ctx, member:discord.Member, *, reason=None):
if reason == None:
reason="aucune raison"
await ctx.guild.ban(member)
await ctx.send(f"le joueur {member.mention} a été banni du serveur impact pour {reason}")
@bot.event
async def on_message(message):
if message.content == "fruitix".lower():
await message.channel.send("Laisse le dieu tranquille !")
I would like to be able to write a text and that the bot answers me, when I use the command it works, for example ".fruitix" but when I do "fruitix" it doesn't work... and I don't find why... I have already read what you sent me but I don't understand..
@slate swan
same to make a messafe when people join my server it does not work
i add : "await bot.process_commands(message) but It still doesn't work
unindent await bot.process_commands(message) to be outside if
where should I put it?
unindent
I'm sorry I'm French I try to do my best
put cursor at this line and press Shift + TAB
too much
i'm verry sorry..
await must be on the same vertical line as if
thats correct
ok i start for testing
and for the welcome message I have to add this command too ?
it works thank you very much < 3
now I have to set the other @bot.event...@slate swan
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
you cant define 2 events with the same name
you need to implement this code in one method
Add elif below and check for creeper
below what? @slate swan
below if
Do you know how Basic if elif structures looks Like?
no sorry I'm a beginner... 😦 I can't find anyone to help me, I'm sick of it. @slate swan
you are the only one who has ever helped me...
That's because it's hard to help beginners with complex python code.
It would be better for you if you learned basic python first, and then resumed your discord bot project once you're done learning.
If you want free resources to learn python you can check !resources
ah 😦 ok... but for this elif function can you help me please?
😦
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!d elif
8.1. The if statement
The if statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
``` It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section [Boolean operations](https://docs.python.org/3/reference/expressions.html#booleans) for the definition of true and false); then that suite is executed (and no other part of the [`if`](https://docs.python.org/3/reference/compound_stmts.html#if) statement is executed or evaluated). If all expressions are false, the suite of the [`else`](https://docs.python.org/3/reference/compound_stmts.html#else) clause, if present, is executed.
No
grrr..; ! 😦
!e
a = False
if a:
print(0)
elif not a:
print(1)
else:
print(2)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
i don't understand.. @naive briar
Because you never learned about conditional operators
Sorry to say this, but you need to learn basic python
Unfortunately there is no shortcut to learning the basics ^-^
Youtube videos or online courses are the way to go
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I succeeded 🙂
thank you, I have another question, I would like to put an administrator permission on my command ".clear" how can I do?
how do u do a hybrid command so it is slash and prefix at the same time, or do you just have to just duplicate all commands to have 1 slash, and 1 prefix?
@commands.has_permissions(administrator=True)
here have my clear command for reference
@sick birch
I'm not able to help atm, sorry
ok
@slate swan thank
do you guys any free uptime monitoring ideas other than UptimeRobot?
I don't think so
Get the ID of the replied to message then fetch the message
Then convert the embed into a dictionary
fetched_message.embeds[0].to_dict() IIRC
Is it possible to make a discordbot join a server but as a regular user?
no discord bot can only be invited by someone with permissions to do it
it cant join on its own but i belive it can create a server
Then how would someone be able to monitor a lot of discord servers using a discordbot without actually having the bot in those servers?
depends what do you mean by monitor
Just get the basic information on a server like who is in it
the bot must be in to know that
So they're either using social engineering to invite the bot or doing something against TOS to see inside a discord server?
if any bot has data from server it is not in then its against Discord ToS for sure
I'm guessing it's against TOS to create an application that logs into a discord account that's in a server just to see what's up? such as to see who is in it and what roles etc?
Scrapped**
I got rid of cogs
But my app_commands don’t work
hey i have just complted learning python now from where can i learn discord.py???
@slate swan
bruh u online reply wen
@slate swansry for another ping
nothing in there
did you even open it?\
why there is no next option??
ya
then read its content and try do make some basic stuff
i gave my 2 nights to learn python becz u said
what did you learn in 2 nights
am asking where is next button if i complete 1st page then wht am i supposed to do??
PYTHON
not everything has a cool tutorial with steps to walk you through
my 2 nights contain 24 hrs i opened my eyes for 24hrs
but wht am i supposed to do after reading 1st page??
do it on your end
heh?
and try it out
change something and see what it does thats how you learn
ty sir for ur help till now
okay
?
How do I make the bot respond to messages?
my:
Hello I want help?
await ctx.reply("Hello")
instead of .send
Can anyone tell me what is data base management and why do i need to learn it?
how do i add add roles to multiple user?
async def addrole(ctx, member: discord.Member):
how to i uninstall the discord_slash folder in this location: "/python3.9/site-packages/discord_slash"
if you already found it you can just remove it
Yea but how to i reinstall it. It has a error in the manage_commands.py
pip install -U discord_slash
it should update it to latest version
but keep in mind it is very outdated
ERROR: Could not find a version that satisfies the requirement discord_slash (from versions: none)
ERROR: No matching distribution found for discord_slash
ok, how to i at options to slash commands?
Ello, i cant seem to get the reactions from a message
msg = await channel.send(embed=giveaway_embed)
await msg.add_reaction("🎁")
await asyncio.sleep(duration_secs)
reactions = msg.reactions
@slate swan cans ya help
it keeps returning an empty string even though theres reactions to it
in what library?
no idea why
I use these:
import os
import discord
import discord.ext import commands, tasks
import interactions
discord and interactions are both discord libraries you cant choose 2 at once you need to choose one to use
Which of them has the function to use options in slash commands?
discord has for sure
its most popular
here are examples of the slash commands in discord library: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
I want to use this command for example:
@bot.command(
name="say",
description="Sagt etwas im Namen des Bots.",
options=[Option(name="text", description="Der Text, der gesagt werden soll", type=OptionType.STRING, required=True)]
)
async def say(ctx: SlashContext, text: str):
await ctx.send(text)
try out some commands from examples and see what you need
I have this code here to mute someone if there spamming but once someone gets muted it mutes people if they say one word
Can anyone help me to fix this
embed.add_field(name="Платформа", value=f"**Обработано команд:** {commands_count}\n**Задержка:** {delay*1000:.2f} мс\n**Запущена:** {uptime} сек назад", inline=True)```
?
why discord removes permissions for particular member in a channel when he lefts and if he rejoin perms are not there :-;
Anyone?
is anyone else completely icked out by these people creating full betting apps as discord bots
sharpline sports
"members made $500, 000" in 2022"
not enough code to tell whats going on
unless you're somehow storing everyone under the same dictionary key
also storing it in a list like that makes no sense to me
wouldn't you just add or minus one and store a timestamp with it to simplify things
I think I am
based on what you've sent, that's the only way i could see it
Can you show me an example
Hello i am really sad.Can anyone help please?😢
dict = {author_id: [msg_count, timestamp]}
Can anyone tell me what basics do i need to learn then go for coding?
trying to remember how i did this for one of my apps
Is this in a storing file?
a storing file?
Like a json file or a txt

Or a cog
json stores dictionaries so yes, so does text files but you should basically never be using text files
I use json anyway
and i would recommend switching to databases and not using json, but if you're new to python and this isn't something you'll release for lots of people i wouldn't worry about it for now
time stamp should be an integer so it should be the same
time stamps are just the number of seconds since a date
jan 1st 1970
How long is a while?
Guys someone has tool?
Exampple:
Using Discord tokens 10limit or more
Using discord channel id(no limit)
Message send: what i want
Au dm response: what i want

