#discord-bots
1 messages ยท Page 260 of 1
๐ฟ
๐ณ
it work๐ฅน
look what magic happens when you do what it tells you to do
You never feed me.
everyone except you
!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**.
there is stickers kwarg
anything change in the code
thats not my language
have you created any bot?
Who's Hindi speaker i might provide support as i know language?
yeah many why does that matter
am indian
person above you
Any error or question?
Guys english please, else use DM.
arre help kar
i belive you need to speak english here
who is this @hasty pike
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

yes please, using english is a requirement here
Sorry my bad
i alweys obey request
Minaa, :3
Been awhile.
from where you are
This isn't chilling channel
@hasty pike indian?
Please stick to the topic
Please specify your question
- setup a database
- connect to it in python
- create a querry to add coins
- create a querry to remove coins
in most simple terms
i treid many time
you tried many times what
how to create database
database
well im not as good in databases

there is a channel for databases #databases
My experties don't worry
Use Docker for that.
i always use docker compose for it but may be too hard for a beginner
Alternatives aren't any better.
i need a patner for making bot
what is docker?
yeah but i dont see me starting my journey with discord bots from docker
Google...
Docker is a tool for developers to quickly create containerized virtualizations of an os in order to create a good environment for developing.
Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers
it help to create database?
its good when you want your code to work the same on each machine
True, I started more simpler too.
@tasks.loop(minutes=15)
async def guild_count():
await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name=f'{len(client.guilds)} servers | type /help or /info'))
print(f"guild count is {len(client.guilds)}")
@guild_count.before_loop
async def before_count():
print('waiting...')
await client.wait_until_ready()
``` is this code right?
should be
Docker is a lot larger than that if you are planning to work with it.
should i ingnore it?
the before_count is not saying "waiting..."
so I dont think it is working
can someone explain me these lines duration_regex = r'(\d+)([hms])' duration_values = re.findall(duration_regex, duration_str)
DO you have any kind of logging setup?
wdym logging setup?
It's trying to match a string with the given pattern then extract it.
How do you connect to discord API or i may say your bot
Well iirc default discord.py uses logging now so you have to do it trough logging module.
where is login setup for dpy?
Here is an example -> https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
at the botton
oh and in duration_regex what's the syntax, I totally don't get it
I don't need this tell him -_-
That is just a raw string to match, "r" meaning "raw" followed by '' encased is the pattern (\d+)([hms])
and my task is at the top
ohh and lastly \d+ does what? I understood the rest
so what do I do?
It matches a single digit, here is a visualization -> https://regex101.com/r/4Hm2je/1
This in particular tries the match any digit after the letters h, m or s
ahh I get it
thanks a lot
Someone will look into it I'm bit busy
ig I should learn abt re module a bit more
@sonic vapor pick request
It's also in order, for example it has to find a h2 match first before it can match with m or s.
Np :3
okay
So I am trying to make a discord bot. The command is /locate and I want it to be shown like the image I attatched. I also want the user to input a "player_gamertag" into the box as shown by the picture. How can I d this?
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
@bot.command(name='locate')
async def locate(ctx, player_gamertag):
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
Here is an example.
Can you explain it to me? Im confused
I recommend looking at the exmaple as well.
Sure, what part isn't clear?
I am. im new to this and have no idea what im looking at.
all of it ๐ข
The example provides a simple bot for you to start. You're doing it right with a message command but slash command have a different method of making a command.
What line should I start looking at for what I need? I genuinly have 0 idea what im looking at...
What is a "guild"
A guild represent what we call a server. Guild is Discord's way of saying that.
so I would put the server ID for mine?
Yes, that is needed so that the bot knows where to copy the commands to. Otherwise you will register them globally what otherwise can take up to an hour.
This way you create a development "guild" so you can use them instantly.
Okay, I have that part done
Nice! Then you need to fill in your token on the bottom of the script and you can try it out.
Are you using Discord.py?
from typing import Optional
import discord
from discord import app_commands
Yes that is what the script imports, did you install Discord.py or did you install py-cord or nextcord?
idk
which one should I have downloaded?
Grab your terminal and input some commands for me
both not found
And this? pip show discord && pip show discord.py
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
guys when i hold shift and click on copy message id it gives me something like this:
343944376055103488-1123628370228416593
but when click on the 3 dots and then copy message id it gives me something like this :
1123628370228416593
what is the diffirence between them ?
First is the channel id then the message id
Other one is just the message id
i see, thx
@slate swan pip uninstall discord.py && pip install discord.py
Try this, just a re-install.
Oki gl
pip install -U discord.py shorter
Ty haven't worked with pip in ages
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)
# In this basic example, we just synchronize the app commands to one guild.
# Instead of specifying a guild to every command, we copy over our global commands instead.
# By doing so, we don't have to wait up to an hour until they are shown to the end-user.
async def setup_hook(self):
# This copies the global commands over to your guild.
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
Do I need this?
The green stuff? No.
what green stuff?
The class? Yeah, it's actually recommended to use a subclass. But you can shorten it -> ```py
class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
if I only want 1 input, I just remove second value right?
@client.tree.command()
@app_commands.describe(
first_value='The first value you want to add something to',
second_value='The value you want to add to the first value',
)
Sure
ty
yk how some bots it responds and says "only you can see this"
how do I do that?
Just play around with it see what it can do, you can move to a more robust method of "playing around" once you get the hang of it more. You might not reach it but the current API limit of "guild refreshing" is at 1000 times.
That is called ephemeral that you can apply when sending a message.
Okay, Ill cross that bridge in a few minutes lol
# This context menu command only works on members
@client.tree.context_menu(name='Show Join Date')
async def show_join_date(interaction: discord.Interaction, member: discord.Member):
# The format_dt function formats the date time into a human readable representation in the official client
await interaction.response.send_message(f'{member} joined at {discord.utils.format_dt(member.joined_at)}', ephemeral=True)
``` Here is an example with the show join date command.
When I change the command, should I remove ctx?
async def locate(ctx, player_gamertag):
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
You can also checkout the docs that also specifies a lot of what I'm saying.
Wups
async def locate(ctx, interaction: discord.Interaction, first_value: int):
Since that command relies on an older still supported method.
or async def locate(interaction: discord.Interaction, first_value: int):
so i get rid of that?
Both isn't possible.
ctx is for messages command and slash commands use interaction.
so how would I get the bot to send a message to the author?
await interaction.user.send("Hi!")
that will work if the user sends the command in the channel?
Yes since it's embedded in the interaction.
You can find more attributes and functions here -> https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction
okay, thx
When I do the command, I want it to make it so only you can see this message. And it to say "TorqueBot is thinking."
Then I want it to update once the code is finished to "Check your dms"
Thinking is happening when an interaction could possibly last longer than 3 seconds.
How do I get it to do that
To ensure this happends you need to defer the command in order to let Discord know you are still processing it.
await interaction.defer(ephemeral=True)
await interaction.response.defer(ephemeral=True, thinking=True)
When responding we respond to the Discord callback. Letting it know we are either finished or still doing something.
And then when its done, how do I get it to change its message to check your dms?
i dont understand
Let's make a command.
async def locate(interaction: discord.Interaction, player_gamertag: int):
await interaction.response.defer(ephemeral=True, thinking=True)
try:
if ctx.message.channel.type == discord.ChannelType.private: # Check if the message channel is a DM
await ctx.send('My apologies, but you cannot use this command in private messages.')
else:
auth_url = "https://x-bot.live/api/postman/auth"
auth_headers = {"Authorization": api_token}
auth_response = requests.get(auth_url, headers=auth_headers)
auth_data = auth_response.json()
xbl_auth = f"XBL3.0 x={auth_data['userHash']};{auth_data['XSTSToken']}"
profile_url = f"https://profile.xboxlive.com/users/gt(%7Bplayer_gamertag%7D)/profile/settings"
profile_headers = {
"X-XBL-Contract-Version": "2",
"Authorization": xbl_auth,
"Accept-Language": "en-US",
}
profile_response = requests.get(profile_url, headers=profile_headers)
profile_data = profile_response.json()
player_xuid = profile_data["profileUsers"][0]["id"]
friends_url = f"https://peoplehub.xboxlive.com/users/xuid(%7Bplayer_xuid%7D)/people/social"
friends_headers = {
"X-XBL-Contract-Version": "5",
"Authorization": xbl_auth,
"Accept-Language": "en-US",
}
friends_response = requests.get(friends_url, headers=friends_headers)
friends_data = friends_response.json()
friend_count = len(friends_data["people"])
except KeyError:
await interaction.response.send_message('Error fetching friends list')
await interaction.response.send_message('Error fetching friends list')
When there is a key error I want the message to change to error fetching friends list
@cloud dawn Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Improved Locater Bot\v2.py", line 17, in <module>
bot = commands.Bot(command_prefix="/", intents=discord.Intents.all())
NameError: name 'commands' is not defined
@slate swan ```py
@client.tree.context_menu(name="test defer")
async def test_defer(interaction: discord.Interaction):
await interaction.response.defer(ephemeral=True, thinking=True)
# Processing (Ignore the code)
import asyncio
asyncio.sleep(5)
# End
#####
await interaction.delete_original_response()
await interaction.followup.send(content="Done! Check your DM", ephemeral=True)
ty
Don't use any of the old code.
ok
where does the prefix go?
What does thinking do??
No where since were making a slash command bot. It's always set to /
makes your bot say "bot is thinking" while it performs a task
I feel stupid
Traceback (most recent call last):
File "C:\Users\Josh\Desktop\Improved Locater Bot\v2.py", line 18, in <module>
client = MyClient(intents=intents)
NameError: name 'MyClient' is not defined
In the bottom where it normally says member is typing??
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Where does it say then??
it sends a message
Oh ok
https://paste.pythondiscord.com/daguqusaka
Copy this code and fill in your guild id and token.
kk
i think ive got it ill lyk
@cloud dawn Traceback (most recent call last):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "C:\Users\Josh\Desktop\Improved Locater Bot\v2.py", line 38, in locate
if interaction.message.channel.type == discord.ChannelType.private: # Check if the message channel is a DM
AttributeError: 'NoneType' object has no attribute 'channel'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\Josh\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'locate' raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
if issubclass(interaction.channel, discord.DMChannel): # Check if the message channel is a DM
This is more specific and doesn't require message intents.
Wups hold on don't think this is correct.
There edited @slate swan
I do recommend testing since I'm coding blind.
ty
what is wrong here
!indention
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
my indentition is fine
how?
how?
please help
this makes no sense
Indentation is very fine indeed 
The code after try isn't the same as anywhere else and above is also really inconsistant.
your if statement on 699
my if statement
How do you execute your code?
run it on the top right
no on zagzag.py
oh
and you're accessing ./spam.txt
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 694, in message
file.writelines(f"{str(message.author.id)}\n")
ValueError: I/O operation on closed file.
what is this error
my file is closed?
The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.
See also:
โข !tags with for information on context managers
โข !tags pathlib for an alternative way of opening files
โข !tags seek for information on changing your position in a file
The file parameter
This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.
An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.
See !tags relative-path for more information on relative paths.
The mode parameter
This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.
'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)
you're using r+ operation
oh
You are trying to modify the file outside of the context.
Has nothing to do with the r+ operator.
file.writelines(f"{str(message.author.id)}\n") is outside of the context but you still try to do operations on the file.
outside context
Hi guys, I made a bot and it needs to send some files in a channel plus in the users dms. Whatever I put first in the code works. for the second one, it just sends it as a file that is not available
files = [nextcord.File(generated_image, filename=f"FreeAI_{i+1}.png") for i, generated_image in enumerate(generated_images)]
await channel.send(f"{member.mention}\n**{prompt}**", files=files)
await member.send(f"Your generated images are ready!\n**{prompt}**", files=files)
@formal basin
(sorry for ping)
Then why would you ping them
Cause he just helped someone 20 mins ago
They were helped
What is generated_image?
can someone help me with this error
show full code
Oh, yeah
2023-06-28 12:47:21 ERROR discord.ext.tasks Unhandled exception in internal background task 'change_status'.
Traceback (most recent call last):
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/ext/tasks/init.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "/Users/hervans/Downloads/Hervy bot/main.py", line 16, in change_status
await bot.change_presence(activity=discord.Game(next(bot_status)))
File "/Users/hervans/Library/Python/3.8/lib/python/site-packages/discord/client.py", line 2040, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
AttributeError: 'NoneType' object has no attribute 'change_presence'
generated_images are the images to send
The discord.File object isn't supposed to be used more than once, anyways
may someone help with my error above.
so define it twice ?
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.add_money' raised an error: TypeError: object NoneType can't be used in 'await' expression
Can u send the code??
Can u tell the values of activity and status_str ?
bot_status = cycle({"Type ?help for commands", f"Watching {server_count} servers.", })
@tasks.loop(minutes=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(bot_status)))```
Tbh the error is pretty clear
Check the docs there is an example on how to set a presence
That should help u understand what u did wrong
the task runs before the bot is ready
Which means you're trying to change the bot's presence before the bot is ready
what u told me yesterday didnt work
so how can i make that not happen
What did you try?

lies
no
Considering you're in the ddevs server -> #697138785317814292 message
Pottr.io's simple dashboard is accessible via computers or mobile devices, allowing users to easily track, log, and take action on real security threats. Pottr.io offers features such as a geographical map showing the locations of threats, information on what vulnerabilities are being attacked, and threat levels that quickly show the risk of sys...
this domain exists 

i am
any errors?
You have an error in the console you probably don't give
not possible
Consider using
channel = client.get_channel(...) or await client.fetch_channel(...)
Then you have an error handler eating your errors
can you print channel varriable to console
there is second part
That's cool, I said to use that
The or is not there for you to choose, it's a logical or
It's one valid line
if .get_channel doesnt find the channel in the cache it will fetch it from the api
First it tries get_channel if it returns None it will use fetch_channel
And if it returned None, you'd have an error - which you're likely eating because of an error handler
!e ```py
print(None or "valid channel")
print("valid channel" or "another valid channel")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | valid channel
002 | valid channel
if the first value it truthy it will use it
else it will use second option
you dont need to check if channel exists now when you are using .fetch_channel
the if most likely always will be True unless you paste wrong channel id but it will throw error anyways
I'd be nice to share the entire file
any error handlers?
im asking if you defined any error handlers in code
Yeah, then you likely have an error handler making all your errors ignored
So look at your code for such an error handler
why dont you just disable it for dev purposes
ctrl + f -> search for error
Then find it, you may also want to consider using cogs
^
no you type error only
... for real? Never used ctrl+f in your life 
it will show you all occurances of the error word in the file
It's the same
Just for one file instead
you said there is error handler and now there is not
Well you definitely have something
is it your code
Find the error handler
^
Is it your code
Then unless you have serious memory issues, you'd know how an error handler looks like, as well as where it is
No, not in 6 days
hmm 200 line per day avg
pick up speed when?
If you really have forgotten then consider going to the doctor to be fair, such memory losses are probably serious
oh my fucking god
or he just dosent know what an error handler looks like
So it's not your code, don't lie lmfao
gimme an example
ah lets focus on the problem
Waiting for them to find the error handler for now
hmm tru
Yeah, ask your buddy GPT
gl
Don't forget to keep the same chat conversation so that it has context 
Does asyncio.sleep() accepts float like 1.5?
copilot >> gpt 
Yeah
Yet most people don't know what they're doing
Hi,
How do you make the type status say how many servers the bot is on?
You want to make fun of yourself like mr been but you can't.
/:
"mr been" 
You can't ๐คฃ
it it possible to put clickable links in code blocks on embeds?
No
no
https://www.a.com
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the clientโs presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
I've been trying to print an error line when an error occurs, but i can't do that using on_command_error, does anyone have any tips?
what error and where does it occur
Why can't you do it with that event
there is an on_error for generic ones outside of slash command and normal command scopes
views have on_error too
Is there a way to turn a reddit link into a mp4 or gif link so then when a bot pulls from a subreddit, it sends a actual playable video?
example?
I'm currently using PRAW to pull posts at random from subreddits, see current code below:
subreddit = reddit.subreddit("- - -")
all_subs = []
top = subreddit.top(limit = 50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
await ctx.send(url)
Images and everything work fine, but of course if a link to a video is posted it is unable to send in a playable fashion. Is there a way to make it convert backend into a GIF/MP4 that will be posted in a playable format.
I am trying to download a video using the below code in Python.
import urllib
dwn_link = 'https://class.coursera.org/textanalytics-001/lecture/download.mp4?lecture_id=73'
file_name = 'trial_video...
you can look into it
with open(...) as file:
...
# file is closed here
file.writelines(...) # attempting to write to file here
Context managers (with keyword) close resources at the end of the block
With files, the lock on the file is dropped at the end of the block (you can't read or write to it again)
What's new
made a cog but im getting something in the terminal
its awaitable
RuntimeWarning anc BotBase.add_cog was never awaited
BotBase.add_cog was never awaited
heres the code if u want it
no i dont need the code i already told you whats wrong
ok
the error message already tells you
did you solve it?
PS C:\Users\Melih\Desktop\dearningbyloing> py main.py
Traceback (most recent call last):
File "C:\Users\Melih\Desktop\dearningbyloing\main.py", line 4, in <module>
bot.run_discord_bot()
^^^^^^^^^^^^^^^^^^^
AttributeError: module 'bot' has no attribute 'run_discord_bot'
PS C:\Users\Melih\Desktop\dearningbyloing>
why do i get this error
`import bot
if name == 'main':
bot.run_discord_bot()`
Because your bot module doesn't have such function ยฏ_(ใ)_/ยฏ
im pretty new to this so i really didnt understand you lmao
You coded it somehow
im watching this guy on youtube and i just followed his steps and tried to run it
You should understand what you doing
Traceback (most recent call last):
File "c:\Users\no\OneDrive\Desktop\BotStarter\main.py", line 18, in <module>
asyncio.run(main())
File "C:\Users\no\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\no\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\no\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "c:\Users\no\OneDrive\Desktop\BotStarter\main.py", line 15, in main
await load()
File "c:\Users\no\OneDrive\Desktop\BotStarter\main.py", line 10, in load
for filename in os.listdir(".\cogs"):
^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [WinError 3] The system cannot find the path specified: '.\cogs'
pasting is silly of me
thats the code
ive looked at the error but it doesnt show the error properly
if yk what i mean
You have cogs folder?
should i try doing C:\Users\BotStarter\cogs.py
ohhh
got a new error
discord.ext.commands.errors.NoEntryPointError: Extension 'cogs.cog' has no 'setup' function.
wait hold on
Ever heard of hosting?
yes
Hey I'm looking for bot devs if anyone is interested. Message me for more information
๐
Does anyone know the function that allows for the command to pop up in chat? I can get it to search but it doesnt show up like a bot command for viewers to see (it works just not the way I want it)
^the answer is Slash Commands. I got it! Thanks.
How do you respond to a interaction a second time?
interaction.followup
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
Doing this gives me a webhook error
discord.app_commands.errors.CommandInvokeError: Command 'lookup' raised an exception: TypeError: 'Webhook' object is not callable
That's because that's not how you use webhooks
You don't call the discord.Webhook object, you call its methods
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
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.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be 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 to send.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
@novel apex
How?
just dm the bot
Ok
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
@commands.has_permissions(manage_channels = True)
@commands.bot_has_permissions(manage_channels = True)
async def unlock(self, ctx, channel: discord.TextChannel, *, reason = None):
guild = ctx.guild
everyone_role = guild.default_role
if :
await ctx.send("The channel is not locked.")
else:
await channel.set_permissions(everyone_role, send_messages = True)
await ctx.send("Done")
what should i add in if to make this work
if True will make it work
huh really? I want the bot to check the permission of everyone_role in the given channel first and if send_messages=True then return channel not locked
See, that's a better explanation
Well, there you go ๐
!d discord.TextChannel.permissions_for/overwrites_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
@commands.has_permissions(manage_channels=True)
@commands.bot_has_permissions(manage_channels=True)
async def unlock(self, ctx, channel: discord.TextChannel, *, reason=None):
guild = ctx.guild
everyone_role = guild.default_role
if channel.overwrites_for(everyone_role).send_messages is True:
await ctx.send("The channel is not locked.")
else:
await channel.set_permissions(everyone_role, send_messages=True)
await ctx.send("Done")
@winter token
Then you pass the role and check the permissions
ok ty
You do realize spoon feeding is just completely pointless and shit? Not helping anyone by doing that
!d discord.TextChannel
class discord.TextChannel```
Represents a Discord guild text channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelโs hash.
str(x) Returns the channelโs name.
Send another error then
what does this mean?
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
fixed it but now i have another problem wait
class TimeConverter:
def converter(self):
duration = None
total = 0
duration_pattern = r"(/d+)([dhms])"
duration_values = re.findall(duration_pattern, duration)
for value, unit in duration_values:
if unit == "d":
total += duration * 86400
elif unit == "h":
total += duration * 3600
elif unit == "m":
total += duration * 60
elif unit == "s":
total += duration
return total
kindly help regarding this
This is an experiment that is only available to a limited number of users.
What this article covers:
What are Apps?
How to add Apps to a DM or Group Message
Desktop/Browser
Mobile
Frequently A...

the bot is not unmuting automatically after the given duration is over
I have a question nobody can answer
eh the regex i think is wrong....
i think change forward slash to backward slash instead
because i've asked everyone
and in the for loop you are using duration instead of the value variable
actually nobody can answer
?
so basically
yea i fixed that
oh lemme try
I've been trying to connect to a dm call or a gc call for the past year and have gotten no luck. either people don't want to answer or they don't know it
ive used both a bot and a account nothing works
not working
its like impossible
any one of them
I just cant figure it out
at all
All right so, bots cannot call users and cannot be used in GDMs, that's one part solved.
what about accounts
The other part is against the terms of services of Discord and will get your account terminated/banned
broo you dont understand your like the 200th person to tell me that ๐ฆ its the only thing I dont know
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
(Krypton, do you recommend I ask my question here (see channel description, "questions") or in a help thread?)
class TimeConverter:
def converter(self):
duration = None
total = 0
duration_pattern = r"(\d+)([dhms])"
duration_values = re.findall(duration_pattern, duration)
for value, unit in duration_values:
value = int(value)
if unit == "d":
total += value * 86400
elif unit == "h":
total += value * 3600
elif unit == "m":
total += value * 60
elif unit == "s":
total += value
return total
``` updated code still wont unmute the user after given duration is over
fiiiine
Then don't ask 200 times about something that is against ToS
but do you know how to do it though like dont tell me but is it even possible
Probably better in #1035199133436354600 with a good title, otherwise you can try #async-and-concurrency
As a user can join a call, yes it's possible
what you u put as ur duration when u using the time converter class
i did $mute @user 1s
can i see the whole mute command?
here
Hey how to make my discord bot stream videos in voice channels?
You can't
Yes
@winter token you cant do this:
member: discord.Member or id = None
i dont think u can do this in a function
it works
really? huh
And why not just put member: discord.Member 
Thats sad :/
but wait i can play songs tho
What you're doing is so cursed
just the time thing wont work
xd
.-.
I wanted it to accept id as well
wow total_duration = TimeConverter.converter()
u nvr put in the durationm
how can I make my discord bot open a new websocket connection in the same vc
And that's the purpose of member: discord.Member
pass it in the duration.-.
nvm
It will accept user mention, user ID, user name and probably some others
change both of them
i didnt know that
Bots cannot be twice in the same VC if that's your question
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberโs hash.
str(x) Returns the memberโs handle (e.g. `name` or `name#discriminator`).
not like duplicating it just open a new connection and close the old one
discord.py will make the parameter converter for you
still not workinggg
This works by checking if the string is a mention, an ID, a nickname, a username + discriminator, or just a regular username.
Exists for all of these https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#discord-converters
thx
eh theres alot problem of ur mute command
your timeconverter is correct just themute command
where
this should be awaited
user = self.bot.fetch_user(id)
Then dunno, never cared about voice channels
okay, how do I know if i need to await in such case
actually THIS : await guild.user.add_roles(mute_role)
should just use await member.add_roles(mute_role)
user = await self.bot.fetch_user(id)
eh
ok in the discord docs it will state if it need to be awaited or not such as if it says it is a corotine command
Read the docs, if it says it's a coroutine you await it
oh
And usually every fetch_ needs to be awaited
ok
i mean i have created a fixed of your mute command but eh i dont really wanna spoon feed you as @slate swan said
Good
its fine, just tell me where im doing wrong
eh
await member.add_roles(mute_role)
await ctx.send(embed = embed)
if duration == True:
duration = TimeConverter.converter()
await asyncio.sleep(duration)
await member.remove_roles(mute_role)
await ctx.send(f"{member.mention} has been unmuted succesfully.")
alot of problem in the mute command .-. i mean alot
Then go over them one by one and tell them what's wrong, that way they learn more than copy pasting an entirely fixed command :)
in theory yes
but if u dont want to change it
you can use this instead
typing.Union[discord.Member, int]
this basically just allows the function to accept both types of inputs.
but u need import typing
o
i mean ya so just do the converter instead
alright
of both id and member
if id == True
change to
if isinstance(member, int)
isinstance() is a built-in python function is used to check if an object belongs to a specified class or if it is an instance of a subclass.
No, that will just go away
You won't have an if check as that's the point of a converter, converts the argument to a discord.Member object
So you just need to do the lower part where you await member.add_roles(...)
the code is confusing me ,...-.
typehint the arg as a Member, if it's not a member then a MemberNotFound exception will be raised ๐ฆ
Then always using fetch_ is not really good but you can keep that aside at the moment
Then your TimeConverter class won't know where duration comes from out of no where
You'll have to pass it as argument
okay so when im in the learning phase should i minimize its use? and when if fetch_ especially used
You should use it when you need it
Considering it always makes an API call, you should only use it when the cache doesn't have it
E.g. to get a user by ID you'd do
user = bot.get_user(ID) or await bot.fetch_user(ID)
so that you first use get_ to get from cache, and if it returns None aka not in cache, you'll use fetch_ and make an API call
Make some sort of get_or_fetch function if you need to return an object from it's ID
Then for your time converter, consider using https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#basic-converters and then you can do something like
def time_converter (argument):
# your converter stuff
# ...
async def mute(self, ctx, member: discord.Member, duration: time_converter = None, *, reason = None):
Just wondering , can discord bots become owner of servers
oh same thing with roles and all?
yup
???
mine wont work if i pass an arg?
?
def converter(self, duration):
total = 0
duration_pattern = r"(\d+)([dhms])"
duration_values = re.findall(duration_pattern, duration)
for value, unit in duration_values:
value = int(value)
if unit == "d":
total += value * 86400
elif unit == "h":
total += value * 3600
elif unit == "m":
total += value * 60
elif unit == "s":
total += value
return total
No, though they can create servers only if they're in less than 10 servers
Ahh thanks , so if i leave a server in which only my bot and i were present . what happens
No need of self and you probably want to name it better
its a class
You will have to delete the server
Does discord.py still count it in guilds list? or like what
No, use the converter as mentioned above
So need to make a class etc.
Create a converter function that will be used as type hint
what happens if i am not . and then using guild.create_invite ask for an invite back? is there a way
You cannot leave a server you own without deleting it, that's how Discord works...
There is no leave button if there is only you and bot
Ah yeah, even this
if message.author.id == client.user.id:
return
author_id = message.author.id
curr_time = datetime.datetime.now().timestamp() * 1000
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)
if len(author_msg_times[author_id]) > max_msg_per_window:
try:
minutes = r.get(f"1 {str(message.guild.id)}")
min = int(minutes.decode("utf-8"))
if f'1 {message.guild.id}' not in r:
pass
else:
duration = datetime.timedelta(minutes=min)
await message.author.timeout(duration)
embed = discord.Embed(title="User muted", description=f" {message.author.mention} has been muted", color=discord.Color.blue())
embed.add_field(name = "Reason",value = "spamming")
embed.add_field(name = "Mute duration",value = f"{min} minutes")
for i in range(1):
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"log {str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)
except KeyError:
pass
```so my bot is spamming the message.channel.send so I did for i in range(1): but still spamming it
how do I fix
did that and got the erroe Error occured: Command raised an exception: TypeError: expected string or bytes-like object, got 'int'
Error says all
the for i in range(1) has no purpose there
It expected a string but you gave an int to whatever function
just git rid of it?
how?
without it it still sends a single message
still spams though
hmm idk
when in need help ask chat gpt
if len(author_msg_times[author_id]) > max_msg_per_window:
try:
minutes = r.get(f"1 {str(message.guild.id)}")
min = int(minutes.decode("utf-8"))
if f'1 {message.guild.id}' not in r:
pass
else:
duration = datetime.timedelta(minutes=min)
await message.author.timeout(duration)
# Check if the user has already been muted to avoid sending duplicate messages
if not any(role.name == 'Muted' for role in message.author.roles):
embed = discord.Embed(title="User muted", description=f"{message.author.mention} has been muted", color=discord.Color.blue())
embed.add_field(name="Reason", value="spamming")
embed.add_field(name="Mute duration", value=f"{min} minutes")
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"log {str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)
except KeyError:
pass
i gave 1s
thats what they suggested 
Well the issue is most likely somewhere else, where you're giving an int instead of a string
did u add a ""
no
.-.
bruh
there u go
await member.add_roles(mute_role)
await ctx.send(embed = embed)
if duration == True:
tduration = converter(duration)
await asyncio.sleep(tduration)
await member.remove_roles(mute_role)
await ctx.send(f"{member.mention} has been unmuted succesfully.")
Why do you still call a converter function
I told you to get rid of that entirely and use a converter as type hint
^
forgot to remove that line
im usinga as typehint
I just asked ai look ```py
if not hasattr(message, 'bot_response'):
await message.channel.send(f"{message.author.mention} no spamming allowed")
log = r.get(f"log {str(message.guild.id)}")
log2 = int(log.decode("utf-8"))
logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
await logging_channel.send(embed=embed)
# Set a flag to prevent the bot from sending another message
message.bot_response = True```
did it work?
It gave me this
worked now thx
does it work?
Im checking now
ok
What part exactly?
u said the bot will accept id as well using discord.Member right? I am confused abt that
You can type hint most parameters to a discord type, e.g. member: discord.Member or role: discord.Role. discord.py has internal converters, e.g. discord.ext.commands.MemberConverter that will convert whatever you give as argument when executing the command to that specific type.
Each converter accepts different input, for the member converter you can give
- ID
- Mention
- User name
- Global name
- Guild nickname
Then when you execute the command, for example !test 562359123086409729 or !test @krypton.ninja it will convert the member parameter to a discord.Member object directly and you can do various things with it
There's nothing to do more than add the type hint to the discord type and you will end up with the object type you want
Converters will also throw errors if a user, role, etc. is not found, so there's not much you need to do
@formal basin spamming is not related to your code as it was already said multiple times. You are running multiple processes of the bot or something else like that.
Ran it by myself to show.
Except there is one thing - if you send the messages faster then you will mute the member, you can get 2-3 messages, yes
ohhh now im getting it
Consider restarting your computer or looking at the task manager and kill all those bot instances running in the background
thanks krypton
guys
im getting 2 argument error in this code
from discord.ext import commands
class Command(commands):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send("pong")```
im wondering what argument i should put in
Actually i wonder how that did work and added a command
It didn't
k it doesnt work ill just remove class bruh
have you added the setup function 
no
yeah I asked ai and it works now
k ill just use cog
i alr have a folder
with it in
im just making a botstarter folder for github
@discord.ui.select(
placeholder = "Choose a Role!",
min_values = 1, # the minimum number of values that must be selected by the users
max_values = None, # the maximum number of values that can be selected by the users
options =
)```
How do i use loop in options parameter i want to fetch label value and description from database
Yeah my messages is being sent faster thats why its spamming
how can I fix that
if len(...) == ... + 1
instead of
if len(...) > ...
should be fine i think
does anyone think it would be bad if my bot checked every 2m to see your status and if you where offline it would remove your online role and visa versa?
i mean it will take up alot of resources so if u have the resources go ahead
wym resources
if it is in a class yes
cpu memory
is it for only 1 person or alot of people?
ya add a self. next to to bot.pool.acquire()
hmmm leme see
there also rate limit when using discord api
Global Rate Limit (per token): 50 requests per second
Global Rate Limit (per IP): 1000 requests per 10 minutes
yh I was worried about that
you can check that in here
https://discord.com/developers/docs/topics/rate-limits#rate-limits
so for me best around 30mins?
cos u have to take into account for other commands also
30m is a lot tho because im trying to ping them at times but ig I could manually update it
doesnt have to be auto
i mean around 10mins to 30mins inbetween is fine i guess you need to trial and error
Label for item
send the code defining it
Please put them in a markdown in discord using `
^^^
Oh now i need to copy discord.py src for this ig
@discord.ui.button(label="disable all", row=0, style=discord.ButtonStyle.primary)
async def disable_all(self, interaction: discord.Interaction, button: discord.ui.Button):
for item in self.children:
if item.label == 'enable all' or 'disable all':
continue
item.style = discord.ButtonStyle.green
You can use on_presence_update event instead of checking manually
But still will need to make sure you aren't sending too much requests
For example you can wait some time for user to rejoin and if it doesn't - give the role
The second part of the condition disable all is treated as a separate boolean expression, which always evaluates to True because non-empty strings are truthy in Python.
so instead using or
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
use a list
if item.label in ['enable all', 'disable all']:
@hasty pike
now try if it work
Thanks
you could first get all the commands name in a list first,
# Get the list of commands from your bot instance
commands = bot.commands
command_names = [command.name for command in commands]
then check for duplicates
from collections import Counter
duplicate_names = [name for name, count in Counter(command_names).items() if count > 1]
after that print out the duplicates
# Print the duplicate command names
if duplicate_names:
print("Duplicate command names:")
for name in duplicate_names:
print(name)
else:
print("No duplicate command names found.")
It says the name in the error
indentation
You have members and for on different levels
But they shouldn't be
Slash commands it seems
Hmm, no. It gives CommandAlreadyRegistered
can i see the full command
is there any example of memberconverter
discord.Member
just add this in ur function:
member: discord.Member
can put it in discord mardown?
instead of screenshot
i mean paste ur code in discord
ok.-.
Just create the converter instance and call convert method with context and string
I have that already
wait so u want your own converter or??
nvm I thought i need to mention discord.MemberConverter in code
Both is valid.
i didnt know just doing discord.Member does that all
oh if i were to do it then how to do that?
Imo using MemberConverter is more cleaner for people who don't know about the library.
Same as the discord.Member, just typehint it.
oh lol ty
some weird examples in some website made me confused
abt it
You wouldn't be the first.
so basicaly whats the diff between discord.Member and commands.MemberConverter
async def select_callback(self, interaction,select,) :
for value in select.values:
role = interaction.guild.get_role(int(value))
await interaction.user.add_roles(role)
await interaction.response.send_message(f"Roles added" , ephemeral=True)
I have this an i want if user deselects any option remove that role how to do it?
if len(author_msg_times[author_id]) == max_msg_per_window +1: like that?
The converter is just tied to the object nothing else.
so the working mechanism is like same?
It is the same just that there was a shortcut created for some reason.
alr
I wish I could tell you more, the library is just weird. Hikari has a nice implementation tough.
discord.Member is a class representing a member in a guild, while commands.MemberConverter is a converter class used to convert input into a discord.Member object within command parameters.
not like that
YOOO IT works finally
thanks
So any role the person has would be able to de-select?
Or during adding?
Don't just say something like that and then not help.
i have self roles person can add roles and remove anytime they want
for eg person has selected role 1 and role 2 at beginning and next time he select role 1 and role 3 so remove role 2
Also i'd add that discord.Member just uses MemberConverter to convert. So both typehint are calling the same thing
Im repyling to myself
You mean remove role 1? Since you selected that at the beginning.
Oh sorry I was reading it wrong.
@client.event
async def on_message_delete(message):
channel = client.get_channel(1123900671687675987)
await channel.send(f"Message deleted: {message.clean}")
how do I just send the message deleted
message.content
I think he meant clean_content
there are docs you can always look into
its message.content
!d discord.Message.clean_content
A property that returns the content in a โcleaned upโ manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.
This will also transform @everyone and @here mentions into non-mentions.
Note
This does not affect markdown. If you want to escape or remove markdown then use utils.escape_markdown() or utils.remove_markdown() respectively, along with this function.
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the messageโs hash.
no remove role 2 since it was selected and added in the beginning and after that role 1 and role 3 were still selected
@client.event
async def on_message_delete(message):
channel = client.get_channel(1123900671687675987)
await channel.send(f"Message deleted: {message.content}")```
TBH you should never use clean_content you should always dissalow your bot to mention here or everyone.
why spoonfeed?
Its just one change
Feed me pls'
whats the embed color format
I looked up html color codes
but thats not it right?
use hex
yes
no
its not valid hex
ff0000
yes but its not proper syntax in python
hm
!e print(ff0000)
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(ff0000)
004 | ^^^^^^
005 | NameError: name 'ff0000' is not defined
!hex
!e print(0xff0000)
!syntax hex
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
16711680
ohhh
random commands does not exist
0xffffff
0xFF0000 == 0xF00
I thought it was dat
^^
check if he has that role already essentially its just a toggle
embed.add_field(name=f"Category: <#{message.category.id}>", value='')
Traceback (most recent call last):
File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 29, in on_message_delete
embed.add_field(name=f"Category: <#{message.category.id}>", value='')
AttributeError: 'Message' object has no attribute 'category
A channel has a category not a message, a message has a channel.
message.channel.category
Yep
!d discord.CategoryChannel.mention
property mention```
The string that allows you to mention the channel.
also mention strings properties exist
you can use them instead of this <#{message.category.id}>
Oh and quick tip, be consistant with your code, use either " or '
how much of an issue is that^?
you are inconsistant thats the issue
None just that consistency is appreciated.
oh word
thanks
how do I see who deleted the message?
I swear I have it on the tip of my tounge but
cant spit it out
got it nvm
embed.add_field(name=f"Category: {message.channel.category.mention}", value='', inline='True')
doesnt mention the category?
@swift trench You seem to know Python, why don't you just use the docs?
oh wait can you even do that ๐
I dont understand them at all
ive tried so many times to
No lol
ok
This article is why we need AI
https://www.itgeared.com/how-to-mention-a-category-in-discord/
Conclusion
Itโs currently not possible to mention a Discord category.
All you need
just put into the search box a keyword
true
File "main.py", line 24
channel = client.get_channel(1123900671687675987)
^
IndentationError: unindent does not match any outer indentation level
I dont understand this tho
@client.event
async def on_message_delete(message):
async for entry in message.guild.audit_logs(limit=1,action=discord.AuditLogAction.message_delete):
deleter = entry.user
channel = client.get_channel(1123900671687675987)
nvm just had to look at it from this

๐ฌ
can you add time in embed fields
timestamps
yes you can
word
is this possible to do with inline fields?
timestamp = datetime.datetime.utcnow()
embed.add_field(name=f"Time: {timestamp}", value='', inline='True')
i know you can \n your way on the first column but maybe there's a more elegant way of doing it
yeah there obviously is a special markdown for timestamps
scrolled through and read it still have no idea what i just looked at ๐
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
hey, are there the examples of timedelta in py docs official
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
so lets assume i used in timeout cmd, if I were to timeout the member for 1 hour 1 min and 10 seconds then how I had to execute the cmd?
!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").
do i need to make converters manually or the bot will do it automatically if i use timedelta
what converters
time
if you want the user to provide time in format like 1h then yes timedelta wont understand what 1h is
thats what I wanted to ask ,alright ty
i have that
this is what @unkempt canyon uses
im still having trouble with the time
what about
well I dont understand how it work
how what works
I read everything you sent and tried like 10 different things and nothing worked
so what did you try
timestamp = datetime.timedelta()
embed.add_field(name=f"Time: {timestamp}", value='', inline='True')
I have this rn but it just returns 0:00:00
I tried that also
and you are still just printing it not using discord syntax or helper function to convert it to special syntax
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
and what is your code?
well I was looking it up and I clicked the first link and there was a class for eastern time
so I looked at it
('%H:%M:%S'))

its not about how you get datetime
its how you use it
- get datetime.datetime object
- pass it to format_dt function
- save output of the function and send it
go with this step list
ok thanks
hi i still got an issue, that my commands / event in my cogs are running twice.
this is my main.py```python
import discord
from discord.ext import commands
import os
from apikeys import *
class MyBot(commands.Bot):
def init(self):
super().init(command_prefix= '!',intents=discord.Intents.all())
async def setup_hook(self):
await load()
bot = MyBot()
intents = discord.Intents.default()
intents.members = True
async def load():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
cog_name = filename[:-3]
await bot.load_extension(f"cogs.{cog_name}")
print(f'Extension: {cog_name} succesfully loaded')
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
@bot.command()
async def test(ctx):
await ctx.send("This is a text command")
initial_extensions = []
bot.run((BOTTOKEN))
You probably have the bot running twice
i don't think, i have restart my pc, restart my vsc and i still have this issue
this is one of my cogs ```python
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command()
async def aide(self, ctx):
help = discord.Embed(title="Liste des commandes :", url=None, description=None, color=0x7434EB)
help.set_author( name="Menu Help du bot", url=None, icon_url="https://cdn.discordapp.com/attachments/1122145321535930499/1122145393032040519/20230624_142400_0000.png")
help.add_field(name="Musiques :", value="!join | !play | !stop | !resume | !pause | !music", inline=False)
help.add_field(name="Modรฉration :", value="!ban | !kick", inline=False)
help.set_image(url="https://media.discordapp.net/attachments/1120608535672270939/1123258060983509124/pu.gif?width=747&height=312")
help.set_footer(text="Demandรฉ par : {}".format(ctx.author.display_name))
await ctx.send(embed=help)
@commands.command()
async def music(self, ctx):
await ctx.send("La liste des musiques : black_clover, black_rover, demon_slayer_3, night_dancer")
@commands.Cog.listener()
async def on_member_join(self, member):
channel = self.bot.get_channel(1121386561150386276)
join = discord.Embed(title="Bienvenue dans le serveur de la Neo Destiny ! ", url=None, description=f":tada: Bienvenue {member} :tada:", color=0x7434EB)
join.set_image(url=member.avatar.url)
join.set_footer(text=f"Nous sommes dรฉsormais : {member.guild.member_count}")
await channel.send(embed=join)
async def setup(bot):
await bot.add_cog(Greetings(bot))```
First things first DON'T change anything in he on_ready function
Its supposed to be a function called when the bot loads and in this case you shouldn't try to change the status or anything Just put there a plain
print statement.
Adding extra things in it can cause chaos .
try deleting all that in the on_ready() and mb pu thtere just print("Bot loaded").
if it all fails then idk where tf the problem is
Remove the extra parenthesis in bot.run()
add this before the bot.run()
async def setup():
await load()
await setup()
Code:py class suggest(ui.Modal, title="Suggestions"): type = ui.InputText(label="Type of suggestion") suggestionbox = ui.InputText(label="Enter Your Suggestion", type =TextStyle.long) async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message(f'Thanks for your response, {self.name}!', ephemeral=True) async def on_submit(self, interaction): await suggestion_channel.send(f"The type is {self.type}")
Error:Traceback (most recent call last): File "main.py", line 20, in <module> class suggest(ui.Modal, title="Suggestions"): File "main.py", line 22, in suggest suggestionbox = ui.InputText(label="Enter Your Suggestion", type =TextStyle.long) NameError: name 'TextStyle' is not defined
@hasty pike help pls
I already load
so i should remove the activity change
the type=TextStyle.long in suggestionbox
try change to
type=ui.TextInputType.textarea
try it
if it fails then do @silk wasp 's method
it already loaded in the setup_hook no ?
File "main.py", line 20, in <module>
class suggest(ui.Modal, title="Suggestions"):
File "main.py", line 22, in suggest
suggestionbox = ui.InputText(label="Enter Your Suggestion", type =ui.TextInputType.long)
AttributeError: module 'discord.ui' has no attribute 'TextInputType'```
ok
it fails


.-.
What are you exactly trying
making a modal
oky
I'll get back to you in a while
oky
it still runs twice
wait give me a sec im checking ur cogs



