#discord-bots
1 messages · Page 245 of 1
ohk
What you trying to do with your code?
https://discordpy.readthedocs.io/en/stable/faq.html#what-does-blocking-mean read the FAQs on docs
discord bot🙂
need a help on this error
You're blocking the event loop 🤷
It just told you in the error
ok
how to fix that
while amount > count:
thats the code thats giving me a error
(btw its a amount: int)
full code
and full traceback pls
because that shouldn't raise that error
!e
while 1 > "amount":
pass
@thin raft :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 | while 1 > "amount":
004 | ^^^^^^^^^^^^
005 | TypeError: '>' not supported between instances of 'int' and 'str'
!e
print("uwu" + 139)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print("uwu" + 139)
004 | ~~~~~~^~~~~
005 | TypeError: can only concatenate str (not "int") to str
a
test
discord.app_commands.errors.CommandInvokeError: Command 'csn' raised an exception: TypeError: can only concatenate str (not "float") to str
how do u fix that
!e ```py
print("string" + 1.23)
@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("string" + 1.23)
004 | ~~~~~~~~~^~~~~~
005 | TypeError: can only concatenate str (not "float") to str
@slate swan you see whats wrong?
dont have no idea what u talking about
you cant add number to a string
its not a string
its a int
the error says otherwise
hold up i have to check again
what are you trying to do? what is the purpose of your command
a gambling bot (for fun)
not real money + not any currency just the bot currency to have fun
and practicing my skills
you have fake currency and you gamble it?
ya
when ever u have 0 it gives u 500
ya
im trying to fix it its giving me lots of errors
where to host discord bot for free?
@client.event
async def on_message(message):
embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
if message.author.id == client.user.id:
return
message.content
if message.embeds:
pass
else:
with open('blocked words.txt') as f:
words = f.read()
blockedwords = words.split()
if any(word in message.content.lower() for word in blockedwords):
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
this is not working
example a blocked word is loser
and if i type lo it deletes
what errors is it giving and what database are you using?
what's not working?
like one blockedword is loser
replit
Tried
and if a type lo it deletes it
what have you tried because my bot is currently hosted on there
Replit and upload robot
?
can you help
this
I have connected my replit with uploadrobot. But by bot is not working like i wanted
I have used huggingface interface api. Uploadbot is making unnecessary request that's i closed my replit
what's uploadrobot??
uptime robot
you could find a server for like $1 a month
its free
mine works fine if its making unnecessary requests just buy a server
uptime robot is free
Ok
can someone help me
mongo db
its giving str or int error idk
Gimme a second lemme get on my pc
ok
!e ```py
bannedWords = ["loser", "lay"] #write the code that grabs the words form the txt
message_content = "I am a los (we will see if it will delete it)"
message_words = message_content.lower().split(" ")
if any(word for word in message_words if word in bannedWords):
print("Banned word detected")
#delete the message
else:
print("Couldn't find the banned words in that message")
#pass ...
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Couldn't find the banned words in that message
@formal basin
its going to be something like that
!e ```py
bannedWords = ["loser", "lay"] #write the code that grabs the words form the txt
message_content = "I am a loser (we will see if it will delete it)"
message_words = message_content.lower().split(" ")
if any(word for word in message_words if word in bannedWords):
print("Banned word detected")
#delete the message
else:
print("Couldn't find the banned words in that message")
#pass ...
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
Banned word detected
see?
yes
u can do the samething with ur code
what do i put in the split
idk if its allowed but wait
@client.event
async def on_message(message):
embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
if message.author.id == client.user.id:
return
if message.embeds:
pass
else:
with open('blocked words.txt') as f:
words = f.read()
blockedwords = words.split()
user_message = message.content.lower().split(" ")
if any(word for word in user_message if word in blockedwords):
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
you should use a database, its way better
than a txt file
thanks\
yw
does someone know how to do a command where u give 2 discord users and it show something like this with the name and profile picture of the user inside a preset photo and then insert 2 emotes with the profile pic of the users??
I mean you essentially do what you said?
Create the image then attach to the embed to send it
You can use Pillow to create the image
!pypi pillow
Why does the unknown interaction error occur when I host the bot on a server when when I run it on my laptop it doesn't occur 🗿
everytime I try to run this python auto closes
don't double click the file then
run it from a terminal
Do they have the same versions of all packages installed?
pip freeze on your laptop and save them to a text file and on your server do pip install -r filename.txt so you are running the same version of all of the packages on both ends
Sorry for the slow response, irl and things on here didn’t leave me much time to try with it all. So I think is missing from my imports. When I try to do slash_commands or app_commands it says things aren’t defined, even when I try to test the code you linked to make sure at least something works with it, it says things like app_commands is not defined. Is there some module I have to install to make this work or something that I’m missing?
Could I employ someone to have a quick look at this please? https://discord.com/channels/267624335836053506/1111084441117397033
if I've got a discord bot for rock paper scissors, and it's using options to decide what text it allows as a choice, but i added a variant of the code that adds more things to rps how would i set up it's options, i was told to ask here
import random
def random_string():
random_list = ["Please try writing something more descriptive.",
"Oh! It appears you wrote something I don't understand yet",
"Do you mind trying to rephrase that?",
"I'm terribly sorry, I didn't quite catch that.",
"I can't answer that yet, please try asking something else."
]
list_count = len(random_list)
random_item = random.randrange(list_count)
return random_list(random_item)
print(random_string())
``` it says that "list" object is not callable in line 13
we can't see your line numbers
this is also pretty irrelevant for this chat 😬
u have to do [] not ()
for the return random_list(random_item)
also u can just do return random.choice(random_list)
Have to do what
how would i make somthing in discord.py i made a cooldown but i want some user not have the cooldown
When accessing something from a list u do list_name[INDEX]
:)
you have to install discord.py
Someone help me with this weird error please.
import disnake as discord
from disnake.ext import commands
class Info(commands.Cog):
def __init__(self, bot):
self.bot: commands.InteractionBot = bot
@ commands.slash_command(name='bot-info', description='Gives you information about the bot.')
async def bot_info(self, inter: discord.AppCmdInter):
embed = discord.Embed(...)
embed.add_field(name='Developer', value='Shrey - `Shrey#2722`')
embed.set_thumbnail(...)
embed.set_footer(text='Use /help to get started!')
await inter.send(embed=embed)
def setup(bot):
bot.add_cog(Info(bot))
This is a very simple cog command bot it gives me error.
Traceback (most recent call last):
File "d:\Shrey\Projects\3P Pie\Extensions\info.py", line 5, in <module>
class Info(commands.Cog):
File "C:\Users\Divi\AppData\Local\Programs\Python\Python311\Lib\site-packages\disnake\ext\commands\cog.py", line 195, in __new__
raise TypeError(no_bot_cog.format(base, elem))
TypeError: Commands or listeners must not start with cog_ or bot_ (in method Info.bot_info)
the traceback says it?
don't name your function bot_info
or anything that starts with cog_or bot_
Commands or listeners must not start with cog_ or bot_
The world would be 10x better if people would take the time to read tracebacks, especially when they're very clear 
Unfortunate
I read it, I didn't realize it has to do with the name of the command itself sry mybad
(in method Info.bot_info)
i suck at coding is that okay
It's not about coding here, it's about reading and understanding tracebacks
i read it, i got this error first time thats why i was confused
thx for the help btw
well, now you know :)
if you aren't understanding a traceback, reread your code & the traceback
I wish docker would give tracebacks why tf it returns empty bodies in a certain container however everything's fine outside 🧐
😭
Raged about it the whole yesterday's evening gonna rage even more today
I have that installed and made sure it’s at 2.2.3
installing it is not the same as importing it
This isn’t giving the role
I’m typing the command and nothing is happening no errors
It used to work
Do you have message content intent
In the code or in discord developer?
Ty I’ll give it a look. I appreciate it
both
I got all intents
your command is probably not running then
Why?
show your full code
!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.
is the role above the bot and are you typing !verify
no
which question
what?
i asked two questions
i can only see one
ohhh yes i type !verify
and no the bot role is higher\
He’s asking 1. Is the role above the bots role & 2. Are you typing !verify
yeah i dont know what happened
Are you sure the bot is running
yes
Doubt that
it is
try running one of your other commands then
the other commands work
What other commands
slash
@client.command()
async def verify(ctx: commands.Context) -> None:
role_id = 1088500965759520838
role = discord.utils.get(ctx.guild.roles, id=role_id)
if role:
await ctx.author.add_roles(role)
await ctx.send("Role was added successfully.")
else:
await ctx.send("Role not found.")
Perhaps try this to verify it's finding the role.
ok
not working
I doubt that you can even run the bot, honestly. Your code at the line 25 is already incorrect
client.remove_command(help)
help isn't defined anyway
why
you need to be more specific than that
it doesnt give me the role
he forgot quotes
That's why it's incorrect
are you sure the id is correct
no im using a website that already makes a help command
What does makes a help command even means
The point is, the help name isn't defined anywhere
when you import discord it creates a help command
yes, and you're trying to remove the default help command?
I already know that
yes
But, your help name still isn't defined
Then, you forgot to add quotes to help within the tuple.
ill make the verify command a slash command
Iirc having more than one event causes commands to stop working? @naive briar
No, if you override the on_message event without calling process_commands method, the bot will not, well, process the commands
ohhhhhhh yes
that is why
thank you guys
Ah yeah, my mistake
Are you talking about import discord.py at the beginning of the code?
what tuple
no
you have to import app_commands from discord
that's the error you got
I’m either an idiot or I never tried that… swore I did… tyvm! Will make sure the slashes actually get uploaded but I really appreciate your time and patience
Hi guys , which are the basic python concepts one should know to use discord.py easily?
i'd say object-oriented programming and the async/await pattern
Any other?
if you learn the two above you will probably already know the smaller ones
I know both , so i can make bots easily , thanks for telling
P
Excuse me, I want to ask, what is the name of the attribute to check roles that have access to certain channels
That's channel attribute, either channel.overwrites or channel.permissions_for, depending on your case
so I want to check whether certain roles can see this channel or not
If it's like that, do I have to redo each role individually? to check whether it can see the channel or not
Yeah that's fine, you can just iterate over them and find out, these are not API calls and not expensive ops
I think so I'll update them once again just to make sure
ok
Oh yeah the server dpy version was outdated thanks for the help guys
hi i have a discord bot and i want him to get all the members in a discord server but when i do this
"member = get(discServer.members, name=datajson[key])"
i only get the bot as a member
class PlayButton(ui.Button):
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer(thinking=True)
songlink = f"https://api.lonelil.dev/fetch/{songlink}"
file_bytes = b_download_track(songlink)
custom_path = "./music/org/"
with open(f"{custom_path}{name}.ogg", "wb") as f:
f.write(file_bytes)
with open(f"{custom_path}{name}.ogg", "rb") as f:
message = await interaction.response.send_message(f"`{name} by {artists}`:", file=File(f, filename=f"{name}.ogg"))
await interaction.response.edit_message(message, content=f"`{name} by {artists}` (updated)")
why does it say that the interaction has already been responded?
do i need to reevinte the bot?
What is datajson[key]? Are there other members with the same name as your bot?
Have you enabled the members intent in your code?
its the name
i enable it on the aplication
do i need to enable it on the code?
deferring is responding, use the followup webhook to send messages
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.
whats the function for that?
thanks
interaction.followup gives you a Webhook object, you can use .send on that
i see
thank you
still the same problem
WARNING:discord.gateway:Shard ID None heartbeat blocked for more than 20 seconds.
discord.errors.InteractionResponded: This interaction has already been responded to before
Can you show your new code?
yes
class PlayButton(ui.Button):
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer(thinking=True)
songlink = f"https://api.lonelil.dev/fetch/{songid}"
file_bytes = b_download_track(songlink)
custom_path = "./music/org/"
with open(f"{custom_path}{name}.ogg", "wb") as f:
f.write(file_bytes)
with open(f"{custom_path}{name}.ogg", "rb") as f:
await interaction.followup.send(f"`{name} by {artists}`:", file=File(f, filename=f"{name}.ogg"))
Hmm this looks fine, can you show the full traceback?
oh nevermind I fixed it, turns out it was the api
sorry about that
Your code which interacts with the api is blocking, you should make it async
If you're using requests, switch to aiohttp
what are the advantages of aiohttp over requests?
@merry cliff
It's still giving the same error
`File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "spikey.py", line 154, in ping
await ctx.response.send_message(f'Pong! {round(client.latency*1000)}ms')
File "/home/container/.local/lib/python3.8/site-packages/discord/interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "/home/container/.local/lib/python3.8/site-packages/discord/webhook/async.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction`
Show code?
I'm trying to host my code on Railway, it's an app that puts Flask and Discord.py together in the same place. The goal is that when you send a post request to the API (flask), the discord bot creates a text channel
but I don't know why when I upload my app to Railway, an infinite loop starts and the app doesn't work
code:
main.py
...
# <--- TRHEADS --->
def run_bot(): bot.run(os.environ.get("TOKEN"))
def run_api(): app.run(port=5000, debug=False)
# <--- RUN --->
flask_thread = threading.Thread(target=run_api)
bot_thread = threading.Thread(target=run_bot)
flask_thread.start()
bot_thread.start()
flask_thread.join()
bot_thread.join()
Procfile
web: gunicorn main:run_api
worker: python main.py run_bot
Nothing to do with code probs it works on pc but not on server
is the server slow?
thats the only reason i've had that issue before
I need to find a better host
Just show it, just to be sure
I need help, I want to create a slash command within a cog and I can't create it as self.tree:
def __init__(self, client):
self.client = client
self.guild = 1053710120493776926
self.tree = app_commands.CommandTree(client)
@self.tree.command()```
commands.Bot comes with its own command tree so you dont need to create another one
as for defining the slash commands, use @app_commands.command() and dpy will recognize it when you add the cog
Thanks
But how to add a guild?
for every command in the cog or just one?
for every command
apply @app_commands.guilds(1234, 5678) to the top of your class
hmm i thought there was an example of this in the docs
Thanks, I'm outdated I've used to create discord bots before there were slash commands
oh wait, that only applies to GroupCog
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#groupcog
well if you dont mind your commands being a single group you can go that route, otherwise you'll have to apply the decorator to each application command
The slash commands will appear without the guild in all of the bot servers?
if you specify guilds() then it can only be synced to whatever guilds you listed, not globally
Ok thanks
Why the slash command isn't displaying?
def __init__(self, client):
self.client = client
@app_commands.command(name="rolldice")
@app_commands.guilds(discord.Object(id=1053710120493776926))
@app_commands.describe(num="number")
async def dice_roll(self, interaction: discord.Interaction, num: int):
print(f"{interaction.user.mention} said {num}")
async def setup(client) -> None:
await client.add_cog(DiceRoll(client))```
It worked before using tree
how are you syncing your tree
which library is better for discord bots?
Whichever you find more easy to use
which one is more beginner friendly?
It depends really on what you're looking for, if you want something widely used and 'normal' in the Python ecosystem then discord.py/nextcord/disnake are good choices, depending on your preferred method of doing things (discord.py uses a command tree type thing for slash commands, nextcord and disnake opted for slash commands more similar to normal text commands with decorators), if you want something more explicit/with more precise control then hikari is a good choice
None of them are beginner friendly, all use async/await and are very object oriented
See pins of #async-and-concurrency
this might also help you, https://tutorial.vco.sh/tips/blocking/, it's also got some stuff about how to make bots
It's essentially a way for parts of your program to pause and unpause inorder to reduce waiting time during I/O operations to allow for a feeling of parallel execution
Does anyone know why my slash command isn't working?
My main file:
import asyncio
import discord
import os
from discord.ext import commands
from assets import TimeLoops
MY_GUILD = discord.Object(id=1053710120493776926)
class MyBot(commands.Bot):
async def on_ready(self):
TimeLoops(self).check_tables()
self.loop.create_task(TimeLoops(self).mute_loop())
self.loop.create_task(TimeLoops(self).mute_loop())
print("Ready!")
async def load(self):
for filename in os.listdir('/'):
if filename.endswith('.py'):
await self.load_extension(f'cogs.{filename[:-3]}')
async def setup_hook(self):
await self.tree.sync()
intents = discord.Intents.all()
client = MyBot(command_prefix="!", intents=intents)
async def main():
await client.load()
asyncio.run(main())
client.run(secret)
asyncio.run(client.setup_hook())
My command file:
def __init__(self, client):
self.client = client
@app_commands.command(name="rolldice")
@app_commands.guilds(discord.Object(id=1053710120493776926))
@app_commands.describe(num="number")
async def dice_roll(self, interaction: discord.Interaction, num: int):
print(f"{interaction.user.mention} said {num}")
async def setup(client) -> None:
await client.add_cog(DiceRoll(client))
There's so much wrong with this
@naive briar explain
You should have notice it immediately. In your load method, you're getting a list of files in your current directory, not in the cog folder that you're trying to load it from
as for now, they are in the same directory
Then load in from the current directory
Oops
I've changed it to await self.load_extension(f'{filename[:-3]}') but it's still not working
Any errors? It's not working doesn't make me understand your problem
No error. just not showing the slash commend
@naive briar Do you have any idea what the problem might be? I've enabled applications.commands
You enabled it, but did you invite your bot with it?
fixed
please don't crosspost
(his cogs weren't even loaded in properly in the first place)
lmao
@naive briar Do you have any idea what the problem might be now?
import asyncio
import discord
import os
from discord.ext import commands
from assets import TimeLoops
MY_GUILD = discord.Object(id=1053710120493776926)
class MyBot(commands.Bot):
async def setup_hook(self):
for filename in os.listdir('/'):
if filename.endswith('.py'):
await self.load_extension(f'{filename[:-3]}')
#TimeLoops(self).check_tables()
#self.loop.create_task(TimeLoops(self).mute_loop())
#self.loop.create_task(TimeLoops(self).mute_loop())
await self.tree.sync()
print("Ready!")
intents = discord.Intents.all()
client = MyBot(command_prefix="!", intents=intents)
client.run(secret)
command file:
class DiceRoll(commands.Cog):
def __init__(self, client):
self.client = client
@app_commands.command(name="rolldice")
@app_commands.guilds(discord.Object(id=1053710120493776926))
@app_commands.describe(num="number")
async def dice_roll(self, interaction: discord.Interaction, num: int):
print(f"{interaction.user.mention} said {num}")
async def setup(client) -> None:
await client.add_cog(DiceRoll(client))
You get the errors/logs/outcome, we're not interpreters - you tell us
I got no error. the slash command simply not appearing on my server.
can you verify that your cog is even loaded?
I checked it now, and the cog isn't loaded... that's odd do you have any idea why?
how did you uhm verify it?
Why are you doing a listdir over /
If you want the current folder it's ./ which is clearly different
myeah, just putting your cogs in cogs folder would make that less of an issue
And you should put your cogs in a cogs folder and load from ./cogs
(which is used in the docs too)
a question guys
is it possible to make buttons inside an embed?
i was thinking on maybe making an interface for the users
in my bot
like an UI, so peoples could use the bot easier
inside, no
below, yes
okay it seems that i will need to make tutorial of how to use my bot later
i can predict that it can still get overcomplicated
Bobux bot got such a good tutorial how to use
Site would be the best solution
i see
okay i will need to understand this, since i'm implementing the database into a file outside the bot, gonna be overwhelming, but i need to try my best
okay let me see if i understood the code
the setup hook is the part where it will pre-generate the tables
and the close method is to close the database
and the init is to conect or something to the database
the bot class is the class of the bot
but since i'm using a file outside the bot file... I have no idea how i will implement
what do i change at the class bot and init thing since i'm using a file different from the bot file?
guess i will need to change Bot to database, but... there is the command.Bot thing
i will need to change something here
but something is missing
idiot
i d i o t
i-d-i-o-t
i_d_i_o_t
i.d.i.o.t"
stupi
s-t-u-p-i
s_t_u_p_i
s.t.u.p.i
s t u p i
dum
d-u-m
d_u_m
d.u.m
d u m
nerd
n-e-r-d
n_e_r_d
n.e.r.d
n e r d
sucker
s-u-c-k-e-r
s_u_c_k_e_r
s.u.c.k.e.r
fat
f-a-t
f_a_t
f.a.t
f a t
loser
l o s e r
l.o.s.e.r
l-o-s-e-r
l_o_s_e_r```
why is it deleting: i didnt
@client.event
async def on_message(message):
await client.process_commands(message)
embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
if message.author.id == client.user.id:
return
if message.embeds:
pass
else:
with open('blocked words.txt') as f:
words = f.read()
blockedwords = words.split()
user_message = message.content.lower().split(" ")
if any(word for word in user_message if word in blockedwords):
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
print(f"Toxicity detected by {message.author.name}: {message.content}")
Because you're doing blockedwords = words.split()
So you're splitting on every whitespace
Considering you have s t u p i
i will be an element in blockedwords
Which will trigger i didn't because it contains i as well
oh
You likely want a words.split("\n")
You also shouldn't really open the file on every message but rather keep the content of the file, or the blockedwords directly, cached somewhere in a bot variable for example
@client.event
async def on_message(message):
await client.process_commands(message)
embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
if message.author.id == client.user.id:
return
if message.embeds:
pass
else:
with open('blocked words.txt') as f:
words = f.read()
blockedwords = words.split("/n")
user_message = message.content.lower().split(" ")
if any(word for word in user_message if word in blockedwords):
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
print(f"Toxicity detected by {message.author.name}: {message.content}")
``` like this
Looks better
message.content.lower().split("/n") ```
should i do that too~
Well here the issue is that you consider s t u p i a bad word
So that will never be found
And no you shouldn't split with new lines user messages
user messages should be split with spaces
ok
But if someone sends s t u p i it won't get caught since the user message will be split to s, t, u, p and i
And none are in your blacklist obviously
should i put it an spaces
You can't really do anything against that as a beginner
ok
I'd rather use some online service where you send the content and it checks for toxicity and you get the result whether it's toxic or not, or use some algorithm - although those have lots of false positives
idiot i d i o t i-d-i-o-t i_d_i_o_t i.d.i.o.t stupi s-t-u-p-i s_t_u_p_i s.t.u.p.i s t u p i dum d-u-m d_u_m d.u.m d u m nerd n-e-r-d n_e_r_d n.e.r.d n e r d sucker s-u-c-k-e-r s_u_c_k_e_r s.u.c.k.e.r fat f-a-t f_a_t f.a.t f a t loser l o s e r l.o.s.e.r l-o-s-e-r l_o_s_e_r
it is like this now
but still doestnt work
Because of the reason I stated
Use an online service to check against profanity, Perspective is free and performant
idk how to use api
They have a documentation, if you need help implementing it you can always use #1035199133436354600
There even is example code in Python :)
thought being a nerd is not a bad trait, it's a good trait
since it means that you have brains
people call other people that in a bad way
thats why
People call others "donkey" in a bad way as well
Just like lots and lots of other words
it's like "banana" from my country
That's why APIs like Perspective do what you need, they check context with machine learning etc.
originally it's to refer to a fruit
but here it's to refer as a bad way
like calling someone "um banana"
or saying "a preço de banana"
oh perfect
just my 2 cents as someone who does a lot of moderation stuff, I'd really discourage filtering automatically like this, while you can do this it'll result in a community that people don't want to engage in if there's a lot of filters that take commonly said things and always assume the context is bad
simple text filters cannot replace humans reading context and taking action, ML-based stuff is better but not perfect
ik i still have mods
blockedwords = ["idiot", "i d i o t", "i-d-i-o-t", "i_d_i_o_t", "i.d.i.o.t", "stupi", "s-t-u-p-i", "s_t_u_p_i", "s.t.u.p.i", "s t u p i", "dum", "d-u-m", "d_u_m", "d.u.m", "d u m", "nerd", "n-e-r-d", "n_e_r_d", "n.e.r.d", "n e r d", "sucker", "s-u-c-k-e-r", "s_u_c_k_e_r", "s.u.c.k.e.r", "fat", "f-a-t","f_a_t", "f.a.t", "f a t", "loser", "l o s e r", "l.o.s.e.r", "l-o-s-e-r",
"l_o_s_e_r"]
if any (word in message.content.lower() for word in blockedwords):
await message.delete()
await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
print(f"Toxicity detected by {message.author.name}: {message.content}")
``` it doesnt work i tried to change it
there will always be people creative enough to bypass this type of filter, discord has a built-in feature for censoring swear words, I'd suggest using that one instead?
thought people also use the P word as a way to offend the other
but i guess it's way too heavy
we've got something like ~15 words actually blocked and they're all ones that pretty much cannot be used in a non-malicious context, and moderation is still easy enough, you can honestly just stick a few slurs in native automod and be fine tbh
(you may be able to tell I'm not a fan of naive text filters
)
i got it working again
n|e|r|d 
or just placing a single joiner character, ner.d
yeah
honestly just enable that and do manual moderation
the feature you're working on is kind of pointless
Actually even funnier, just writing a sentence 
You're such a nerd.
that would get flagged
since its now doing striung in string rather than string in list
ah yeah changed the check in-between
or just in some weird font 
Hey what IDE/IDLE do I use to make a discord bot
Any IDE that supports python
Which one would you call the best in terms of features?
the most popular ones are visual studio code (vscode) and pycharm, both are pretty much as good as eachother, though for some features in pycharm you need a paid license/to be a student
Oh okay thank you
np
or apply for open source license*
yeah that too
Though the base functionalities are free and should be enough for beginners
Or even advanced people
i just stick with vsc because I don't want to bother with the hassle of getting pycharm stuff running and I have a good config already
Yeah makes sense
but either will do you just as well really
pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program.
How do I fix this
I'm trying to install discord in the terminal
I did
pip install discord
on windows you likely have the py python launcher, so install with py -m pip install discord.py instead (discord is a mirror of discord.py)
what does -m stand for
or you can create and activate a virtual environment which should provide its own pip
its how you run a module/package directly, rather than some .py script
yes, module/package/library are used essentially interchangably in discussion about python
oh ok ty
thanks
Hey I'm reading a documentation on the discord module, and I don't know what intents means, can someone help?
client = discord.Client(intents=intents)
!intents
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.
What's the gateway
Is there any way to make a bot output 9 images in a 3x3 grid?
I think my level is at PCEP
format the image urself?
the position of the image on the 3x3 is not constant, I should probably use Pillow or something, theres no way to do it using embeds or normal file upload?
:incoming_envelope: :ok_hand: applied timeout to @ocean mango until <t:1685043966:f> (10 minutes) (reason: attachments spam - sent 9 attachments).
The <@&831776746206265384> have been alerted for review.
if u just want to send multiple imagen in one embed u could
dont think its gonna show up as 3x3 matrix on discord

!unmute 627192394399350795
:incoming_envelope: :ok_hand: pardoned infraction timeout for @ocean mango.
ty
oops, you sent the same image 9 times and it triggered the bot filter :P
was trying to demonstrate what I meant
ahhh, i see
I mean I know sending two identical embed with the same url but different images will send one embed with both images so maybe you could try nine?
Sounds a bit iffy tho
i am 70% sure it will show up with
| a | b |
| a | c |
I do not know what that means, I just need at least 3 images to be adjacent to each other
So you know how when you create an embed you can give the title a irl
yes
If it’s the same for multiple embed with images then it will stick all the embeds into one and have multiple images
am I suppose to replace a b c d with image url?
how do you merge embeds like that?
Yeah I haven’t seen anything more than that but could just be because nobody has tried
just make sure embed url is same
yes this could work
Might not work with nine
wb 3x1
then i just ouput that 3 times separately
If it’s three it won’t be in a row discord will make one larger and the other two smaller
To fit them in a square
I see
Just curious why do u need 3x3 images?
building a game
Can you explain the idea
So its a card game which relies on the concept of adjacent placement
yes
For a smooth image
Sorry for disturbing, but do you have documentation on how I can composite one image over another using PIL
ty
Do that but 9 times
how do i set up a list of what my bot will accept as a response for a command, example: rock paper scissors bot only accepts the answer rock paper or scissors for a command, if anything else is said it ignores it and waits for one of the options stated?
if-else
?
lets say i wanted a bot to only respond to the options rock, paper, scissors, lizard, spock
how would i do that using if else
idrk how discord bots work im really new to all of it
a command or a normal message?
uhh
can i dm you what it looks like so far?
or is it ok to post big messages here
!pastr
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.
@bot.slash_command(
name="rpsls",
description="Play rock, paper, scissors, lizard, spock against a computer"
)
async def rps(interaction: nextcord.Interaction):
channel = interaction.channel
embed = nextcord.Embed(title="Rock Paper Scissors Lizard Spock", description="Choose rock, paper, scissors, lizard, or spock.", color=0x7c00ff)
prompt_message = await interaction.send(embed=embed)
timedoutembed = nextcord.Embed(title="Timed Out", description=f" <@{interaction.user.id}> The game has been canceled as you did not respond in time.", color=0xff0064)
def check(m):
return m.content in options and m.channel == channel and interaction.user.id == m.author.id
try:
msg = await bot.wait_for('message', check=check, timeout=30.0)
except nextcord.NotFound:
await interaction.followup.send(embed=timedoutembed)
return
except asyncio.TimeoutError:
await interaction.followup.send(embed=timedoutembed)
return
computer = random.choice(options)
if msg.content == computer:
result_message = f"I chose {computer}. It's a tie."
result_color = 0xffae42 # Yellow Orange
elif msg.content == "rock" and computer == "scissors":
result_message = f"I chose {computer}. You won."
result_color = 0x00ff00 # Green
elif msg.content == "paper" and computer == "rock":
result_message = f"I chose {computer}. You won."
result_color = 0x00ff00 # Green
elif msg.content == "scissors" and computer == "paper":
result_message = f"I chose {computer}. You won."
result_color = 0x00ff00 # Green
elif msg.content == "lizard" and computer == "spock":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
elif msg.content == "lizard" and computer == "paper":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
elif msg.content == "spock" and computer == "rock":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
elif msg.content == "spock" and computer == "scissors":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
elif msg.content == "paper" and computer == "spock":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
elif msg.content == "rock" and computer == "lizard":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
elif msg.content == "scissors" and computer == "lizard":
result_message = f"I chose {computer}. You won"
result_color = 0x00ff00 # Green
else:
result_message = f"I chose {computer}. You lose!"
result_color = 0xff0000 # Red
result_embed = nextcord.Embed(title="Rock Paper Scissors Lizard Spock", description=result_message, color=result_color)
await interaction.send(embed=result_embed)
im trying to make it only respond to rock paper scissors lizard and spock
oh
my normal rps command uses the options method but idk how to make another one and not have them interfere
this one still has it there rn because i just copied the code to add lizard and spock im not finished yet
i dont know
It tried to execute the code below but if an exception is raised, it goes the to the except code which handles the error
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.
try:
number = int(user_input)
item = some_list[number]
except:
print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")
For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.
Np
I'm still watching the video, he hasn't done the except part yet
What year was the tutorial u are watching made
Or how many years ago
It looks a bit outdated
Also you kind of peaked your bot token
You should reset it ASAP from the dev portal @slate swan
Oh ok
I'm away from my computer at the moment so I'm just trying to understand what's going on
It was made 7 months ago
Wait what
!await
That’s for asynchronous stuff
Idk what that stuff is
So it can run at the same time as other stuff
All I know is asynchronous means not happening at the same time
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
So it synchronises unsychronised stuff?
Not really
Basically it’s so that more than one person can use the bot at a time
But what are you trying to make specifically?
Video looks a bit odd for a basic bot
It says easiest discord chatbot
I just want to work my way up because I just finished the basics of python, and all this stuff in Discord being introduced me such as API, async, await, threads, coroutines, had never been taught to me.
Maybe start off with a basic bot then, this one looks like it is teaching bad practices such as handling commands with on_message
Which library are u using
discord
Yeah
Ok
I would teach you myself but I’m on phone rn so unless ur willing to wait like 3 hours then search on yt for a basic discord.py tutorial made in 2022 at the latest
I can't stay up for 3 hours more. It's already late 😔
I wouldn't use YT for discord.py personally, there are plenty of examples in their docs and on GitHub. A lot of the YT videos out there can be misleading
Yeah
discord.gg/dpy if u need more help
@client.slash_command(name="registar", description="Regista o teu perfil na plataforma")
async def registar(ctx: discord.ApplicationContext):
try:
cursor.execute("SELECT userId FROM users WHERE userId = %s", [(ctx.author.id)])
row = cursor.fetchone()
if row is None:
if ctx.author.nick is None:
await ctx.respond("`` ❌ `` Não tens um apelido válido.")
else:
callsign = str(ctx.author.nick[0:3])
nome = str(ctx.author.nick[6:100])
for role in ctx.author.roles:
if str(role.id) in roles:
patente = str(role.id)
else:
continue
cursor.execute("SELECT id FROM patentes WHERE role = %s", [(patente)])
row = cursor.fetchone()
if row is None:
await ctx.respond("`` ❌ `` Não tens uma patente válida 1.")
else:
cursor.execute("INSERT INTO users (nome, patente, callsign, userId) VALUES (%s, %s, %s, %s)", [(nome), (row[0]), (callsign), (ctx.author.id)])
await ctx.respond("`` ✅ `` Perfil registado com sucesso.")
The code above is supposed to check if the user has a role that is listed in a list and if it has keeps the role id in a var, only that.
can someone help?
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
print(f"guild length is {len(self.bot.guilds)}")
for guild in self.bot.guilds:
print(f"found guild: {guild.name}")
for channel in guild.text_channels:
print(f"{channel.name}: {channel.id}")
#your starboard channel object (so you can send messages to that channel)
starboard_channel = self.bot.get_channel(1111417168307961896)
#an if statement which checks if the reaction was a ⭐
if str(reaction.emoji) == "⭐":
#a variable which stores the content of the message a star was given to
message_content = reaction.message.content
if message_content:
# sends a message to the starboard channel with what the message said (won't do embeds for now, that's another story)
await starboard_channel.send(message_content)
elif reaction.message.embeds:
await starboard_channel.send(embed=reaction.message.embeds[0])
else:
await starboard_channel.send(f"Someone starred something, here's the link: {reaction.message.jump_url}")``` How do I make an embed for the image, or text that was starred?
Hello can anyone help with py-cord
embed = discord.Embed(title='NEW MESSAGE ADDED TO STARBOARD', url=reaction.message.jump_url, colour=discord.Colour.yellow())```
In the context of a file object, the seek function changes the stream position to a given byte offset, with an optional argument of where to offset from. While you can find the official documentation here, it can be unclear how to actually use this feature, so keep reading to see examples on how to use it.
File named example:
foobar
spam eggs
Open file for reading in byte mode:
f = open('example', 'rb')
Note that stream positions start from 0 in much the same way that the index for a list does. If we do f.seek(3, 0), our stream position will move 3 bytes forward relative to the beginning of the stream. Now if we then did f.read(1) to read a single byte from where we are in the stream, it would return the string 'b' from the 'b' in 'foobar'. Notice that the 'b' is the 4th character. Also note that after we did f.read(1), we moved the stream position again 1 byte forward relative to the current position in the stream. So the stream position is now currently at position 4.
Now lets do f.seek(4, 1). This will move our stream position 4 bytes forward relative to our current position in the stream. Now if we did f.read(1), it would return the string 'p' from the 'p' in 'spam' on the next line. Note this time that the character at position 6 is the newline character '\n'.
Finally, lets do f.seek(-4, 2), moving our stream position backwards 4 bytes relative to the end of the stream. Now if we did f.read() to read everything after our position in the file, it would return the string 'eggs' and also move our stream position to the end of the file.
Note
• For the second argument in seek(), use os.SEEK_SET, os.SEEK_CUR, and os.SEEK_END in place of 0, 1, and 2 respectively.
• os.SEEK_CUR is only usable when the file is in byte mode.
Hello can anyone help with py-cord
Sorry I’m only familiar with discord.py
okay, i think i'm close to what i desire:
but i don't know how to import client from my bot file
what lib is that?
I already fixed ..?
my bad u didnt say
You should take a look at the example how it's done, right now it makes little sense and the modules naming convention is incorrect https://github.com/Exenifix/disnake-bot-template-postgres
Specifically take a look at utils.database.Database, how it's connected to utils.bot.Bot and how it's used in cogs
Why does my code not work
Uh dude we don't have technologies that make us able to read the whole problem from mind of a discord user remotely, could you please share your code, explain what doesn't work and provide errors traceback if applicable?
😒
Ok
🐈
!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").
!d
we do
🧐
So?
Is there youtube tutorial for a button which opens a hidden channel
There's no youtube tutorial for everything but there's documentation and examples
class HiddenChannelView(discord.ui.View):
@discord.ui.button(label="Unlock")
async def unlock(self, interaction: discord.Interaction, button: discord.ui.Button):
channel = interaction.guild.get_channel(...)
await channel.set_permissions(interaction.user, read_messages=True)
await interaction.response.send_message("Yes")
await send("Press button for secret channel access!", view=HiddenChannelView())```
Very basic example
It's for ticket systrm
There are plenty of ticket bots on github ig
link pls
edit : Sorry for ping! I had a question regarding this thats why i had pinged you, but i figured it out now ^^
🗿
install it
did
pip install discord
An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'in-tree-build')
hm okok lets try
Traceback (most recent call last):
File "main.py", line 18, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
@still plover

man u there @still plover
No need to spam ping people, we're not your personal assistants
python -m pip uninstall discord
python -m pip install discord.py
python main.py
An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'in-tree-build')
Re-install pip
in replit how to
woah nice skull
Better to ask them out, not sure how they handle pip and python packages
ahh idk anymore leave it
You can try to add a requirements.txt file and write discord.py in it
Maybe replit auto-installs
hmmmm
Replit uses poetry
yes theres file named poetry
So, just poetry add discord.py or literally just use their packages tab
[[package]]
category = "main"
description = "A mirror package for discord.py. Please install that instead."
name = "discord.py"
optional = false
python-versions = "*"
version = "1.0.1"
says this (but i did that discord.py from discord)
then this
Replit: Updating package configuration
--> poetry remove discord
exec: "poetry": executable file not found in $PATH
Replit: Package operation failed.
if i try to remove the existing discord
Just accept that replit took the L and switch to VSC or pycharm
Or notepad if you are real pro
how do I run my discord bot
python3 zephyrith.py
Doesn't work
Error code:
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
py
what 
doesn't work
i closed all the stuff out of frustration

btw tell me how
thats some public code btw
thanks
client = commands.Bot(command_prefix = '!')
@client.event
async def on_ready():
print("Zephyrith is active.")
print("--------------------")
@client.command()
async def hello(ctx):
await ctx.send("Hello")
client.run(TOKEN)
Error Code:
client = commands.Bot(command_prefix = '!')
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
What are intents
stonk
!intents
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.
The shared IP part is probably the most important point
As well as underpowered machines but yeah, if you make some private bot it's not that relevant eventually
so i copy everything that person uploaded on replit and past it on my computer and run it?
I'm watching a tutorial
i mean its just a variable
I know it doesn't make sense, but it's trial and error 😦
i have told it multiple times here already
discord.py tutorials are usually outdated and the ones on youtube are infamous for their bad quality
i know pep and all that but still variable is a variable
can confirm
that does not mean you should call apples oranges
I don't understand what Intents.default means T_T
I only know the basics of python such as for loops, while loops, 2D arrays, arrays, and functions
What do I learn
what's OOP
it depends on the programmer with what they want to call it
I get its a good practice to name it correctly for future and code sharing purposes but while you are starting just to be comfortable you should name it as you want so that you can understand what you are doing and later on update it
well anyways its out of scope for this channel
Oh, do you have any recommendations
so you're saying naming a variable client instead of bot is going to help them understand what they are doing?
Ppl just follow bad tutorials or chatgpt to name commands.Bot client most of the time
i was here to ask about how to go about with using cooldowns in databases
After I finish OOP what do I do
I would recommend understanding the async/await pattern, that will be quite useful
async and await is a built in function in Python?
they are keywords, not functions
oh what do the keywords do
yea i know the difference but again most are gonna follow an outdated tutorial so it really wont matter at this point sadly
anyways bump since it was missed
so i actually wanted 2 commands one slash and one prefix both in different files to have the same cooldown because it replies to one database but i asked elsewhere and i found no solution so i thought to moving the cooldown from the default system to a database
command and no hybrid because i am not using discord.py i am using disnake
i dont want to learn tree commands
Guys, coroutines are functions that can be stopped and resumed when executed right?
yes this will not work for 2 different commands in 2 different files.
more specfically 2 different types of commands
look the prefix and the slash command does the same thing
thats why i want to make a database for cooldown
I mean how would a database have cool down built in
thats the reason i am asking
what's the reason for a database? Do you just want persistent cooldowns?
here is the reason
disnake has dynamic cooldowns: https://docs.disnake.dev/en/stable/ext/commands/api.html#disnake.ext.commands.dynamic_cooldown
you can have some data structure that stores the user id, command name and duration that the cooldown expires
again not for 2 different type of commands
read again. It accepts a callable that returns the cooldown.
and I believe disnake has no seperate module for app commands like dpy has
let me repeat it once more
i have a prefix command and a slash command that do the same thing and same cooldown but if one is used the other can be too and i like to keep my code clean so these are in 2 different files
i tried multiple methods of linking the cooldown ( inbuilt to the library ) and it didnt work and figured it will be easier to just move the cooldown to a database because i already have one
and i want to know how should i be doing it " the right way "
I understand. I don't understand why you need a database for this when you can just use something simple like a dictionary
cooldowns = {(user_id, command_name): datetime_when_cd_expires}
a simple mapping like that, then you can have a check on your commands that make a simple dict lookup
this is not #bot-commands
since the command name of the prefix and slash command is presumably the same, you'll have the same cooldown on both of them
okay i shall try that thank you
i understand what you mean now
i was trying with the message and not command name
I just hope disnake supports checks on slash commands
it does
Hey what is instance considered to be in programming
!class
Classes are used to create objects that have specific behavior.
Every object in python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.
Here is an example class:
class Foo:
def __init__(self, somedata):
self.my_attrib = somedata
def show(self):
print(self.my_attrib)
To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.
bar = Foo('data')
bar.show()
We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.
in the second example, bar is an instance of Foo
the same way 10 is an instance of int, or "hello world" is an instance of str
bar is an instance of Foo?
Oh I don't know what Foo is
it's the class, read this please
there is no foo
Foo
I've never seen someone in my life write a function like this init
it takes some data, assigns it as an attribute and has a method that prints that attribute
please watch the Corey Schafer OOP playlist, it explains very clearly how classes and objects work
okay
as well as dunder methods and other OO concepts like inheritance
I thought I was missing out or something
cause he said Instantiating
I've never learnt that thing
I had to search it up
Thanks for the help though
Hey @vocal snow
In python when I'm using an instance and then a dot after it then another word. Does that mean I'm creating new fields in a database
or is the whole thing just a variable
Does that mean I'm creating new fields in a database
No, there are no databases involved
think of it as a variable which is attached to the instance
you could think of it as a table, but the data isn't actually persistent
consider a table Employee: ```sql
CREATE TABLE Employee (
id INTEGER PRIMARY KEY,
name TEXT
);
in the table, each row (called a record) is like an instance
why doesnt my bot give roles or remove them on update, nor posting embeds into specified channel
do you have member intents enabled?
So the arguments within the init function make up an instance
the arguments in the _init_ must be passed to create a new instance, yes
Not if you don't make it do so
!e
class AClass:
def __init__(self, arg):
pass
a = AClass(123)
print(a.arg)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 6, in <module>
003 | print(a.arg)
004 | ^^^^^
005 | AttributeError: 'AClass' object has no attribute 'arg'
@client.event
async def on_member_update(before, after):
if isinstance(after.activity, discord.CustomActivity) and after.activity.name == "discord link":
role = discord.utils.get(after.guild.roles, name="Your Role Name")
await after.add_roles(role)
channel = bot.get_channel(channel_id)
embed = discord.Embed(title="Custom Activity Update", description=f"User {after.name} now has the custom activity 'discord link'.", color=discord.Color.green())
await channel.send(embed=embed)
elif isinstance(before.activity, discord.CustomActivity) and before.activity.name == "discord link":
role = discord.utils.get(after.guild.roles, name="Your Role Name")
await after.remove_roles(role)
channel = bot.get_channel(CHANNEL_ID)
embed = discord.Embed(title="Custom Activity Update", description=f"User {after.name} no longer has the custom activity 'discord link'.", color=discord.Color.red())
await channel.send(embed=embed)
doenst give role
nor posting embeds
Yup
I don't understand, why is there first argument/instance considered to be a variable
maybe add an else: and make sure the statements are executing as desired
else instead of elif?
no, a separate else to handle the case where the if and elif dont execute
So you can access the instance within its methods
oh right
the function was called after the variable, how does the function know that emp_1 is self
is it just a thing we do
emp_1 is just a name given to the instance afterwards
Employee('Corey', 'Schafer', 50000) is itself the instance
When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.
class Foo:
def bar(self):
print('bar')
def spam(self, eggs):
print(eggs)
foo = Foo()
If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.
Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').
Why is this useful?
Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.
Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.
Self is passed by python lets say
also should note that Employee('Corey', 'Schafer', 50000) doesn't call the __init__ first, it calls __new__ which creates the object, calls the _init_ and returns the object
although for now you can just think of it as python passing self implicitly
So to summarize it self is an instance used to call methods in a class
because methods in a class can't be called directly without an instance which builds a link to call the method
am I right?
self is instance object in class
You can call a method without an instance if it's a staticmethod
I meant we use a variable to send an argument
I'm now confused again
What
isn't emp_1 a variable that's sent as an argument to self
not really
I really don't understand then
So, what's being sent to self
What's so confusing
The instance 🤷
There are 4 arguments here, the guy calls the function but there are 3 arguments
what part is the instance
self
how does the computer know that self isn't Corey or Test
Cause its 1st argument always
I don't really understand
he inputted 3 arguments but the function has 4 arguments in the parameters
Sigh
Does it magically know
1st argument is always instance
or is there hidden code which does that
Cause self is passed automatically as first argument always in methods
Python does it in the background
and for it do that the name of the function in the class must be innit?
or does this apply to every class function
Every method in class gets self as first parameter
To every method, except staticmethods
in
emp_1 = Employee('Corey', 'Schafer', 50000)
Would self become emp_1
not the variable
but inherit the name emp_1
self just represents some instance of the Employee class, so if you were to call a method on your emp_1 instance, then self would just be emp_1
thank you
I have a question, once we call the employee class in the emp_1 variable, does it become an instance of employee?
Employee('Corey', 'Schafer', 50000) is what's actually creating an instance of the Employee class. emp_1 = ... is just assigning that instance to the emp_1 variable, so that it can be referenced later on in your code.
thank you
so are classes just used to store functions?
Classes are primarily used to create your own type of objects, with their own set of attributes, and their own set of methods.
Yes, they can also be used to "organise" functions in a way.
You can decorate a function within a class using the @classmethod decorator and you'd then call that method on the class itself, rather than having to create an instance of the class and call the method on the instance. But be mindful that classmethods use the cls parameter in place of self.
attributes mean data right?
oh nice
self.name = "John" would be an example of an instance attribute. self.name is the attribute itself, while "John" is the value of that attribute
the .name part is the attribute right?
Yeah you're right
thanks
so can i say attributes are like properties?
Properties are something slightly different, so call them attributes
ok
Yo @slate swan @vocal snow
Check out what I did with Class and Instance variables
It's great to see people getting into new stuff and making it work, but maybe you missed the purpose of the #discord-bots channel
Yeah mb
Just a tip, try to name your classes with PascalCase (it's just convention)
https://paste.pythondiscord.com/qilahikipe
Bot is not responding to elif statement
does anyone else have an issue with activities not being returned when querying the API?
using discord.py and user.activity or user.activities (user is discord.Member) always returns ()
(intents are set to all() and intent.presence returns True when queried)
Probably better not to cross-post in multiple servers but focus your question in one first
Can anyone see mine help post
yepa 
I don't even know what I did that my bot logging used to provide full tracebacks but now traceback.format_exc() just gives NoneType: None 
normalmsg = ['hello']
res = f"Hello {message.author.mention}", f"Hi {message.author.mention}"
if any (word in message.content.lower() for word in normalmsg):
await message.channel.send(random.choices(res))
if message.content.lower().startswith("hi"):
await message.channel.send(random.choice(res))
``` my bot is sending ['Hi @formal basin']
instead of Hi @formal basin
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
you changed your webhook token
What man i didn't change nothing
but in the error it says invalid webhook token
Why did it not happen for the first 15 iterations then
so you need to put the webhook token
because something happened to the webhook token
so you need to put a new token into it
Man im not even using webhook
show your code
class No_prot_pot(discord.ui.View):
#some unrelated code here
async def on_timeout(self):
for item in self.children:
item.disabled=True
await self.message.edit(view=self)
oh idk that
how long did you set your timeout?
and where do you assign message to?
cause i think that error message means your interaction has expired
30 seconds
In another func
Hm why did it work for the first 15 iterations then
your interaction token hadnt yet expired
yeah i checked discord developers, 401 invalid webhook token is what you get when using an interaction past its 15 minute lifespan
can anybody tell me how to implement RedPajama-INCITE-Chat-3B-v1 into the chatbot? it is basically a open source database
i am trying so hard but unable to do that
Is there any way to fix it
how is self.message defined?
is there a way to get thsi to send as an embed? or do interactions have to be normal messages
class ApplyModal(discord.ui.Modal, title="Builder"):
t = discord.ui.TextInput(label="Embed Title", placeholder=" ", style=discord.TextStyle.short)
v = discord.ui.TextInput(label="Embed Description", placeholder=" ", style=discord.TextStyle.long)
n = discord.ui.TextInput(label="Image URL", placeholder=" ", style=discord.TextStyle.short)
f = discord.ui.TextInput(label="Footer", placeholder=" ", style=discord.TextStyle.short)
async def on_submit(self, interaction: Interaction):
await interaction.response.send_message(f"Success!", ephemeral=True)
channel = discord.utils.get(interaction.guild.channels, name="embed-test")
embed = discord.Embed(name=f"{self.t}", color=discord.Color.random())
embed.add_field(value=f"{self.v}")
embed.set_image(url=f"{self.n}")
embed.set_footer(text=f"{self.f}")
await channel.send(embed=embed)
@client.tree.command(name="embed", description="Build an embed")
async def embed(interaction: discord.Interaction):
await interaction.response.send_modal(ApplyModal())
else:
selector_list=No_prot_pot(ctx,player_list)
embed102=discord.Embed(title=f'__**Round {client.round_info[ctx.guild.id]}**__',
description=f''
colour=discord.Colour.random())
#embed.set_image(url="g")
#ctx=await ctx.original_response()
selector_list.message=await ctx.followup.send(embed=embed102, view=selector_list)
send_message has an embed kwarg
I guess you can't edit the followup webhook message after 15 minutes as described in that screenshot sent above
maybe just send a message to the channel directly
via interaction.channel.send
doubt so since it seems like discord invalidates the followup webhook itself after 15 minutes
Theres no limit for this one right?
how exactly would that be done inside interactions?
await interaction.response.send_message(embed=embed, ephemeral=True)
ok ok
i keep getting this error
TypeError: bad operand type for unary +: 'str'
im trying to get a random number, and have the bot say it
code please
oh
"Higher or lower? Your number is: ", + str((random_number))
you have a comma after the string literal
and would recommend using an fstring
!fstring
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
it was the comma
tysm
how can i get the up arrow and down arrow reactions on the message below it
^ code
channel.send will return the Message object, call add_reaction on that
How would I go about checking which invite code a member joined with in the on_member_join event?
although I really dislike how your code is structured, it only allows for one game session at a time
and if someone reacts with 👍 before the attribute is set then it's going to crash
you should just wait for a reaction_add event in the command
how could i code it better
You should use buttons
i could try that
!pypi reactionmenu
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.
this one is good^^
i arldydid with reaction
it is working good but I want to change with slash command
so the code is no longer the same
button are more appropriate but more difficult too
Has anyone here fully set up Discord.py 2.0 and wavelink along with working slash commands and preferably also that menu pagination and would be willing to spend an hour tops setting up a base project doing all of the above? I'd be willing to pay 50$ for a confident and capable hand in it. I am a full stack software engineer and have an existing large-scale project using disnake[discord] and wavelink but the disnake[discord] wrapper is no longer supported and refactoring has been a big roadblock so just a guiding hand in terms of the syntax and all of that to run through it quickly would be very helpful. I have looked at the documentation and understand it but I want someone knowledgeable who has built a project at scale to show me if there are any shortcuts or optimizations I would be missing and things of that nature that might make the process of making the transition easier and less stressful since it is already going to be a large refactor. Let me know and I will be happy to pay upon completion of the above described effort!
!pypi discord-ext-pager is one ive written that somewhat resembles danny's discord-ext-menus, but you can also learn from their source code since they're not extraordinarily complicated to write
A view-based paginator library for discord.py 2.0
does anyone know how to send a color with embed in webhooks? i have this so far
if embed:
data["embeds"] = [
{
"description": description,
"title": title,
}
]```
color=discord.Color.colname()
????????
i literally just said through webhooks
"color": 10201343 (or whatever integer from 0 to 16777215) sets the embed colour if I remember correct
discord.Color.color_you_want() is just a hex code
It's the same thing as putting the number for the same color there
Oh, you're confused about the key name
They're probably talking about sending a webhook message without a client library
i keep getting this error
NameError: name 'message' is not defined
Can you show us your code?
And which line is the error happening in?
@sick birch wrong link
No worries feel free to send the corrected link
Did you mean to have that if statement in your on_message function?
lemme try that
on_ready isn't good for much more than simply printing out that you're logged in (like you already have done)
now i got IndentationError: unindent does not match any outer indentation level
!indents
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
Python works off indentation - make sure it's consistent
E.g everything you want to be part of an if statement should be indented one step further:
if some_condition:
something # indented to be inside if statement
something_else # indented to be inside if statement
not_indented # not indented, it's not part of the if statement
new error
SyntaxError: 'await' outside function
You may have indented it too far now
The if should be indented one time so it's inside on_message
If you indent it 0 times, then it's outside the on_message
E.g
async def on_message():
if some_condition:
do something
do more stuff
i have this
sent_message = await message.channel.send('stuff')```
and im still getting it
Can you paste the whole function?
async def on_message(message):
if message.author == client.user:
return
if '$hilo' in message.content.lower():
random_number = str(random.randint(1, 100))
if message.content.startswith('$hilo'):
sent_message = await message.channel.send('Welcome to HiLo! Would you like to start a game?')
await sent_message.add_reaction('👍')
await sent_message.add_reaction('👎')
client.game_message_id = sent_message.id
Yeah notice how everything starting with if '$hilo' in message.content.lower() isn't indented?
That means it's not part of the on_message function
ohhhh
If you're on VSCode you can pretty much highlight the entire section that's not indented, press tab and VSCode will indent all of it for you
im on replit
I don't use replit but it shouldn't be too difficult to do it by hand either
im just confused on where to indent and where not to
@client.event
async def on_message(message):
if message.author == client.user:
return
if '$hilo' in message.content.lower():
random_number = str(random.randint(1, 100))
if message.content.startswith('$hilo'):
sent_message = await message.channel.send('Welcome to HiLo! Would you like to start a game?')
await sent_message.add_reaction('👍')
await sent_message.add_reaction('👎')
client.game_message_id = sent_message.id
there you go
How hard can it be
Please don't just spoonfeed people
I'm trying to guide them to getting it right on their own
wait, i think i got it
async def on_message(message):
if message.author == client.user:
return
if '$hilo' in message.content.lower():
random_number = str(random.randint(1, 100))
if message.content.startswith('$hilo'):
sent_message = await message.channel.send('Welcome to HiLo! Would you like to start a game?')
await sent_message.add_reaction('👍')
await sent_message.add_reaction('👎')
client.game_message_id = sent_message.id```
this is working
Doubt it
yeah, turns out when i ran '$hilo' an error came up
What error?
!e 🐈
if False:
cat = 0
print(cat)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 4, in <module>
003 | print(cat)
004 | ^^^
005 | NameError: name 'cat' is not defined
