#discord-bots
1 messages · Page 280 of 1
Tbh if lots of time passed since you created that code and your code style and stack got better I would recommend simply rewriting it from the beginning no matter how big the bot is
especially for person like me from old discord.py
if im gonna rewrite im just gonna create a whole new bot
becuase i dont wanna rewrite anything in that bot
Dashboard interacts with bot through db I assume
So it's not a problem
and to just throw it away idk.
nah but i wanna make a whole new bot
i finnaly can talk about favorite coding language without getting warned
nice
Now try doing that in unity general
idk what im gonna do
uh
what ur problem?
life is problem so every human have problem
wait what new intent?
Adapting text commands to slash is so painful you would better just implement same functionality from scratch
though there is only 3
its very painful
i got bot that will never change to slashcommands
the easiest way to solve it if i get message content intents
everything will be perfect
Or just scam discord for mc intent 
but discord is dum and thinks i got slash command script connected and gives slashcommand badge to my bot
thanks for this idea
minecraft intent 
if i rewrite my bot im gonna do it like anti nuke based or something like that
i am coding an ai
its painful
yeah
i always wondered what that all anti nuke bots do
currently make typos deletion and fix them from list and made bot understand even 1 year old kids responses
Smash that red button
nothing
kick everyone
thats what they do
hmmmmmm
more like nuke
nuke is dump whole server and users dm
My AIAS bot deletes people for sending more than 4 periods in a row.....
got 4k pings from each server
Although it's still better than discord antispam
i know what nuke is
hm if bot would have perms to edit users messages
spam @everyone and delete channels, ban members etc
Nuke is that thing that does big boom
it makes millions of pings
just destroy server lol
Boom boom get outta my room or smth
but how you wanna stop that using a bot
do you have any idea what bot i should do
kick the bot that does it
do that antinuke i wanna see what it does
prevent users from giving others dangerous permissions, prvent adding bots, whitelisting users
Think of 3 ideas, ignore them all, pick 4th
i made a custom bot for a server
Oh no bobux unknown exception alert cya guys
i made a feature for my bot that is crazy secure
if someone gives admin perms to bot then
u need a card to get perms
for real admin dont scan and dont have perms
dam bros got whole error alerting system on satelite
wadafak
Hate this thing
Traceback
worst part about discord libraries errors is that its doubled
cause there is always CommandInvokeError
Yeah screw them
not having errors
like its the same thing 
How I can make the command deleted when it typed?
await ctx.message.delete()?
await ctx.message.delete()
They don't need that much space do they?
bc node gr3 on hosting is full
Actually depends on bot
if u have custom prefix bot
and save server id and prefix in json
☠️
@vale wing you looking for devops
?
you need a database
for real waiting 2 months for disk fix
cant bad host
Well bobux for example logs random 12 numbers every 30 minutes and db size doesn't exceed 2 MB
wym
For what
We got stats
for automation of bobux 
Aw man you didn't even see the beast in action
Lots of stuff is automated already
Even extensions setup function
dam and is the method named _auto_setup
I forgor
Cause I wrote that half of year ago
Almost guessed
def auto_setup(self, module_name: str) -> None:
module = importlib.import_module(module_name, None)
sys.modules[module_name] = module
members = inspect.getmembers(
module,
lambda x: inspect.isclass(x) and issubclass(x, commands.Cog) and x is not Cog,
)
for member in members:
self.add_cog(member[1](self))
self.log.ok("%s loaded", module_name)```
me 2 years ago idk how still it works
src/bot.py lines 35 to 40
def _auto_setup(self, path: str) -> None:
module = importlib.import_module(path)
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and issubclass(obj, commands.Cog) and name != "BaseCog":
self.add_cog(obj(self))
self.logger.info(f"Loaded {name} cog.")```
guys u know whats the worst thing to do to slow down ur bot?
Mine has more lines!
i guess asher modified your code a bit and i stole it from him and modify it also
Probably
x what a great varriable name
You just have condition in separate if statement and I have that in lambda
Yeah could do that as py for _, cog in members
What other kinds of automations were you thinking of
i meant more like outside of python code scope
dockerize if not already, github actions to auto update code on remote server on new version
hm i got ai but its useless in my bot what do i do with it?
cool
and the ai is smarter than gpt 3 i think
🥶
what you use for it?
its private
i meant what library
it isnt using library
LaMDA
its coded in python
Tensorflow
nope
Scikit
you just coded an AI neural network from scratch?
ChatterBot
how can i use the ephemal feature on embeded messages, i tried this but its still visable to everyone:
#code by telcaum
@bot.command()
async def vote(ctx):
await ctx.send(embed=discord.Embed(
title="vote register",
description=f'''hello {ctx.author.name}
(logged in as: user {((str(ctx.author.id)))})
now type &&f for the full list of canidates and other information'''),
ephemeral=True)
without tensorflow or pytorch
only uses re to delete the no needed things from message
i alr told its no using packages except re
I remember how I once had "ai" bot
ephemeral only applies to slash commands
!d discord.ext.commands.Context.send
how it was?
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.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
ephemeral (bool) –
Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. This is only applicable in contexts with an interaction.
New in version 2.0.
So basically when you would make any statement like "sky is blue" bot would reply with "Um actually, sky isn't blue 🤓"
mine is based on fun/serius responses or every kind
No nlp ofc, pure regex
if question.lower() == "is sky blue?":
and have a very nice data collection system
?
like send users messages and take commands via dms
I should probably make it public for educational purposes or whatever
why not
i got very nice data collection system in my bot which is very advanced
well, how?
!d discord.Member.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**.
How it works
for real it can almost get ur location
i cant tell
K sure
bunch of if else blocks
nope
just by chatting with bot
alr i tell how time zone collection works
it analizes what time u use bot most time
and by weather option
which country weather is used the msot
most
Very advanced AI
Jk the one and real AI bot I ever made was this https://github.com/Exenifix/AIAS
It processes your message and reverses its sense
AIAS uses random forest classifier
you know its serious when bot is inside utils
works like normal chatbot?
mine works nearly like gpt
mine can code script (barrely)
hm am looking for a Collab with someone
am really bored
everyone stopped chatting 😓
if i wanted to get the ID members robux clothign games and games visit how would i get all those values?
right now the embed is in a embed object
Do you have a discord bot in the same server as that message?
yes i want to get the values
ID, members, robux etc
Get the message id, then print out the contents to see what it looks like internally
From there you can see the pattern and try to parse the values out
how would i do that from
What does printing that give you?
Is there another alternative to getting the number of messages in a channel for 1 day other than using .history()?
[EmbedProxy(value='``32374568``', name='**ID**', inline=True), EmbedProxy(value='``0``', name='**Members**', inline=True), EmbedProxy(value='``0``', name='**Robux**', inline=True), EmbedProxy(value='``0``', name='**Clothing**', inline=True), EmbedProxy(value='``0``', name='**Games**', inline=True), EmbedProxy(value='``0``', name='**Game Visits**', inline=True)]
this
Try printing embed.fields[0]["name"]
see if it's **ID**
i doubt it do you think there's a easier way
I'm making a guess, if it works like I think it won't be that bad
Actually looks like it'd be embed.fields[0].name
TypeError: 'EmbedProxy' object is not subscriptable
So you can just use a dict comp here
Yea just checked, they're attrs not keys
what i showed you are fields right cuz i saw this
Smth like
dict = {field.name: field.value for field in embed.fields}
Might want field.name[2:-2] bc bold
where did you learn about the thing i forgot what it's called like string something to like shorten ur code
Wdym? The dict comp?
yea
From this discord, you can pick up lots of stuff around here
you just learned it on the fly no yt or anything?
Yeah, I learned to do things the "long" way through tutorials but learned how to write it a different way from here
can someone help me make a discord bot i am new to this bot making xd
Discordpy
oh anything else i need to learn to make a bot like a special program?
yoo it's the ensemble classifier (dtc on crack)
Python and OOP that's it
well i assume youtube has tutorails for it right?
You know python?
somewhat not too advanced
You need to be good at OOP for making bots
u only need functional programming to make it online
Bots are not for increasing your server's online count tho
can't i just host it on my pc
You can run bot in 4 lines
(context: I am C++ bot dev)
Too advanced for this channel
and lets say i learn oop where do i program it like in vsi? or just python in it self
alr I'm gonna go u can handle skids
import discord
from discord.ext import commands
bot = commands.Bot(intents=discord.Intents.default())
bot.run("TOKEN")
That's it
no like is this where i run it
i always used online stuff so i am not sure on windows
Well seems like you need a good editor
IDLE is good enough
Is it? Never worked with it tho 
ur talking to a person who has used nano to code
damn
It's easiest tbh

and the idea i wanna make for it i might need help more than oop
like actual help cause it kinda weird
can i just say what it is
Sure why not
i want it to be able to send me announces in a channel when i post something new on curseforge for my mod ya know
website for mods
Never heard
can i do that though
You need API
api for the website right?
Read, you'll understand your limits
What you can do and what not
Ig
Note: Any registered account which is not a game developer and did not request a key, will be deleted
Figure it out "I have 0 knowledge of it"
oh right sorry
Trynna not to give you false information
btw i saw people turn it into jar files and use txt files
is that possible to make alone?
so i made some code in idle shell can i run on it?
What exactly you want
to run the code so the bot works?
Isn't it better to run file instead 
so like save it and run it?
Yes
so i ran it
like as a normal python file but i can't see it so i assume it worked right
Which code did you run
python?
Show?
and i did get help from yt
do i just send copy and paste
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
# Start the update announcement task when the bot is ready
check_for_updates.start()
@tasks.loop(minutes=15) # Run the task every 15 minutes
async def check_for_updates():
page = requests.get(CURSEFORGE_URL)
if page.status_code == 200:
soup = BeautifulSoup(page.content, 'html.parser')
update_element = soup.find('div', {'class': 'b-post__date'})
if update_element:
latest_update = update_element.text.strip()
await announce_update(latest_update)
else:
print(f"Failed to fetch page. Status code: {page.status_code}")
This isn't full
i am still working this is what i did so far
It's incomplete
oh then time to work more to finish
and can i install discord.py on idle?
linux or windows?
Windows
can you tell me how then i use windows too
Ig you need someone much more experienced than me to guide you here
Or maybe just 'YouTube'
how would i make a command that creates emojis
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") to do this.
in_file = open("emojitest.png", "rb")
data = in_file.read()
in_file.close()
await interaction.guild.create_custom_emoji(name="test", image=data)```
how would i make it where it looks for the file inside a folder
not related to your question but reading and opening a file is a blocking operation
!pypi aiofiles
you should use this
damnnn never knew that
depending on the file it might or might not be a blocking operation
for an image it's fine imo
How it is not blocking here? 
it is always a blocking operation, perhaps you meant that depending on the size of the file the operation could block the event loop for more or less time
while opening a file isn't that blocking, reading one definitely is
^^
opening a file just internally places a pointer/cursor to file content in 0th index
whats the command for dming a user
i want to take text from one user and dm it to a separate user
You mean method?
!d discord.User.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**.
how do you find the user you want to dm
I am running into a problem here, let me give you a code example:
@bot.event
async def on_message(message):
x = await getX()
print(x)
await message.channel.send(x)
async def getX():
return 10
Log:
None
For some reason it always outputs None
!d discord.Client.get_user the docs 🤷
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!e
import asyncio
async def getX():
return 10
async def main():
x = await getX()
print(x)
x = await getX()
print(x)
x = await getX()
print(x)
asyncio.run(main())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 10
002 | 10
003 | 10
Doubt it
could you write an example im kinda confused, no worries if u aren't able to rn tho
What's confusing about it
wait discord.Client.get_user gets the id of the user who ran the command right
its worded as "Returns a user with the given ID" which sorta sounds like you need to already know the id
No, read the docs
wait so you already need to have the id
Yes?
is there a discord.Client.get_id or smth
No
than how do u get the id in the first place
The user’s unique ID.
ok ty
!e
import asyncio
async def main():
x = await getX()
print(x)
x = await getX()
print(x)
x = await getX()
print(x)
async def getX():
return 10
asyncio.run(main())
@dawn stratus :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 10
002 | 10
003 | 10
What do you mean dosent work for discord for sum reason?
How I can get author avatar url
ctx.author.avatar_url not working
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
Author is of type Member
ctx.author.avatar?
Yes 
what is the error for a user with dms off?
!d discord.Member.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**.
Raises
HTTPException – Sending the message failed.
except HTTPException:
could I do that?
yes but you need to import it from discord module
!d discord.HTTPException
exception discord.HTTPException(response, message)```
Exception that’s raised when an HTTP request operation fails.
under discord
ok
I already have a try and except how can I add a second one?
you wanna have same case for two errors or two different cases for two exceptions
different
try:
...
except Exception:
...
except OtherException:
...
thats possible
I never new
thanks
!e
try:
0 / 0
except ZeroDivisionError:
print("No")
except ValueError:
print("Also no")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
No

if you wanted the same case for many errors you can do ```py
try:
...
except (Exception, OtherException):
...
thanks for the info
!E py try: raise Exception except* Exception as e: print(e.exceptions)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
(Exception(),)
wait you know if the bot tries to kick its self will it raise the HTTPException error?
!d discord.Guild.kick
await kick(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`kick_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.kick_members "discord.Permissions.kick_members") to do this.
Why would someone make their bot try to kick itself
idk
yes it will be HTTPException
oh I see
Raises
Forbidden – You do not have the proper permissions to kick.
HTTPException – Kicking failed.
Forbidden is subclass of HTTPException
wait if I check if the member is itself how can I make it go the on_app_command_error
hi i'm trying to use the clash royal api, but when i imports the requests. I have an error "requests" is not accessedPylance Import "requests" could not be resolved from sourcePylancereportMissingModuleSource (module) requests
This is my code ```python
import discord
from discord.ext import commands
import os
from discord import app_commands
from apikeys import *
import requests
intents = discord.Intents.default()
intents.members = True
api_key = ''
bot = commands.Bot(command_prefix="?", intents=intents)
@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.run((BOTTOKEN))```
raise exception
you can create own exception and handle it in error handler
oh true
does it work when you run it?
cause pylance isnt actual interpreter
also tip
for discord bot i wouldnt recommend using requests since its blocking (slowing your discord bot) use aiohttp instead
if you wanna find out more check out !blocking command
no raceback (most recent call last): File "c:/Users/MYOUSSEF/Desktop/app/main.py", line 6, in <module> import requests ModuleNotFoundError: No module named 'requests'
do i need to install it ?
aiohttp is installed when you install discord.py or its forks
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
is it possible to make a discord slash bot and run it as a bot not a client
yes it is
i cant do it
what did you try?
What's the problem then
tried this
import discord
from discord.ext import commands
from discord_slash import SlashCommand
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True
MY_GUILD = discord.Object(id=1133019868292186133) # replace with your guild id
bot = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(bot, sync_commands=True) # Create a SlashCommand instance
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
@slash.slash(name="hello", description="Greets the user.")
async def hello(ctx):
await ctx.send(f'Hi, {ctx.author.mention}!')
@slash.slash(name="add", description="Adds two numbers together.")
async def add(ctx, first_value: int, second_value: int):
result = first_value + second_value
await ctx.send(f'{first_value} + {second_value} = {result}')
@slash.slash(name="send", description="Sends the provided text.")
async def send(ctx, text_to_send: str):
await ctx.send(text_to_send)
@slash.slash(name="joined", description="Shows when a member joined the server.")
async def joined(ctx, member: discord.Member = None):
member = member or ctx.author
join_date = member.joined_at.strftime('%Y-%m-%d %H:%M:%S')
await ctx.send(f'{member.display_name} joined at {join_date}')
@slash.slash(name="test", description="A test command.")
async def test(ctx):
await ctx.send("This is a test command!")
def main():
bot.run('MTE----UgY')
if __name__ == "__main__":
main()
discord_slash is outdated discord.py already has slash commands built in
fady@debian-et8re0j:~/Documents/Code/public/FlareMod$ python3 main.py
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/main.py", line 3, in <module>
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'
fady@debian-et8re0j:~/Documents/Code/public/FlareMod$
should i remove it???
remove discord_slash? yes
okie
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True
MY_GUILD = discord.Object(id=1133019868292186133) # replace with your guild id
bot = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(bot, sync_commands=True) # Create a SlashCommand instance
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
@slash.slash(name="hello", description="Greets the user.")
async def hello(ctx):
await ctx.send(f'Hi, {ctx.author.mention}!')
@slash.slash(name="add", description="Adds two numbers together.")
async def add(ctx, first_value: int, second_value: int):
result = first_value + second_value
await ctx.send(f'{first_value} + {second_value} = {result}')
@slash.slash(name="send", description="Sends the provided text.")
async def send(ctx, text_to_send: str):
await ctx.send(text_to_send)
@slash.slash(name="joined", description="Shows when a member joined the server.")
async def joined(ctx, member: discord.Member = None):
member = member or ctx.author
join_date = member.joined_at.strftime('%Y-%m-%d %H:%M:%S')
await ctx.send(f'{member.display_name} joined at {join_date}')
@slash.slash(name="test", description="A test command.")
async def test(ctx):
await ctx.send("This is a test command!")
def main():
bot.run('MTE---UgY')
if __name__ == "__main__":
main()
fady@debian-et8re0j:~/Documents/Code/public/FlareMod$ python3 main.py
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/main.py", line 12, in <module>
slash = SlashCommand(bot, sync_commands=True) # Create a SlashCommand instance
NameError: name 'SlashCommand' is not defined
fady@debian-et8re0j:~/Documents/Code/public/FlareMod$
if you dont have discord_slash you cant create SlashCommand
so what should i do now
look at the example'
okie
,
subclass a Bot and not Client
okie
but then you dont have to create tree instance
okie
@past dome HI
hello hehe
https://paste.pythondiscord.com/L46A
this is ot workig
Also, you don't have the message_content enabled, so your bot cannot read messages
examples/app_commands/basic.py line 41
@client.tree.command()```
this tree in between matters
And app_commands.describe is for app commands
but you said i donnt nnneed a tree
You don't need to define a tree
yes you dont need to create one cause Bot already creates one for you
okie
how’d u write the command to dm them once you have the id, im bad at reading documentation, sry
its like await User.send(“stuff”) would you have to do like User = “id” or smth
or am i being dumb
Client over Bot any day with slash commands.
true
Hey there. Im very new to discord bots and im trying to fix an old python script.
Im using asyncio.get_event_loop().create_task(run_bot()) To start my "main" function loop.
When trying to run it, i get the following message RuntimeWarning: coroutine 'run_bot' was never awaited self._ready.clear()
How do I have to change this?
show code
Why is it not showing emojis?
how does it look like in code?
primary_path = random.choice(list(RUNES.keys()))
secondary_paths = [path for path in RUNES.keys() if path != primary_path]
primary_keystone = random.choice(RUNES[primary_path]["Keystone"])
primary_keystone_emoji = f':{primary_keystone.replace(" ", "_")}:'
secondary_path = random.choice(secondary_paths)
secondary_lesser = random.choice(RUNES[secondary_path]["Lesser"])
secondary_lesser_emoji = f':{secondary_lesser.replace(" ", "_")}:'
embed.add_field(name='Runes', value=f"{primary_keystone_emoji} - {primary_keystone}\n{secondary_lesser_emoji} - {secondary_lesser}",
inline=False)```
Its not the full code but it is about this
async def run_bot():
location = "Duisburg"
today = get_date_now()
daily_prayer_times = get_daily_prayer_times(location, today)
while True:
if not run_bot_channels:
# print('NO CHANNELS')
await asyncio.sleep(10.0)
continue
time_now = get_time_now()
await bot.get_channel('960804554910339085').send("Time: " + time_now)
print("testttt")
# await client.get_channel('800046347016863757').send(run_bot_channels)
if is_next_day():
today = get_date_now()
daily_prayer_times = get_daily_prayer_times(location, today)
# For testing purposes only:
# daily_prayer_times = ['07:55', '07:56', '07:57', '07:58', '07:52']
for i in range(len(daily_prayer_times)):
if time_now == daily_prayer_times[i]:
print("Sending prayer notification to channels!")
if i == 0:
for channel in run_bot_channels:
bot_channel = bot.get_channel(channel)
await bot_channel.send('Wake Up - It\'s Fajr Time!')
elif i == 1:
for channel in run_bot_channels:
bot_channel = bot.get_channel(channel)
await bot_channel.send('Take a Break - It\'s Dhuhr Time!')
elif i == 2:
for channel in run_bot_channels:
bot_channel = bot.get_channel(channel)
await bot_channel.send('Make Wudhu - It\'s Asr Time!')
elif i == 3:
for channel in run_bot_channels:
bot_channel = bot.get_channel(channel)
await bot_channel.send('Gather For Prayer - It\'s Maghrib Time!')
else:
for channel in run_bot_channels:
bot_channel = bot.get_channel(channel)
await bot_channel.send('Don\'t Sleep Yet - It\'s Isha Time!')
await asyncio.sleep(60.0)```
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
and what is the value of RUNES ?
okay anyways
https://discordpy.readthedocs.io/en/stable/faq.html#how-can-i-add-a-reaction-to-a-message
thats how to attatch emoji to message
its about how to add reaction but process of getting emoji is the same
here the full: https://paste.pythondiscord.com/RU4Q
if you want to have an infinite loop in your bot that does something
use tasks and not a while True loop
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
oh sick I will look into it. thanks alot ❤️
A hands-on guide to Discord.py
Should I use:
primary_keystone_emoji = discord.utils.get(message.guild.emojis, name=primary_keystone.replace(' ', '_'))
secondary_lesser_emoji = discord.utils.get(message.guild.emojis, name=secondary_lesser.replace(' ', '_'))```
this should print Test right? Because for me it is not doing anything. Do I have to call it somehow
python```
@tasks.loop(seconds=10)
async def run_bot():
print("Test")
Is there any simplier way to do this?
guild = discord.utils.get(client.guilds, id=1135157269328302110)
# First emoji
primary_keystone_emoji = discord.utils.get(guild.emojis, name=primary_keystone.replace(' ', '_'))
# Second emoji
secondary_lesser_emoji = discord.utils.get(guild.emojis, name=secondary_lesser.replace(' ', '_'))```
Yeah just get the Emoji string
By putting \ before the Emoji itself on discord
You have to start it
Can you show me an example?
and you copy this text and send via bot
Other than on_invite_create and on_invite_delete are there any other invite based events?
no, only those what else you need about invites
I just wondered if there was, I’m in the midst of developing an invite tracker bot
It should still use the emojis from a specific guild
So if we add the bot to another server, it should still use emojis from our server
yeah thats how it works too
That’s how it works, all you need is the name and code of the emoji and paste it in the response of your command
Can I set too many values in one field in embed and if its yes so how?
what does set too many values mean
Wait
Look there is only one value can I add more?
embed.add_field(name="Server1", value="not ok", inline=False)
no you can only add one value to one field
but you can insert any text to it
with new lines too
no that looks like description
Description
Like this
Not this
you can use markup in description
👍
hm am bored
what can i do when am bored
idk im currently scrolling through discord.py source code and finding random issues so i can contribute xd
currently got this Rapptz/discord.py#9519
Join bobux
We are just at stage of planning content for future version
i can give u idea
oh nice
invite me then
K
Sure I would be thankful
someone wanna explain to me how python -m discord -v command works
discord/__main__.py line 336
parser.add_argument('-v', '--version', action='store_true', help='shows the library version')```
Just shows the version?
surprising
ur the owner of bobux bot?
Yes
oh cool am owner of doggeł inc
im owner of Google INC
Oh mo
for real?

So what the idea is
but for real ur owner of google?
We need a way for spending bobux
yeah want free youtube premium?
@bot.event
async def on_ready():
print("the bot is online")
await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type = discord.ActivityType.listening, name="Hustel Members"))
channel = bot.get_channel(1136780399096385627)
await channel.send("Online")
Why the bot status is online?
it bugs
had that too change in while
if not means there is bug
when the new task list arrives? i need to know a deadline for current tasks @vale wing
i asked u something in dm
hi i need help when i type a command i tell me that it is not found ```python
import discord
from discord.ext import commands
import os
from discord import app_commands
from apikeys import *
import aiohttp
intents = discord.Intents.all()
intents.members = True
cr_api_key = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjYzNDdlY2I3LTc0YTctNDQ0ZS04YzFiLTEwMTAzYTE2MTk2ZSIsImlhdCI6MTY5MTE0MjkxNCwic3ViIjoiZGV2ZWxvcGVyL2FkMzI0NWIxLTc2OTAtMWRlZi03MjVlLThkM2RlZTY5NTk0ZCIsInNjb3BlcyI6WyJyb3lhbGUiXSwibGltaXRzIjpbeyJ0aWVyIjoiZGV2ZWxvcGVyL3NpbHZlciIsInR5cGUiOiJ0aHJvdHRsaW5nIn0seyJjaWRycyI6WyIxOTcuMy4xMzUuMTAzIl0sInR5cGUiOiJjbGllbnQifV19.O7H1f9JjUb5Pr2RpCcaNmCG7lwhel07ySQE5nqkYOaDmDJyW_2bHYCSgQUssq5jg6sqrw0Vs5VJHyO-qVHCEXA'
bot = commands.Bot(command_prefix= "?", intents=intents)
@bot.command
async def test(ctx):
await ctx.send("Salut")
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Clash Royale", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")
bot.run((BOTTOKEN))```
Put parentheses behind the @bot.command
@bot.command()
Then I have to save every ID for each emoji?
i haven't started yet , + it's a api key of clash royale so ...
ty
How i can get meaaage tezt from message id
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
!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.
Isn't it the same Like saving name of each
I don't know if i can ask the question here but i want my bot to communicate with the clash royale api but they ask me a ip adress, do i need to enter a special one because it's a discord bot or i just need to enter my public ip ?
What do you mean theh ask me a ip adress
the allowed ip adress
that can communicate with the api
( i host my bot in vs code)
send ss
i ask this question because i have created a key using my public ip adress and when i test a code it return me API Error - Status Code: 404
ok ty
if not search for your public ip address and add it there
so it was not the ip ... API Error - Status Code: 403 {"reason":"accessDenied.invalidIp","message":"Invalid authorization: API key does not allow access from IP
no because the rest of the message error telling me that my adress ip is not allowed
oh wait
that's when you request?
yes when i enter the ?player [playerTag]
Can I get access to the super-secret-google-employee-website?
Yeah, no
Sounds like an adblocker
Sounds like Brave

hello
Hi...?
Meh
hi
I'm not in denial
I am
I have a reputation as denial already
he was in denial for losing a game probably
so y'all just
occasionally still come back to this channel and help people
nah this channel is long dead
I sent that 2 hours ago

how would i make a command where you insert a server id into a list? I have a list with server id's so if the server id isnt there then the bot will just leave the server, im trying to make a command where i can insert a server id into that list with a command
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
Choose your poision for how you wish to store/validate server ids
Discord api will validate it for you
you are trying to use a varriable that you didnt define yet
!e x = "something" + x
@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 | x = "something" + x
004 | ^
005 | NameError: name 'x' is not defined
but category is defined with the slash command :/
the screenshots you provided dont show that
show full code
you gave me two screenshots that dont even show code lines how am i supposed to know where its placed
i obviously defined the slashcommand before using category object sir
@slate swan
sorry
.. whats so hard about sharing the function code?
@default_permissions(administrator = True)
@bot.slash_command(title = "ticketpanel", description = "Send the ticket panel")
async def ticketpanel(ctx, category : discord.Option(str, "Write here the category id where the tickets will be created")) :
pb = Button(label = "🛒 PURSHASE", style = discord.ButtonStyle.grey)
eb = Button(label = "💱 EXCHANGE", style = discord.ButtonStyle.grey)
hb = Button(label = "📌 HELP", style = discord.ButtonStyle.grey)
mv = View()
mv.add_item(pb)
mv.add_item(eb)
mv.add_item(hb)
async def pb_callback(interaction) :
category = discord.utils.get(interaction.guild.categories, id = category)
channel = await ctx.guild.create_text_channel(name=f'🛒・{interaction.user.name}', category = int(category))
you use category inside pb_callback function
Do you know if your bot has a feature where you can go into any server and set its prefix individually? When someone wants to change its prefix on its server, it doesn't respond guys i need your help?
yes but how can i use the global category object in it ? :)
@commands.hybrid_command( name="prefix", aliases=["setprefix", "prefixset"], help="Allows you to change prefix of the bot for this server") @blacklist_check() @ignore_check() @commands.has_permissions(administrator=True) @commands.cooldown(1, 10, commands.BucketType.user) @commands.max_concurrency(1, per=commands.BucketType.default, wait=False) @commands.guild_only() async def _prefix(self, ctx: commands.Context, prefix): data = getConfig(ctx.guild.id) mod = data["mod"] if ctx.author.id in mod: data["prefix"] = str(prefix) updateConfig(ctx.guild.id, data) await ctx.reply(embed=discord.Embed( description= f":tick: | Successfully Changed Prefix For **{ctx.guild.name}**\nNew Prefix for **{ctx.guild.name}** is : `{prefix}`\nUse `{prefix}help` For More info .", color=0x50101)) else: await ctx.send(" le le
when you need varriable in function you accept it as argument
oh so i have to set the function like that ? :
async def pb_callback(interaction, category : category) :
....```
what you mean by : category
you cant use varriable as typehint
the slash command option
or i have to write = category ?
i doubt it will work
@slate swan do you help me?
command code?
yes

category is None
yeah idk why :/
debug it and see
can you put print("something") on top of your command to see if it runs?
like this
in which line?
man you really dont get python
i would learn it before starting a discord bot project
i am finding a teacher
ishh
would anyone be able to check my bot that ive built a while ago? its not working anymore, and im not even sure why
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What do you mean by "doesn't work"
@hushed galleon that was quick fix by Rapptz
it used to print that it was checking for roles etc, it was working exactly as intented. but now nothing works like it should. i do get my print that says the bot connected to the discord API
i have a few screenshots on my github that shows what it used to do.. i think some updates to the API broke it, it's the only excuse i can find lol
i already have that, i just want to know how i can store an id in a list with a command
looks like my loop isnt starting, not sure of the syntax for that, do i just call my function in my if main statement at the end of my file?
if __name__ == "__main__":
bot.run(disc_token)
check_twitch_online_streamers()
Everything after bot.run wont run
someone knows how to detect when member is changing of voice channel ?
with discord.py
good catch thanks
ok ive changed the code, i do get more print statements now
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
so, if i give myself the role, the bot will remove it, and give me proper print statements.. so i know its got proper rights
also, after.activities does have stuff in it
2023-08-04 19:47:44----------ZeddyBot is checking for roles----------
2023-08-04 19:47:44----------ZeddyBot is Removing LIVE role from renegadezed----------
(<Spotify title='The Startup' artist='Harris Heller' track_id='00WrXhzCC2DO68p5YFKH1A'>,)
2023-08-04 19:47:44----------ZeddyBot is checking for roles----------
ok with the API update, i think the on_member_update event does not hold the activity event anymore, i need to switch to on_presence_update
can anyone confirm my findings?
this is my code now.. the problem now, is that the after object wont have the roles attribute..
@bot.event
async def on_presence_update(before, after):
print(
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------ZeddyBot is checking for roles----------"
)
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if LIVE_ROLE_ID in after._roles:
return
else:
print(
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------ZeddyBot is Giving LIVE role to {after.name}----------"
)
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if LIVE_ROLE_ID in after._roles:
print(
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------ZeddyBot is Removing LIVE role from {after.name}----------"
)
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
https://discordpy.readthedocs.io/en/stable/migrating.html#presence-updates-now-have-a-separate-event
Presence updates (changes in member’s status and activity) now have a separate
on_presence_update()event.on_member_update()event is now only called on member updates (changes in nickname, role, pending status, etc.).From API perspective, these are separate events and as such, this change improves library’s consistency with the API. Presence updates usually are 90% of all handled events so splitting these should benefit listeners that were only interested in member updates.
yeah, thats what broke my bot. but im not sure how to fix the code to make it work
ive switched to on_presence_update to get access to activity
can you show the error traceback you got? im not sure what you mean by after not having the roles attribute
uhh i guess so
cause it's not removing the role if i manually give it to myself, which it should, since im not "streaming"
right, cause changing your roles only triggers on_member_update
i guess the cleanest solution would be registering the same function as a listener for both events
e.g. py @bot.listen("on_member_update") @bot.listen("on_presence_update") async def update_live_role(before, after): ...
oh wow, i didnt know you could stack those decorators
BRUHHHHH its working.. ive been at this for 2 hours, lmao
huge thanks! ❤️
Thanks Delliott !!
is there any other way to define member: discord.member in arg after prefix
how do i make a command where you insert an id, and that id goes into a list
shawneey can you give me some more context
can i use this to dm the same user each time, even if the user isn’t running the command if i have the user id, i couldn’t find info about that lol
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Or if this returns None use this
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
@tepid dagger
no but how do i write a dm to the user once i have the id
ik how to get the id
thats my question bc i am bad at coding
how do i dm the user once i have the id
im making a command where you put a server id, and that server id goes into a list so that the bot is authorized for the server, i did everything else i just need to figure out how to insert an id into a list with a command
this returns User
yea
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**.
is User the actual user
yeah what else
idk
wait do you write it as await User.send(“stuff”)
or do you have to define “User”
User is just a class
you need to get User class instance
and if you wanna get it from id
how
use the methods i linked
Return type
Optional[User]
is that unclear or what
and than u can use User.send(“stuf”) or am i being dumb
why dont you try?
what are you trying to do lol
?
is get_user(id) the entire line
so client.get_user(id)?
if you named your instance client, yes
^
your fine lol
it says “User” not defined
That's just Python in general, not discord.py
you need to save whatever get_user returns
and use tihs method on it
so User = client.get_user(id)?
user = client.get_user(id)
await user.send(“stuff”)
wait what
it says “User” not defined
do i have to make user = User(client.get_user(id)) or smth
dont ask me just try
show code and traceback then
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
full traceback
i belive its so small you can screen shot it
i don’t
The error said otherwise
then show line 31
.
nvm
it works now
👍
i forgot to remove parentheses that i forgot i added lol
do you know any good hosts that arent that expensive
https://discord.com/channels/267624335836053506/965291480992321536
check out pins here
oh, thanks sorry didnt know there was a channel for it
no worries
i put the server id in the list but for some reason the bot still left the server?
Does anyone here know how to use the riot api?
nvm, the code isnt registering thats why lol
Try asking in #1035199133436354600 since its not really related to discord bots itself
It was about a discord.py error with the riot api but ok thanks
Like you said again the error itself is with riot api and not discord bot
what can i do ?
Error?
yes
I mean show the error lol
okay
In my code it's about in a channel with "! Feedback (message)" what to write and when you send it, the message is automatically deleted and replaced in an embed. above should be the author name and image of the sender of the message.
Error not the objective
okay
Where's the code for checking balance?
Are you using a database or what?
bot.client
wait
You ain't committing the changes, thus the balance isn't being updated on the db, it's only being changed locally
how and where ?
Instead of client
What module r u using to access the database?
motor?
except commands.CommandOnCooldown as error:
embed = discord.Embed(title="Cooldown", description=f"Try again <t:{int(time.time()+error.retry_after)}:R>", colour=discord.Colour.red())
await ctx.reply(embed = embed)```
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 86395.70s
ok
You don't
The error will be sent to the command's error handler, not inside the command
Anyone with some Bot coding experience i could really use your help right now.
Im trying to develop my code and instead of having all the command and jargon in one .py file. I wanted to have say a base file for the bot '''edox.py''' , a api/key storage file '''.env''' and then another file that would store the commands '''cogs/moderation.py''' but when i use this method the bot stops responding. But does initially log in.
🤣 haha... Nvm i figured it out
i have a anti bad word system. lets say this is my list = ["test1", "test2"] people can bypass it by doing "test1test2"
how can I fix that?
No one can tell if they don't know how you implemented it
ok but why not use discord automod
wdym
We dont know how to fix your system if we dont know how your system works
oh ok let me show you
^
its bad
and it lets admins say bad words
@client.listen()
async def on_message(message):
if message.author.id == client.user.id:
return
key = f'antibadwords:{message.guild.id}'
if r.exists(key):
if profanity.contains_profanity(message.content) or profanity.contains_profanity(replaceDoubleCharacters(message.content)):
await message.delete()
embed = discord.Embed(title="No bad words please", description=None)
embed.set_footer(text="Censored by better_profanity")
log = r.get(f"logs:{str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"1bad word detected logs: {message.guild.id}")```
this is my system
I use the better_profanity package
Why is that an issue
"its bad"
I don't want admins swearing
why are they admins if they dont even follow your rules
idk
Ok well then it's an issue with better_profanity
why?
there's no way to 100% block all profanity, people will always find new ways to say the words
it's an issue because it doesnt work?
ik
but I have lots of ways to stop that
let me show you
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
well you arent accounting for special characters, regional variations
@client.listen()
async def on_message(message):
if message.author.id == client.user.id:
return
message_content = message.content.lower()
special_characters = r"[.\/,'|*=\-_`!<>+$%^?!1234567890@]"
string_without_special_characters = re.sub(special_characters, "", message_content)
key = f'antibadwords:{message.guild.id}'
if r.exists(key):
if profanity.contains_profanity(string_without_special_characters) or profanity.contains_profanity(replaceDoubleCharacters(string_without_special_characters)):
print("test2")
await message.delete()
embed = discord.Embed(title="No bad words please", description=None)
embed.set_footer(text="Censored by better_profanity")
log = r.get(f"logs:{str(message.guild.id)}")
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
embed.add_field(name="Reason", value="contained bad words")
embed.set_footer(text="Censored by better_profanity")
log2 = int(log.decode("utf-8"))
logging = client.get_channel(log2) or await client.fetch_channel(log2)
await logging.send(embed=embed)
print(f"2bad word detected logs: {message.guild.id}")``` this one is for people who put special characters between the letters
!pate
» windows-path
» pathlib
» relative-path
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Still doesnt account for character variations
check out this for some regex
this is regex
Okay? and?
https://paste.pythondiscord.com/T7KA
this is for people who put spaces in between letters and people who use special letters like î
cool
whats @client.listen()??
It's a listener, similar to @client.event but can be used multiple times to create multiple listeners for events
huh is it in a cog?
No? it can be used anywhere
ok
how can I check if a user is not in the guild?
if user not in guild?
well interaction.guild for slash command
!d discord.Guild.members
property members```
A list of members that belong to this guild.
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
We don't know, you tell us what's not working
also is button.callback even allowed to be used like that
yeah
u cant use callback like that
button.callback needs an async function with interaction as first param
async def foo(inter):
...
button.callback = foo
!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/6GUQ
why is this error handler raising an error when I kick a bot even thoughI made an error handler for it
oh wait
where I can find all the error like Bad argument, missing permission, etc ..
Is there a docs hava all of them?
Somebody can help me?
code:
https://paste.pythondiscord.com/JBBQ
error:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/src/cogs/commands/CompleteOrder.py", line 120, in complete_order
view.add_item(prev_button.callback(prev_callback))
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 324, in add_item
raise TypeError(f'expected Item not {item.__class__.__name__}')
TypeError: expected Item not coroutine
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'completeorder' raised an exception: TypeError: expected Item not coroutine
/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py:1252: RuntimeWarning: coroutine 'Item.callback' was never awaited
await self.on_error(interaction, e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
@shrewd apex
discord.py docs
I want the errors only
https://fallendeity.github.io/discord.py-masterclass/error-handling/
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?#exception-hierarchy
A hands-on guide to Discord.py
Thx
@say.error()
async def say_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply("**Only administrators can use this command")
What is coro?
Coroutine
How I can solve this error
Remove the parentheses:
@say.error() -> @say.error
Ok
I have another question
bot.command()
@has_permissions(administrator=True)
Like this it's should only administrators can use it but if I made this
bot.command()
@has_permissions(administrator=True)
@has_role("say")
It's need to be admin and also have the role or only who have the role can use the command without being admins?
both
Also a good way to answer your own question in your own would be to try it and see
make a custom check
Didn't understand
What's confusing about it
Wydm by make a custom check
@harsh orbit i shared a tutorial b4 ut covers all this
if u had read a bit of it u would know what to do
Can you help me now just in this thing
A hands-on guide to Discord.py
@shrewd apex #1099412777988280324 message
done
I didn't find any thing from what I want
It's only saying how to make has_permission or is_owner etc . Not the answer of my question
A hands-on guide to Discord.py


