#discord-bots
1 messages · Page 246 of 1
No doubt about it
What is sent_message if the message content doesn't start with '$hilo'?
this worked, mine didnt
replit and vscode use the same engine
with
im getting
NameError: name 'random_number' is not defined
when 'random_number' is defined
https://paste.pythondiscord.com/rofiyologi
it is in a function you cannot access it directly
oh
how should i do this then
what are you trying to do
you don't want to change it every 0.5 seconds first of all
you probably want to change it after the game is over, and also add a check for concurrency
i need a new number every 0.5-1 second, because then i would need to rerun the code everytime, for a new number
no you don't
just pick the number when you run the command
im trying to make something like this
i'm typing
@commands.max_concurrency(1, per=commands.BucketType.user)
@bot.command(
name="higherlower",
description="Starts a new higher or lower game."
)
async def higher_lower(ctx: commands.Context) -> None:
random_number = random.randint(1, 100)
next_number = random.randint(1, 100)
predictions = 0
def check(reaction: discord.Reaction, user: discord.User) -> bool:
return (
user == ctx.author
and reaction.message.channel == ctx.channel
and str(reaction.emoji) in ("⬆️", "⬇️")
)
while True:
message = await ctx.send(f"The number is {number}. Will the next number be higher or lower?")
await message.add_reaction("⬆️")
await message.add_reaction("⬇️")
try:
reaction, user = await bot.wait_for("reaction_add", check=check)
if (
(str(reaction.emoji) == "⬆️" and next_number > number)
or (str(reaction.emoji) == "⬇️" and next_number < number)
):
predictions += 1
await reaction.message.add_reaction("✅")
else:
await reaction.message.add_reaction("❌")
break
except asyncio.TimeoutError:
await ctx.send("You took too long! The game is over.")
return
await ctx.send(f"You lost! You were at {predictions} predictions.")
holy
this may not be correct but the general concept is to use a while loop inside the command
okay
max_concurrency basically ensures the user can only run one game at a time
wait_for waits for any event with a default time out of 180 seconds
https://paste.pythondiscord.com/kozosacasu
Issue: the bot does not responses to the elif not isinstance statement:( and I am not getting the errors either. Maybe the bot is still passing the number to the function even though its no longer an int
it is not even sending str(result)?
What's the problem
That's how it should be
You type hinted that the number parameter should be an int
yes
but if the number is like 54a, it is no longer an int tho
Then the bot will raise an error
it does not
Do you have an error handler
No, an error handler
nope
Show the code
which?
mate why are you asking for help for the same thing in two servers at once
and not using the help that you're being given at all on either
They already got an answer, dont bother
the post was confusing
and my issue is fixed already
anyone know a command for running a function that does something every 5 seconds in the background once called and ends after a certain time ?
lol what
Wdym lol what
Yes, but what are you doing every 5 seconds?
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
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").
sir, do u know how to send ephemeral to a person that is not the original interaction user for buttons?
Don't expect help saying oi 💀
i am sorry, master
forgive ur fellow student
Holy fuck 💀
Can't do that
then how do some bots do it
they say "This menu is not yours" in ephemeral
its for updating data in database
i tried the loop but how to make it stop automatically after a certain time?
count (Optional[int]) – The number of loops to do, None if it should be an infinite loop.
input a count easy
Because that is the interaction's user? You pressed the button bruh
but it does not send msg for me:(
@stray tangleks.loop(second=5,count=120) it will run it for 2 mins every 5 seconds?
... What did you try?
followup
What?
damn u making me look like a dumb
No it'll run for 10 minutes, every 5 seconds 120 times
No I'm making you look like someone who can't explain something to save their life
async def interaction_check(self, interaction: discord.Interaction):
if interaction.user.id != self.author.id:
try:
await interaction.folowup.send('This command is not for you!')
except discord.errors.NotFound:
pass
return False
return True```
ah thats how it works thanks
Why are you using a followup
there's nothing to follow up to
the interaction is already responded to...
No it's not
Can anybody repair me this line of code?:
await interaction.guild.get_channel(channel_name).send_message(view=ChannelButtonView())
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**.
can anyone help me understand 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.
invites = {}
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name="DM me to report a player!"))
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)!")
except Exception as e:
print(f"Sync Failed! {e}")
def has_perm(interaction : discord.Interaction):
if interaction.user.id == 533692379777990656 or interaction.user.guild_permissions.administrator:
return True
else:
return False
for guild in bot.guilds:
invites[guild.id] = await guild.invites()
@bot.event
async def on_invite_create(invite):
if not invite.guild.id == 1039553876778561536:
return
invite_time = ""
if invite.max_age == 0:
invite_time = "Forever"
if invite.max_age == 1800:
invite_time = "30 Minutes"
if invite.max_age == 3600:
invite_time = "1 Hour"
if invite.max_age == 21600:
invite_time = "6 Hours"
if invite.max_age == 43200:
invite_time = "12 Hours"
if invite.max_age == 86400:
invite_time = "1 Day"
if invite.max_age == 604800:
invite_time = "7 Days"
if invite.max_uses == 0:
invite_uses = "Unlimited Uses"
else:
invite_uses = str(invite.max_uses)
channel = invite.guild.get_channel(1111678175374741646)
embed = discord.Embed(
color=discord.Colour.yellow(),
title="Invite Created",
description=f"""
Created By: {invite.inviter.mention} ({invite.inviter} - {invite.inviter.id})
Valid For: {invite_time}
Uses: {invite_uses}
Invite Code: {invite.code}"""
)
await channel.send(embed=embed)
for guild in bot.guilds:
invites[guild.id] = await guild.invites()
def find_invite_by_code(invite_list, code):
for inv in invite_list:
if inv.code == code:
return inv
@bot.event
async def on_member_join(member):
if not member.guild.id == 1039553876778561536:
return
invites_before_join = invites[member.guild.id]
invites_after_join = await member.guild.invites()
channel = member.guild.get_channel(1111678175374741646)
for invite in invites_before_join:
if invite.uses < find_invite_by_code(invites_after_join, invite.code).uses:
embed = discord.Embed(
color=discord.Colour.green(),
title="Member Joined",
description=f"""
Member Joined: {member.mention} ({member} - {member.id})
Invite Code: {invite.code}
Inviter: {invite.inviter.mention} ({invite.inviter} - {invite.inviter.id})"""
)
await channel.send(embed=embed)
invites[member.guild.id] = invites_after_join
return
I am trying to make an invite tracker but it doesn't work for 1 time use invites since they expire and I get an error for trying to use, .uses on a NoneType object
Instead of that humongous if chain just use pendulum
thanks for the suggestion!
But the invite issue is a headache I think it might just not be possible
!d discord.Invite
class discord.Invite```
Represents a Discord [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") or [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") invite.
Depending on the way this object was created, some of the attributes can have a value of `None`.
x == y Checks if two invites are equal.
x != y Checks if two invites are not equal.
hash(x) Returns the invite hash.
str(x) Returns the invite URL...
Could you give full traceback please
Just saying .uses can be None
discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/creator_bot.py", line 124, in on_member_join
if invite.uses < find_invite_by_code(invites_after_join, invite.code).uses:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'uses'
That so basically means invite is deleted after usage
You need a different approach - find the invite that is in old invites but is not in new ones
Can do that with sets
code = ({i.code for i in before_invites} - {i.code for i in after_invites}).pop()
Idk if you can put invites into sets but strings definitely
How do I make my bot detect a message sent in a channel?
@client.event
async def on_message(message):
content = message.content
print(content)
This is not working
!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.
Enable the message content intent and then it will work
You mean this?
I mean the code
Ohh thanks, i had typed intents.members = True
Thanks again!
Also, how do I make my bot work only in a specific server?
- Make it private
- If you want, though unneeded once it's marked private, add an event handler for guild joins and make the bot leave the guild
hmm alright thanks!
Just a toggle to activate in the developer portal
👍
How do I send an ephermal message?
ephemeral=True in your send
Any ideas for commands for both staff and members
what?
I Have a shop server and i have the command "$vouch". I wanna add a command like "$totalvouches" that shows how many people runned the command $vouch, how can i do it?
Like ideas of commands I can add to my discord bot
so how does your vouch command work?
ill show u
please help in #1111990380695658497
@bot.command()
async def vouch(ctx, *, suggestion):
await ctx.channel.purge(limit=1)
channel = discord.utils.get(ctx.guild.text_channels, name='✔〢vouchεs')
suggest = discord.Embed(title=f'{ctx.author.name}', description=f'{suggestion}')
sugg = await channel.send(embed=suggest)
await sugg.add_reaction("❤️")
checkforvideos.start()
File "/home/runner/Nasheeds4u/venv/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 123, in on_ready
checkforvideos.start()
AttributeError: 'function' object has no attribute 'start'
i was doing an on_ready event
show me the code
so this doesnt even do anything apart from adding a reaction?
what's checkforvideos?
the user types example
$vouch very good server
and later in this channel
that's kinda- but ok
you should really store the count in a db unless you want to make tons of api calls every time you get the count (channel.history)
@tasks.loop(seconds=900)
async def checkforvideos():
with open("youtubedata.json", "r") as f:
data=json.load(f)
print("Now Checking!")
for youtube_channel in data:
print(f"Now Checking For {data[youtube_channel]['channel_name']}")
channel = f"https://www.youtube.com/channel/{youtube_channel}"
html = requests.get(channel+"/videos").text
try:
latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
except:
continue
if not str(data[youtube_channel]["latest_video_url"]) == latest_video_url:
data[str(youtube_channel)]['latest_video_url'] = latest_video_url
with open("youtubedata.json", "w") as f:
json.dump(data, f)
discord_channel_id = data[str(youtube_channel)]['notifying_discord_channel']
discord_channel_id = client.get_channel(int(discord_channel_id))
msg = f"{data[str(youtube_channel)]['channel_name']} Just Uploaded A Video Or {data[str(youtube_channel)]['channel_name']} is Live Go Check It Out: {latest_video_url}"
await discord_channel_id.send(msg)
checkforvideos.start()
@checkforvideos.before_loop
async def checkforvideos():
print('waiting... 2 ')
await client.wait_until_ready()
@client.tree.command(name="add_youtube_notification", description="admin only")
@app_commands.default_permissions(administrator=True)
async def add_youtube_notification(interaction: discord.Interaction, channel_id: str, *, channel_name: str):
with open("youtubedata.json", "r") as f:
data = json.load(f)
data[str(channel_id)]={}
data[str(channel_id)]["channel_name"]=channel_name
data[str(channel_id)]["latest_video_url"]="none"
data[str(channel_id)]["notifying_discord_channel"]="1111972172303437935"
with open("youtubedata.json", "w") as f:
json.dump(data, f)
await interaction.response.send_message("Added the YouTube Account Data!")```
the 2nd wont work bc every time someone writes the command it gets deleted
@client.event
async def on_ready():
await client.change_presence(activity=discord.Activity(type = discord.ActivityType.watching, name='Nasheeds4u'))
print("bot online")
try:
synced = await client.tree.sync()
print(f"synced {len(synced)} commands")
except Exception as e:
print(e)
checkforvideos.start()```
dont use, use
requests, aiohttp
json, a db
on_ready, a startup task or setup_hook
that is the on ready event
..but the vouches channel
just use channel.history to get the messages in that channel
how can i use a startup task?
its my first time making a bot to be honest so i dont know how
don't know how to what
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
use channel.history
heres the docs then
does it need to be in a class?
what do i replace with self if it is not in a task
async def setup_hook() -> None:
checkforvideos.start()``` could I do this
async with aiohttp.ClientSession() as session:
async with session.get(channel+"/videos") as resp:
html= await resp.text()``` I put aiohttp
but still doesnt work
!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.
Doesn't explain anything
And you have two functions named checkforvideos. How is it possible to not notice that
bruh
i deleted 1 but still not working no error
yeah but when the bot comes online it needs to start checking
can someone help me
what doesn't work about it, dont just say someone help me
nvm about it
Hi, I created 2 buttons left arrow and right arrow and I want, once clicked it turn page but idk how to do. I found a tutorial on YouTube but it is with réactions and I want with buttons ^^
I don’t want the bot to respond to the interaction but just to change the page of the embed
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.

Why is this not working?
# Get the channel object
channel = client.get_channel(1067852667755429980) # Replace with your desired channel ID
# Fetch messages from the channel
async for message in channel.history(limit=None):
# Check if the message is not a pinned message and older than 2 minutes
if not message.pinned and message.created_at < datetime.now() - timedelta(minutes=2):
await message.delete()```
what do you mean not working
^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'history'```
is this in a command?
No, I want to run it as a task:
class MyClient(commands.Bot):
async def on_ready(self):
print('Bot is ready!')
async def setup_hook(self):
auto_delete_messages.start()
@tasks.loop(seconds=10) # Adjust the interval as needed
async def auto_delete_messages():
# Get the channel object
channel = client.get_channel(1067852667755429980) # Replace with your desired channel ID
# Fetch messages from the channel
async for message in channel.history(limit=None):
# Check if the message is not a pinned message and older than 2 minutes
if not message.pinned and message.created_at < datetime.now() - timedelta(minutes=2):
await message.delete()```
is 1067852667755429980 a valid channel id?
Yes
well maybe the bot has not grabbed all guilds so it cannot find the channel
like the bot is not ready yet
they have different tzinfo I guess
also why do you need such task deleting messages every 2 minutes
obv but what's the purpose of it
how can i make a command channel specific? (so the command only works in that one channel)
U haven't added ctx in the async
Hm
Added
...
bot.remove_command("help")
@bot.command()
async def help(self, ctx):
embed = discord.Embed(title="**__Celestial Help__**",description="My pefix is !\nUnder development", color=discord.Color.blue())
embed.add_field(title="**Some catagory of my commands are**", description=" Utility\n Moderation\n Fun\n Giveaway")
await ctx.send(embed=embed)
There is no self in main commands
No need to use self this is not a cog
Then what I use
;-;
help_command=None in your bot constructor
Subclass it
Oh I can use it?
Idk how to do it ;-;
Better practice than remove_command
Ok
Nvm this can you send me a good docs for adding that function that change our message to another msg
Eg. I have done ?help and help menu come then i choosed utility catagory from last tab
@slate swan hey in embed.add_field we can't use title ???
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
hello anyone know, if it's possible to make this in discord.py ?
Yes, it's called a modal
with how function i do that ?
it's not in discord.py, i don't find
ho thanks !
@slate swan hey can you tell me how to make this maybe last ping please
it's a "SelectView"
a View
How can I make it
@client.tree.command(name="random-number", description="sends a random number choose a number e.g 1 10")
async def randomnumber(interaction: discord.Interaction, number1: int, number2: int):
await interaction.response.send_message(f"you chose a number from {number1} to {number2} and you got:", random.randint(number1, number2))
Traceback (most recent call last):
File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 24, in randomnumber
await interaction.response.send_message(f"you chose a number from {number1} to {number2} and you got:", random.randint(number1, number2))
TypeError: InteractionResponse.send_message() takes from 1 to 2 positional arguments but 3 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/random-number-generator/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'random-number' raised an exception: TypeError: InteractionResponse.send_message() takes from 1 to 2 positional arguments but 3 were given```
...
What the 😂
so im making a random number command where you chose the from number to number
class Select_catalogue(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="text",emoji="🌠",description="text"),
discord.SelectOption(label="text2",emoji="🚀",description="text" + commandes_admin[1]),
]
super().__init__(placeholder="Cliquez pour consulter les commandes disponible",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction, timestamp=None):
if self.values[0] == "text":
embed_test = discord.Embed(colour=None, color=random.choice(colors), title='Fonction de Bienvenue !', type='rich', description='test')
await interaction.response.send_message(embed=embed_test ,ephemeral=True)
elif self.values[0] == "text2":
embed_test = discord.Embed(colour=None, color=random.choice(colors), title='commande', type='rich', description='test')
await interaction.response.send_message(embed=embed_test ,ephemeral=True)
# Classe pour appellez le catalogue
class SelectView(discord.ui.View):
def __init__(self, ctx):
super().__init__()
self.add_item(Select_catalogue(ctx))
view = SelectView(ctx)
await ctx.send(embed=embed, view=view)
you aren't even setting the string correctly
Dont tell me you code it for me
dont spoonfeed
and i got this error
it's a example for how use that
read your code again
Oh ok
me?
yes
ok
how are you sending your messages
responding
Hey you know it's a class how can I import this in my bot.command?
await interaction.response.send_message(f"you chose a number from {number1} to {number2} and you got:", random.randint(number1, number2))
you think this is correct?
yes...
this isn't print()
you can't just concat string like that
put it inside the f string
@astral ether hm
ohhhhhhhh i see
Put it in f string or it will print number1 instead of the no. You entered
Hmm you already told..
what how would it print it
What ?
It will print
no it cant
Number1
i dont have print in my code
Huh send_message I mean 🗿
oh

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
what is a _meta ?
Never heard of that
Here i am trying to create the model and once i try to add the author id to the ManyToManyField It won't work due to that error.
Using tortoise that should be the way to add an id to the models
anyone know why this constantly appearspy Ignoring exception in on_application_command_error Traceback (most recent call last): File "c:\path-to-file", line 490, in _run_event await coro(*args, **kwargs) File "c:\path-to-file", line 281, in on_application_command_error raise error File "c:\path-to-file", line 890, in invoke_callback_with_hooks await self(interaction, *args, **kwargs) File "c:\path-to-file", line 3402, in trivia await interaction.channel.send(file=file, embed=embed) File aiohttp.client_exceptions.ClientOSError: [Errno 1] [SSL: SSLV3_ALERT_BAD_RECORD_MAC] sslv3 alert bad record mac (_ssl.c:2578)
hello someone fix this error ?
Traceback (most recent call last):
File "C:\Users\aress\OneDrive\Bureau\Selfbot\main.py", line 42, in <module>
bot = commands.Bot(command_prefix='.',self_bot=True)
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'
you're missing the intents argument in the bot instance
if i send you the main.py can you fix it ?
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='.', self_bot=True, intents=intents)
This will enable all 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.
where do i put it?
wait go dm plz
self_bot argument doesn't exist anymore iirc
You would put it under your imports in your main.py file
I have no clue
I think you're right though, self_bot is to indicate self bots iirc
fyi; selfbots are not allowed by discord and you risk your account getting permanently banned
because you haven't defined anything called ButtonView
i keep getting
TypeError: expected token to be a str, received NoneType instead
are you using a valid token when running your bot? make sure it isnt empty
.env file has "DISCORD_TOKEN=jgeiebebnendiscordtokenhsjsjsjdjj"
i could generate a new tolen
pritn it make sure it prints correctly
token
how can i make automatic message sent when i upload video/post to instagram i want it to sent to #instagram
hi
you probably want an instagram webhook
💀
stop making selfbots
lmao ☠️
actually doing a little research it looks like instagram shut down their feed api
instagram reels user
nobody uses reels
how can i make it so these commands only work in a channel with the id of "1111885634336985178"
how would one create instances for discord bots? so that people can use their own tokens for a discord bot to get their own branding on a bot?
i see you used my code
yeah
thanks for that, it looks really nice
# adding reactions not what this does btw, this is just a check to make sure the reaction is correct
thats just for me to understand it better
lol
@smoky sinew I got a question
- you can use
{user.mention}instead of<@{user_id}> if member == None:should beif member is None:and name and pfp should be defined outside the if statement- for the leaderboard you need a database
- minor nitpick - you don't need time or os, and you don't need reactions intent since you already have it included in n
discord.Intents.default()
as for your actual question @snow coral
you can add a global check
can you check here?
bot.add_check(lambda ctx: ctx.channel.id in ALLOWED_CHANNELS)
talking to me?
or with a decorator: ```py
ALLOWED_CHANNELS = (1111885634336985178,)
@bot.check
def check_channel(ctx: commands.Context) -> bool:
return ctx.channel.id in ALLOWED_CHANNELS
im getting an error with that
with what
TypeError: argument of type 'int' is not iterable
you forgot the comma at the end then
(1111885634336985178**,**)
that makes it a tuple
() and (0,) are both tuples, (0) is a singleton
oh
(((0))) is still a singleton
didnt think the comma was important
how can i whitelist more than one channel
like 2
instead of 1
okay
thanks for all the help! the bots finished now :)
cool
does anyone wanna help or explain to me how to make antinuke command?
yes
just have a bunch of checks and a counter for each user
well..
ban them if they’re over a threshold
uhm idk
events
Why is it none? when is it being added to the database, and the return message for afk member when comes back works perfectly fine and it also gets removed from db
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
The get_member method will return None if the member was not found 🤷
Well thats weird…. if its not found in database or message mentions?
if it's not found in cache, which is only populated if you've got the members intent enabled
all intents are enabled
get_member expects an ID, not a mention
you sure user_m isn't a string?
what does get_or_create return?
User.get_or_create returns your model object and a bool, so your user_m is a model, use user_m.id
tortoise ORM, the thing says it all. Let me send u the docs in a min
It is not a bool because im using the user discord entity field to detect user ids
in the database is being added the int of the afk member
That doesn't answer anything
@Cog.listener()
async def on_message(self, message: Message):
if message.author.id == self.bot.application_id:
return
afk = await AfkModel.get_or_none(guild_id=message.guild.id)
user, created = await User.get_or_create(id=message.author.id)
if afk:
if message.author != message.guild.owner:
await message.author.edit(nick=message.author.name)
async for item in afk.discord_id:
if item.id == message.author.id:
await message.reply(
f"Welcome back {message.author.mention}! "
f"You went afk - {format_dt(afk.time, style='R')}"
)
await afk.discord_id.remove(user)
if message.mentions:
if afk:
async for item in afk.discord_id:
if item.id == message.mentions[0].id:
member = message.guild.get_member(item)
await message.reply(
f"**{member.display_name}** is AFK because: `{afk.reason}` "
f"{format_dt(afk.time, style='R')}"
)
Ok so look, in this part im also checking the message, which works perfectly fine
Only the message mentions are the problem
even if i pull the objects out of the discord_id which is the afk member list for that guild it would still return none
https://tortoise.github.io/models.html#tortoise.models.Model.get_or_create
Tuple[Self, bool]
user_m, created = await User.get_or_create(id=message.mentions[0].id)
^^^^^^
member = message.guild.get_member(user_m)
^^^^^^
your user_m is not an int
i wouldnt use orm without knowing fundamental tbh
I just assumed it
plus orm is always slower
i would just use a db driver like asyncpg and do raw sql from that, last time i used tortoise orm is when it is provided by the framework like django
I just feel that my entire setup suits, and it's decently made :)
So i will just continue using tortoise for now
sure
definitely has more pros than cons to it
altho i don't specifically use orm i use asyncpg for the sql queries and attrs/dataclasses to validate models
There's 1 more issue i forgot about, adding time and reason per user, not per guild 😂
only pros i can think of is it being faster to develop an application with friendly interface assuming you already have the skill and good core, but the cons are still huge, slower runtime, not skill transferable to other languages. not knowing the fundamental of sql would be an issue for the user not knowing how would they optimize a query. everytime you are face with a new orm you are force to relearn the quark of that orm, it gets annoying
i don't use orms out of the box for that reason i just use dataclasses with attrs and such for more structured data and performing operations based on that i don't see a huge speed reduction and its quite necessary with nosql dbs like mongodb which don't internally perform validation so u could spend hours debugging where ur inserting or updating wrong data unlike sql
then again not sure about tortoise in SQL it's simply just paired primary key of user and guild together
Well i will manage to finish that a bit later, I'm happy that i still managed to add multiple users to 1 field because at first i didn't know about ManyToMany relations, so i'll take it as a win for now
I currently have no logic to do this, but i will surely find out tomorrow
good luck 👍
Will need it 
Do you guys think that should i rewrite the entire code making user id primary, which means more tables but i wont need to sort all the schema out i just have to add the guilds to the user id which would be a lot easier
what do you guys think? @shrewd apex @golden portal
which is even more nice i can add timestamp on creation
and it wont cause any issues
i do not know what the goal is so
Building a afk command using postgreSQL 😂
so i mean, if you're talking about AFK table to store the afk states, depending on how you want it to behave for example, if you want it to apply to just a specific guild, make both user id and guild id a primary key, so its a composite key, if you want the afk to apply to all guilds, make only user id a primary key
^^
CREATE TABLE IF NOT EXISTS afk_members (
user_id BIGINT NOT NULL,
guild_id BIGINT NOT NULL,
since TIMESTAMP NOT NULL DEFAULT (NOW() AT TIME ZONE 'utc'),
reason TEXT,
PRIMARY KEY (user_id, guild_id)
);
why do u need not null for user id and guild id u already have the as primary key also u can have "No reason provided" as default for reason
why would you want "no reason provided" as the default reason
that should be a frontend thing
why not? it can be done here also
what if they want multiple languages for example, then you would have to update all rows from "no reason provided" to null
if they want multiple languages let the user just enter in their own language

@commands.group(invoke_without_command=True)
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
if role in user.roles:
await user.remove_roles(role)
else:
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
await user.remove_roles(role)``` how do I add more of these commands?
just put more..?
user: discord.Member
btw on commands like these you need a guild_only check
though i think has_permissions takes care of that
If someone blocked you, they don't see your messages
Unless they explicitly look at the message, which then misses the point of having them blocked
🤨
hey mudkip, I don't know if you remember me but can you unblock me in dms and we need to talk.
hey mudkip, I don't know if you remember me but can you unblock me in dms and we need to talk.
yup
When creating ticket transcripts, i currently get them uploaded to github and then have to manually download them and open the .html
is there a way i can get these to auto upload to somewhere like tickettool so i do not have to download and rather be able to just open in the internet?
how do I access them?
!d discord.app_commands.CommandTree.fetch_commands
await fetch_commands(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the application’s current commands.
If no guild is passed then global commands are fetched, otherwise the guild’s commands are fetched instead.
Note
This includes context menu commands.
The returned objects have an id attribute
For example
cmds = await bot.tree.fetch_commands()
print(cmds) # List of AppCommand objects
!d discord.app_commands.AppCommand.id
The application command’s ID.
0|hak | Ignoring exception in on_application_command
0|hak | Traceback (most recent call last):
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 700, in _run_event0|hak | await coro(*args, **kwargs)
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1361, in on_application_command
0|hak | await self.process_application_commands(interaction)
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1353, in process_application_commands
0|hak | await app_command.invoke(interaction)
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/slash_core.py", line 719, in invoke
0|hak | await self.prepare(inter)
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 324, in prepare
0|hak | if not await self.can_run(inter):
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 630, in can_run
0|hak | ret = await maybe_coroutine(local_check, inter)
0|hak | File "/usr/local/lib/python3.10/dist-packages/disnake/utils.py", line 599, in maybe_coroutine
0|hak | return await value
0|hak | File "/root/Hak/cogs/cards.py", line 20, in cog_slash_command_check
0|hak | r = await self.bot.get_profile(inter.author.id)
0|hak | File "/root/Hak/db.py", line 178, in get_profile
0|hak | async with self.curr.acquire() as conn:
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 998, in __aenter__
0|hak | self.connection = await self.pool._acquire(self.timeout)
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 838, in _acquire
0|hak | return await _acquire_impl()
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 823, in _acquire_impl
0|hak | proxy = await ch.acquire() # type: PoolConnectionProxy
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 137, in acquire
0|hak | await self.connect()
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 129, in connect
0|hak | self._con = await self._pool._get_new_connection()
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/pool.py", line 521, in _get_new_connection
0|hak | con = await connect_utils._connect_addr(
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/connect_utils.py", line 768, in _connect_addr
0|hak | return await __connect_addr(params, timeout, False, *args)
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/connect_utils.py", line 825, in __connect_addr
0|hak | tr, pr = await compat.wait_for(connector, timeout=timeout)
0|hak | File "/usr/local/lib/python3.10/dist-packages/asyncpg/compat.py", line 56, in wait_for
0|hak | return await asyncio.wait_for(fut, timeout)
0|hak | File "/usr/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
0|hak | return fut.result()
0|hak | File "/usr/lib/python3.10/asyncio/unix_events.py", line 254, in create_unix_connection
0|hak | await self.sock_connect(sock, path)
0|hak | File "/usr/lib/python3.10/asyncio/selector_events.py", line 500, in sock_connect
0|hak | return await fut
0|hak | File "/usr/lib/python3.10/asyncio/selector_events.py", line 505, in _sock_connect
0|hak | sock.connect(address)
0|hak | FileNotFoundError: [Errno 2] No such file or directory
```I start getting this error after a few hours of uptime on my bot. I have no idea why this is happening and the bot won't respond to any commands after this. A temporary fix is just to restart the entire vps.
When creating ticket transcripts, i currently get them uploaded to github and then have to manually download them and open the .html
is there a way i can get these to auto upload to somewhere like tickettool so i do not have to download and rather be able to just open in the internet?
are you sure you have all files needed on the vps?
how do you convert a File/Attachment object to bytes 💀
@client.tree.command(name="random-number-button", description="Sends a button that when clicked sends a random from number1 to number2")
async def randomnumberbutton(interaction: discord.Interaction, number1: int, number2: int):
try:
button = Button(label=f"Random number from {number1} to {number2}", style=discord.ButtonStyle.primary)
channel = client.get_channel(1112053260879147130)
async def button_callback(interaction):
await interaction.response.send_message(random.randint(number1, number2))
await channel.send(f"random number button clicked by {interaction.user}")
button.callback = button_callback
view = View()
view.add_item(button)
await interaction.response.send_message("Click the button to get a random number from 1 to 20", view=view)
await channel.send(f"random-number-1-to-20-buttons command used by {interaction.user}")
except:
channel2 = client.get_channel(1112053260879147130)
await interaction.response.send_message("error: The number1 needs to be bigger than number2")
await channel2.send(f"random-number-button command used by {interaction.user} but an error occured")
this command won't send.
no error
Did you try to look at your own code
yeah
Then you should already see what's wrong
I can't see anything wrong
Your code responsible for responding is inside the button callback
And it will never be executed
thanks zefo
How to add that add to server button on a bot
@client.hybrid_command(name="logging", description="Setup your logging channels")
async def logging(ctx, log_type, channel: discord.TextChannel):
log_type.options= {
"role_update",
"message deleted",
"message edited",
"Moderation Actions"
}
valid_log_types = ["role_updates", "message_deletes", "message_edits", "mod_actions"]
if log_type not in valid_log_types:
await ctx.send("Invalid log type. Valid log types are: role_updates, message_deletes, message_edits, mod_actions.")
return
set_log_channel(ctx.guild.id, log_type, channel.id)
await ctx.send(f"{log_type} logs will be sent to {channel.mention}")
why can i not get options when i do /logging?
Because that's not how you set options??
You're setting .options attribute of a string in the command callback
ive not read it im asking for someone else, cuz hes banned from the cord
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
this will error out as soon as command is run
it will raise an AttributeError
Tell him to read the app_commands documentation
And send this
hello, anyone know how to use database with discord.py ?
@commands.group(invoke_without_command=True)
@commands.has_permissions(manage_roles=True)
async def role(self, ctx, user: discord.Member, *, role: discord.Role):
if role in user.roles:
await user.remove_roles(role)
else:
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, user: discord.Member, *, role: discord.Role):
await user.add_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
await user.remove_roles(role)
@role.group()
@commands.has_permissions(manage_roles=True)
async def create(self, ctx, user: discord.Member, *, role: discord.Role):
await user.create_roles(role)``` like that? because in the create command it is white at create_roles instead of being colored
well me for my personal bots I use files to save my data but I would like to switch to a database for the bots which are on a lot of servers, but I have never used a database
^
What's your question?
is this correct? because when its in role add or remove it is colored at the user.remove_roles(role) and user.add_roles(role) but it is white at user.create_roles(role)
So maybe create_roles isn't a valid method?
Did you check the documentation to see if it exists?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
What is user.create_roles even supposed to do
You can't create roles for specific members in discord
You create roles specific to servers (guilds)
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
New in version 2.0: The `display_icon` keyword-only parameter was added...
@role.group()
@commands.has_permissions(manage_roles=True)
async def create(self, ctx, *, role: discord.Role):
await create_role()``` so start like this?
im js confused on what to do ik how to code it now but like
what should the primary code to set it up look like?
get a Guild object (eg, ctx.guild); call it's create_role method
class AfkModel(Model):
"""AFK Model."""
discord_id: int = BigIntField(pk=True)
guild_id: ManyToManyRelation[Guild] = ManyToManyField(
"Bot.Guild", related_name="afk_guilds"
)
reason = TextField(null=False)
time = DatetimeField(auto_now=True)
@slash_command()
async def afk(
self,
inter: disnake.ApplicationCommandInteraction,
reason: str = Param(default=Ellipsis, max_length=100),
):
"""
Set your status to AFK.
Parameters
----------
reason: Reason for going AFK.
"""
if "[AFK]" in inter.author.display_name:
await inter.send("AFK detected in name, aborting...")
return
await inter.response.defer()
afk = await AfkModel.get_or_none(discord_id=inter.author.id)
guild, created = await Guild.get_or_create(id=inter.guild.id)
if afk:
await afk.guild_id.add(guild)
await AfkModel.update_or_create(reason=reason)
else:
afk_create = await AfkModel.create(
discord_id=inter.author.id, reason=reason
)
await afk_create.guild_id.add(guild)
if inter.author != inter.guild.owner:
await inter.author.edit(nick=f"[AFK]{inter.author.display_name}")
await inter.send(
f"Set your status to AFK with reason: `{reason}` {format_dt(utcnow(), style='R')}"
)
@Cog.listener()
async def on_message(self, message: Message):
if message.author.id == self.bot.application_id:
return
afk = await AfkModel.get_or_none(discord_id=message.author.id)
guild, created = await Guild.get_or_create(id=message.guild.id)
if afk:
if message.author != message.guild.owner:
await message.author.edit(nick=message.author.name)
async for item in afk.guild_id:
if item.id == message.guild.id:
await message.reply(
f"Welcome back {message.author.mention}! "
f"You went afk - {format_dt(afk.time, style='R')}"
)
await afk.guild_id.remove(guild)
if message.mentions:
user = await AfkModel.get_or_none(discord_id=message.mentions[0].id)
member = message.guild.get_member(user.id)
await message.reply(
f"**{member.display_name}** is AFK because: `{afk.reason}` "
f"{format_dt(afk.time, style='R')}"
)
This afk command works almost fine, the only issue that im having is that once a user goes afk in a certain guild, then goes to another guild afk the reason and time will be updated to the "new afk guild" and i don't want that, reason and time should be per guild
anyone have any ideas of how could i make reason and time per guild?
class Guild(DiscordEntity):
"""Base Guild model, meant to be reference by extensions"""
async def fetch(self, bot: InteractionBot) -> DiscordGuild | None:
"""Returns the associated guild for the given guild Model."""
return bot.get_guild(self.id)
you need a composite primary key of (discord_id, guild_id), and you'll need to pass both of those when fetching from the database
Here's the thing, using this orm i don't know how to have multiple primary keys
i actually tried looking for that
in the tortoise orm docs
i see
well you can still fetch the model with both values
afk = await AfkModel.get_or_none(discord_id=message.author.id) doesn't mention the guild id... you need to add that so it only retrieves the model for the current guild
Yeah i told u my only problem because basically the schema now is like this:
{afkuser:id, afkinguilds:[1,2,3..], reason:reason, time:time}
are you actually storing a list?
I did, and you have a Many to Many relation, that's not the same as storing a list
not at all, there are two main tables and a third one that relates them
And let me tell you why, if i had made the models simple, having guild id as aprimary let's say, another user couldn't go afk right?
Because of duplicated key
And that's the reason why i've moved to mtm relations
So i can store multiple guild ids where the user can actually go afk
yes, but your database is not storing a list
there is a table for Afk users, a table for Guilds, and a table that relates them
even though you might be getting a list in python (thanks to the ORM)
that doesn't change my answer, you need to adjust your code so it will only retrieve the AfkModel that belongs to the current guild
Well yeah it is not a list, it's storing multiple fields of guilds id, was just telling u an example
That's the problem! I told you already, that works fine basically
But if you go in other guilds afk reason will be updated same as time
here is adding the new guild if the afk member id was already found
and by updating the model using update_or_create it will update the reason which shouldn't be doing that
and the time is automatically being updated thanks to the DatetimeField
so i don't need to store a str and whatever, just a painful thing
actually a m-m relation doesn't make sense here because one AfkModel can only belong to one guild
Table AFK Table Guild
user_id guild_id
guild_id guild_name
... ...
``` it's as straightforward as this
And AFK primary key has to be composite
if your ORM doesnt support that then idk what you can do
Should be able to
I just don't know how to make it composite
Never had multiple pks But knowing how to do it would help a lot in the future
Also mind checking ur dms? I wanna show u an example
@vocal snow
if tortoise has a GitHub repo then check their issues those often contain hidden gems
Managed to fix it thanks to @vocal snow
It works perfectly fine
#databases Definitely a good place to visit 
Hey, could someone help me write bot suggestions
What are you trying to do?
game bot
commands suggestion
That after writing the message, he deletes it, makes a message from the bot with the content written by the user and adds reactions
So someone to "suggest" something for your bot?
.
.
Who writes the message and who is "he"
No look my message
New proposal: Tresc
And the message that the user wrote is deleted and the bot sends it with reactions
embedded most likely
Oh, i could give u a code for that, i was using embed + buttons, it's just outdated, you would have to work on it
It's also connected to database, so in case bot goes offline you can still interact with the buttons
Give me code bro
👍
print("Hello World!")
quick question, how can I safely make a command named list
not so cool
as list is a type
I can't do it yet
if you set the command name in the decorator then the function's name can be different than the command's name
thx
Call the actual command list_ or list_command or something, and set name="list" (like you already have)
yea
Does anyone have command suggestions?
ideas?
then learn
you just take an argument named feedback and then delete ctx.message
name the function _list so it doesn't "interfere" with the reserved variable list
it gets greyed out
or list_
kinda scares me ngl
it will eat you, true
I named it list_
[tool.poetry.scripts]
bot = "spooky.bot.__main__:exec"
web = 'helpers.web_run:dev'
web-prod = 'helpers.web_run:prod'
FROM python:3.11 as base
RUN apt update
RUN apt install -y python3-pip python3-wheel gcc
RUN pip install poetry
WORKDIR /app
COPY ./poetry.lock ./pyproject.toml /app/
RUN poetry config virtualenvs.create false
RUN poetry install
COPY . /app/
FROM base as web
EXPOSE 8000
CMD python3 ./helpers/wait_to_db.py && poetry run aerich init-db && poetry run web-prod
FROM base as bot
CMD python3 ./helpers/wait_to_db.py && poetry run aerich init-db && poetry run bot
Pretty sure you need compose
hey so, i'm new to discord.py and i want to make a command that would search a channel for a certain message string and then return a value of of how many messages were found including that string. i'm not exactly sure how i could go about this so any help would be appreciated!
Actually no, i just texted someone that contributed to docker, They said it's well structured and it doesn't require any changes and that the warning shouldn't be affecting the bot
which in fact it doesn't affect the bot and it works properly
you could just use TextChannel.history but you would probably need to cache the messages to make it a lot faster
this is what i have so far, it's going well but i'm not entirely sure how to actually count a specified word, i've tried a few things without avail, some explanation would be helpful, thanks!
Compare your specified word with message.content
Also this is already a built-in feature on Discord, just letting you know
i know, just wanted to challenge myself and build it into a bot
this is gonna be extremely slow
like you could be looping over millions of messages
and making a lot of api calls
also you want to define counter inside the command, and use += 1 instead of + 1
is there any possible way i could make it more efficient?
cache messages in some kind of database
though you should ask for consent as storing messages is pretty invasive
yeah, currently just on a private testing server with only myself in it
this can greatly reduce your API calls: you can basically "catch" every message in your on_message and count in that event instead
possible downside: if your bot goes offline, the messages won't be counted anymore
Just made this https://hastebin.com/share/judosijoko.rust and I'm off to sleep, I'd like to wake up with a few ideas of slash commands or other thing to make
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
format your code https://pypi.org/project/black
lol
Formatting is for chumps!
awful take
Heh
Just bored. Gotta sit in car waiting for some old man to finish getting zapped .
:-; I could be home programming but nooo real life is like “go outside” and I’m like no there are bees
D:
Bees are nice
how do i make my bot have a status
thanks
why does my bot have its own help command that i never coded
and how do i get rid of it
cause i wanna make my own help command
discord.ext.commands.Bot comes with its default help command
i fixed it
what are you trying to do
if you're extending the default one you can just override MinimalHelpCommand or HelpCommand otherwise just set help_command to None ```py
bot = commands.Bot(
...,
help_command=None
)
Well I kinda do have concerns about that person knowing dockerfile well. First, as per dockerfile reference, you cannot have more than one CMD instruction in single Dockerfile. Second, multiple FROM statements indicate that you are doing multi-stage build. I highly doubt this is your case, as it's typically used in scenario where you first need to build an executable then to run it. From what I can see, you want to run a bot then concurrently run web. That's exactly what docker-compose is for.
The warning actually appears because of enabled logging I guess. I couldn't find any information regarding dev mode on disnake docs but heard it automatically reloads extensions on files change
Warning has nothing to do with docker but you definitely should look into compose
Hey guys just interested if any of you had preferences around cloud hosting ? If so who did you go with ? Thx
async def kick(interaction: discord.Interaction, member: discord.Member, Reason):``` what do i put in the reason
Put what in what
Put in a annotation for reason
You should already know what to put there if you know what you're doing
It's like the easiest thing imaginable
ok
Put in anything you want, you namesd the parameter reason so I’m assuming jt expects one
async def kick(interaction: discord.Interaction, member: discord.Member, *, reason = "no reason provided"):``` I thought this would work
that makes it so that if the reason is not passed, the default reason is 'no reason provided', you can still pass the reason when running the command for it to set the reason 🤷♂️
Yeah but i cant run my bot Traceback (most recent call last): File "main.py", line 60, in <module> async def kick(interaction: discord.Interaction, member: discord.Member, *, reason= "no reason provided"): File "/home/runner/number-bot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 887, in decorator command = Command( File "/home/runner/number-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 665, in __init__ self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__) File "/home/runner/number-bot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 370, in _extract_parameters_from_callback raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}') TypeError: parameter 'reason' is missing a type annotation in callback 'kick'
try defining reason as a string and then setting default value like:
reason: str = "no reason provided"
ok
thanks
fixed?
yes i forgot the colon in reason
@client.event
async def on_app_command_error(interaction: discord.Interaction, error):
if isinstance(error, app_commands.ValueError):
command = interaction.app_command
channel2 = client.get_channel(1112053260879147130)
await interaction.response.send_message("error: number1 needs to be bigger than number2")
await channel2.send(f"{command} command used by {interaction.user} but an error occured")
```how can i get this error handling to work
how can i do button error handling
i just updates my discord py module and my bot isnt working anymore
turns out i have been working on 1.7 version all this time and the latest version is 2.2
it was a bad choice to learn from open ai
then update your code to work with 2.2
how can i do button error handling?
well i just checked the pings and thats what im gonna do next year
good bye
btw
# before
bot.load_extension('my_extension')
# after using setup_hook
class MyBot(commands.Bot):
async def setup_hook(self):
await self.load_extension('my_extension')
# after using async_with
async def main():
async with bot:
await bot.load_extension('my_extension')
await bot.start(TOKEN)
asyncio.run(main())
``` which one is better to use? and how
i believe setup_hook is better
can you explain how it works?
i mean
do i run the bot normally as bot.run(token) like before if i use setup_hook?
or it needs to be awaited or something?
and is that class auto assigned to the bot or there is a way?
if im saying anything stupid pls dont kill me
setup_hook and async with bot are both good
setup_hook is called automatically when the bot starts, using that method you'd simply use bot.run(token)
when you're using async with, you do need to call discord.utils.setup_logging, since bot.start doesnt automatically set it up
override the on_error method of your ui.View class
does d.py implement __aenter__ and __aexit__ on commands.Bot?
oh thanks
guys how can i make it that my bot checks if there is a user mentioned in a message like in a command for example
@bot.command()
async def send(ctx,*,message):
like in this case i want it to check if there is a mention in the message and reply with yes or no
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
This might be what you're after
hmm let me see
Hi, what's the way to get the default converter for type?
I want to make my custom converter, that first tries to convert the value with it's converter and then can do something else with them.
- how should i call that converter so it would work absolutely the same as if just typehinted the function as
arg: intfor example?
will justargument = await converter.convert(ctx, argument)work?
HERE_IS_MY_COOL_TOKEN = "..."
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".", intents=discord.Intents.all(), test_guilds=[703325198086307860])
class TestArgConverter(commands.Converter):
def __init__(self, type_):
self.type_ = type_
async def convert(self, ctx, argument):
converter = ??? # get default converter for self._type
argument = await converter.convert(ctx, argument)
# Some extra stuff
return argument
@client.command()
async def test(ctx, arg: TestArgConverter(int)):
...
client.run(HERE_IS_MY_COOL_TOKEN)
Actually i guess i found it https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/converter.py?#L1210-L1245
But i will still appreciate any comments and suggestions
!d discord.ext.commands.run_converters
await discord.ext.commands.run_converters(ctx, converter, argument, param)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Runs converters for a given converter, argument, and parameter.
This function does the same work that the library does under the hood.
New in version 2.0.
this one is the public function you should use instead of a private one
ty
whats some good moderation command i could code in my bot?
mute
you can do much with it
when you have basic logic you can extend it to be able to mute everyone in a role for example
Timeout 🥱
okay i don't know if i'm doing this right, but seems to work:
maybe changing connect to connection
using a persistent view or listening to on_reaction event if u want to do it with reactions i recommend using buttons
Yes but how.. can u say what i need to code? or send it to me?
Ive never did a embed
Thats my code now
sigh replit
i'd really rather do tutorials with youtube for discord.Embed and buttons since it's its own rabbit hole
Is discord.py discontinued?
that is old news. reaaaally old news.
it's been recontinued quite a while back
it repeats itself
Hi! Having some trouble getting this command (entire extension actually) to work. I am adding a basic functionality to my bot so that I can do a command with a message ID and it will give me a list of everyone who reacted on it.
This is my extension currently
import discord
from discord.ext import commands
class GiveawayCog(commands.Cog, name="Giveaway"):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.command(description="Get list of users who reacted to a specific message.")
async def reactlist(self, ctx, message: discord.Message) -> None:
message_id = message
channel = message.channel
found_message = await channel.fetch_message(message_id)
reaction_users = []
for reaction in found_message.reactions:
async for user in reaction.users():
reaction_users.append(user.name)
await message.channel.send(reaction_users)
print ("test")
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(GiveawayCog(bot))
Its not giving an error or anything and seems to be loading it fine, but it just simply does nothing when this command is called.
Any ideas?
Can anyone see my help post
i would just use a list comprehension ```py
reaction_users = [user async for user in message.reactions.users]
users = [
user for user in reaction_users
if user != self.bot.user
and reaction.emoji == "🎉"
]
also there is no need to fetch messages like that, discord.Message fetches for you
but i don't know why your bot wouldn't be responding
And that would take from reaction.users(): line down?
Yeah not sure
it repeats itself idk why
yeah
code
k
found_message = await channel.fetch_message(message_id) so I could get rid of this? @smoky sinew per what you said about discord.messages fetching it?
@smoky sinew bro
Can you see my help post???
https://discord.com/channels/267624335836053506/1112766107011514488
if you use replit i'd atleast recommend using secrets to hide your token because theres a lot of people lurking on replit waiting for bot tokens that arent hidden using secrets
using replit in general isnt a good idea
unless you have a membership because in that case its somewhat decent
people use it because they dont have to download anything


yes start with the code i sent
!d discord.Emoji
class discord.Emoji```
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of `None`...
@commands.command(description="Get list of users who reacted to a specific message.")
async def reactlist(self, ctx, message: discord.Message) -> None:
reaction_users = [user async for user in message.reactions.users]
users = [
user for user in reaction_users
if user != self.bot.user
]
await message.channel.send(reaction_users)
Better?
@smoky sinew hey in this code else statement is wrong can you see why?
@commands.bot_has_permission(timeout_member=True)
async def mute(self, ctx, member: discord.Member, duration: str = "10m", *, reason: str = "No reason"):
if (
ctx.author.top_role >
member.top_role
and self.bot.top_role > member.top_role
and member != ctx.author
and member != self.bot
):
await ctx.send("You cannot ban this user.")
return
else:
try:
td = self._convert_to_timedelta(duration)
Well it's just a warning, considering the bot has NO issues running means that poetry install works perfectly
you have to use users not reaction_users and why is the indentation like that
what's with the indentation again
Can you please edit it by your self please
no
Unsure about the indentation, looks fine on my end so maybe Discord brought it over weird. Here is screenshot. with fixed code so you can see indentation.
Please I am trying to do it but not fixing
that is definitely not right
look at how it looks on discord
for reaction in message.reactions:
if reaction.emoji != "🎉":
continue
users = [
user async for user in reaction.users()
if user != self.bot.user
]
actually just use this
i forgot reaction was not defined
If I wanted it to be any reaction I could theoretically just remove the if reaction.emoji line right?
Bot runs and what about web thing?
sure
That's single dockerfile right?
indentation look fine?
users will not be defined
so I can just get rid of that then
get rid of what
Am I missing something
well it will be defined but it will only get the last reaction*
Is async comprehension a thing
yes
Just found it in PEP 530
anything that implements __aiter__
So if I want it to be any reaction what would I need to change?
append each users to a users list instead of setting the users list to the list comprehension
did you load it
yeah through config
what did you put
"extensions.giveaway"
are the other extensions in the same folder and loaded correctly?
Yeah, here one sec
probably because you're running two bot instances
also what is the point of including the description if you're not going to use it
you're most definitely running 2 instances of the bot
i wanted to make my own help thing
the one already there didnt look good
then what's the point of including the description
idk
how can i make an annotation that you need to put something in
what is an annotation
i know java annotation
like in a command
yes!
what is that
for example /kick member(you must do this) reason(you must do this)
how can i make the reason you must do this
are you talking about slash or prefixed commands?
slash
don't set a default..
do reason: str instead of reason: str = "no reason provided"
ok
@commands.command()
@commands.has_permissions(guild_owner=True)
async def antinuke(self, ctx, *, role: discord.Role, option: str=None):
if option == "on":``` do I just add events now?
@smoky sinew
dont mean to be rude or anything but options annotations is incorrect, its option: str | None = None or option: typing.Optional[str] = None
what
they don't know what annotation means
I'm here to help not to judge
Oh alright! Thank you
Thank you!
I’ve tried to explain to everybody I’m a little new but all I get is docs but they think I haven’t tried docs
No problem
Wish i could help but i left bot dev a while ago sorry
best of luck to you!
I Have a question. How can i make it so when a user joins a vc channel it moves him in another one?
When he joins a specific vc*
Hi, can anyone help me? I'd like to make an embed verification but I can't. Here's my code:
async def verif(ctx):
bouton_verif = Button(label="Acceder au serveur", style=discord.ButtonStyle.green, emoji=":lock:")
view = View()
view.add_item(bouton_verif)
embed = discord.Embed(
title="La verification",
description="Veuillez cliquer sur le bouton ci-dessous pour accéder au reste du serveur. Merci !",
colour=0x7f63d1,
)
embed.set_author(name="Verification")
embed.set_image(url="attachment://verification.png")
file = discord.File("verification.png", filename="verification.png")
embed.set_image(url="attachment://verification.png")
await ctx.send(file=file, embed=embed, view=view)```
basically the lembed senvois but i try to follow youtube tutorials i can't make it so that when we click on the button it adds to the person the role with this id : 1112695505856761958 can sqn help me please
thank you in advance
Can you describe what are you trying to make?
so the command is that when I do the command +verif ( + = my prefix) it sends a embed (attachment) and I would like that when we click on the button below it adds to the person who clicked on the role with the following id: 1112695505856761958 (this is my role member) but it never works youtube tutorials so I come to ask for help here
Okay
give me a moment
okay thanks for the help i appreciate it
Where are you from?
France?
import aiofiles
@bot.command()
async def verif(ctx, role: discord.Role=None, msg: discord.Message=None, emoji=None):
if role != None and msg != None and emoji != None:
await msg.add_reaction(emoji)
bot.reaction_roles.append((role.id, msg.id, str(emoji.encode("utf-8"))))
async with aiofiles.open("reaction_roles.txt", mode="a") as file:
emoji_utf = emoji.encode("utf-8")
await file.write(f"{role.id} {msg.id} {emoji_utf}\n")
await ctx.channel.send("Reaction has been set.")
else:
await ctx.send("Invalid arguments.")
@bot.event
async def on_raw_reaction_add(payload):
for role_id, msg_id, emoji in bot.reaction_roles:
if msg_id == payload.message_id and emoji == str(payload.emoji.name.encode("utf-8")):
await payload.member.add_roles(bot.get_guild(payload.guild_id).get_role(1112695505856761958))
return
Do something like that
guys someone can help me with my project?
What is it?
can we talk privatly?
Whats is it about
discord bots?
betting bot
kk
how can i make this?
detect when a person has joined a voice channel, create a new channel, and then move them to that channel, then check when everybody has left the new channel and delete it
member_update event
can someone send me the docs to on_role_create event
search it on the search bar
read the path
now
how do I make this:
@commands.cooldown(1, per=5400,)
not apply to me or administrators?
!d discord.ext.commands.dynamic_cooldown
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
you can add a logic for you and admins here
alright man thanks :)
Yes and thanks i test tomorrow. can i dm you if i have another problem?
How can I make it so that a loop task executes the same time every day (e.g every day at 10 am)
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
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").
Note the time kwarg
how could i make profile cards?
!d pillow
No documentation found for the requested symbol.
use pillow
im not finding much on how to make them
well that's because pillow is a generic image editing tool
in this case you would probably want to have the background, text, profile picture, and level bar separate
how could i make it so the # of predictions saves from a game instance, so i can use it in the stats menu later on?
https://paste.pythondiscord.com/hixotihevi
database
@mild dome
@steep slate
NO!!!! Didn’t work in the Python discord
Have fun changing it ❤️
just tried creating my first bot, but this discord module attribute error isn't going away, any help please?
it's commands.Bot (discord.ext.commands.Bot, not discord.Bot)
also that tutorial is outdated and will not work
oh really
from dotenv import load_dotenv
from discord.ext import commands
import discord
import os
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(intents=intents, command_prefix="!")
@bot.event
async def on_ready():
print(f"Logged in as {bot}.")
if __name__ == "__main__":
load_dotenv()
bot.run(os.getenv("TOKEN"))
just use something like this, you can keep the event
right
the difference is the intents
which determines what data the discord api will send to your bot
||is there any difference between from dotenv import load_dotenv and from dotenv import load_dotenv()?||
EDIT: importing with the brackets is an error
lol
i thought i was being bad
nvm then
Yeah second is syntax error, if you want to import and load in one line you could
__import__("dotenv").load_dotenv()```
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Perms can be specified in overwrites kwarg, check docs
(don't actually do this)
Why not
!d import it's just discouraged
__import__(name, globals=None, locals=None, fromlist=(), level=0)```
Note
This is an advanced function that is not needed in everyday Python programming, unlike [`importlib.import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module").
This function is invoked by the [`import`](https://docs.python.org/3/reference/simple_stmts.html#import) statement. It can be replaced (by importing the [`builtins`](https://docs.python.org/3/library/builtins.html#module-builtins "builtins: The module that provides the built-in namespace.") module and assigning to `builtins.__import__`) in order to change semantics of the `import` statement, but doing so is **strongly** discouraged as it is usually simpler to use import hooks (see [**PEP 302**](https://peps.python.org/pep-0302/)) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of [`__import__()`](https://docs.python.org/3/library/functions.html#import__ "__import__") is also discouraged in favor of [`importlib.import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module "importlib.import_module").

Anybody able to help me with something?
Who am I kidding? ofc ya'll can.
ya'll smart cookies.
Anyway I am storing this symbol (➤) in a json file, but when I call it to discord it changes to • anybody know why?
How do I catch a Missing permissions exception? I tried commands.MissingPermissions but that doesn't seem to work
is it a slash command?
No, its a normal command
oh damn
i havent used normal commands in a while
that side of discordpy has been pushed out of my brain
maybe something to do with the encoding
most likely this
Is your bot or the user missing permissions? Because those will raise 2 different exceptions
!D pil
No documentation found for the requested symbol.
!d PIL
owner_roles = [1105755873625768017]
moderator_roles = [1105755873625768017, 1108524473788936253]
support_roles = [1105755873625768017, 1108524473788936253, 1108524166656819220]
locked_channels = [1109796765311442967, 1109796850397098065, 1109796957704163338]
blacklisted_words = ["123"]
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle)
print("\x1b[38;5;41m[Success] Bot Online")
@client.event
async def on_message(message):
if message.author.bot:
return
if not message.content.startswith(client.command_prefix):
if any(role.id in owner_roles for role in message.author.roles):
return
content = message.content.lower()
for word in blacklisted_words:
if word in content:
await message.delete()
await message.channel.send(f"{message.author.mention} Your message contains a blacklisted word and has been removed!")
return
await client.process_commands(message)
basically the code is meant to delete the blacklisted message but it doesnt, any clue why
(thats obviously not all my code)
nvm i fixed it a different part of the code was interfering with it
Fyi this feature is already builtin to discord as automod
i know but discord automod sucks in my opinion
its easily bypassable
You're saying that like yours isnt
i already said it isnt my full code + i obviously removed blacklisted_words so i dont have a bunch of slurs in chat
You aren't making sure its a whole word, checking for replacement letters, or blocking the user from sending the message at all
it already detects that, i just add a bunch of stuff to blacklisted_words and the message gets deleted
alr
plus this isnt gonna be a public discord bot im just making it cause yea
Hello!
I'm a beginner of coding bot
I hope i can find someone can help me create a discord bot together ^^
The bot i want make a about a game call "Splatoon" from Nintendo switch(just hope but not really needed)
what about if someone adds whitespaces between each letter? Uses unicode characters that resemble other characters?
tough luck ig
thats why you dont rely on bots
you just said automod sucks 💀
it does
exactly, manual moderation is quite essential for this, your system is just as foolproof as discord's builtin regex automod (except that one will actually prevent the message from being sent in the first place)
doesnt discord automod have limits though?
wdym limits
@slate swan here's a couple of blacklist filters I made https://github.com/Exenifix/AIAS/blob/master/utils/filters/blacklist.py
how can i get the owners name on_guild_join
Is it possible to use custom_id and url in buttons with discord.py v2?
Can anyone help me, I have 2 issues. 1: Is it possible to remove the bot from "replying" to a slash command so that it just sends a message after I use and command. And 2: How do I correctly mention everyone, I have tried to just @ everyone but it doesn't actually ping.
well for the 1st issue you can just do py await interaction.channel.send("message")
Thank you that worked, but do you know how I can give a blank response to this?
hold up im trying to see
await interaction.response.send_message(".", delete_after=1)```
idk if that would work
but try
cool
It would probably work, but like it isn't the most aesthetic way imo, anyway thanks for your effort! Any idea on the second problem?
let me see your code
so you cant at everyone on your bot
Is this enough?
yeah
I do have the permission for the bot to at everyone
ok 1 sec
I found this
Why do you need your bot to mention everyone...
For an announcement
it worked for me
But did it ping you?
ye
Anyway I fixed it thank you guys
oh ok
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/discord-bot/events/la_lfg.py", line 135, in callback
group_chat_button = GroupChatButton(thread)
File "/home/discord-bot/events/la_lfg.py", line 70, in __init__
super().__init__(style=discord.ButtonStyle.green, label="Group Chat", custom_id="group_chat", url = thread.jump_url)
File "/usr/local/lib/python3.10/dist-packages/discord/ui/button.py", line 102, in __init__
raise TypeError('cannot mix both url and custom_id with Button')
TypeError: cannot mix both url and custom_id with Button
Is there a way to get the button to work with a custom id and url? I can work around it if not, but it would be nice to know from someone more experience here as google isn't doing me any favours. And don't really want to ruin my code with crap from google.
Why do you want to do this?
custom_id is only really necessary for making components persistent
url buttons don't have any functionality in that sense so they don't need a custom_id
Because im replacing an a LFG bot so copying some of its functionality as well as improving on it, as you can see the 1st message is a hidden only to user which is where you doing all the selections for the raid, and can then create the raid, from here its posts a public embedded thread, but the hidden messages updates with a messgae saying this raid group has been created etc with a button that links directly to the newly created thread, as this is going to be for multiple different groups, I assumed it would need to be persistent
The screenshot isn't my bot, this is the bot I'm going to replace with my own bot eventually.
Ah yeah url buttons don't need to be persistent since they don't do anything on the bots side, it's all client side
normal buttons need to be persistent so the bot can handle it or whatever but url buttons don't
@client.tree.command(name="google", description="go to google")
async def google(interaction: discord.Interaction):
button = Button(label="google", url="https//:google.com")
view = View()
view.add_item(button)
await interaction.response.send_message(view=view)```
that is how to do a link
Cheers dude, muchly appreciated. This helps a ton actually. 🙂
Great, np
I started using cogs and my bot does run and the command works but it gives an error that the command doesn't exist. Does anyone know how to fix this?
well then the command doesnt work? make sure that your cog is being loaded. Can you upload the code of your cog so we can take a look
and prob also the part that loads the cogs
!d discord.TextChannel.slowmode_delay
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.
Hey guys is there any way to have a bot up 24/7 for free? Without having to have my computer on the whole time
Please tag me when replying
replit but you'll be wasting their resources so just pay the couple of bucks like everyone else does
the command works tho i'll upload the code
Affordable hosting providers:
• OVH Starting at $3.35/mo for 1 core, 2GB RAM, 20GB SSD
• DigitalOcean Starting at $5/mo for 1 core, 1GB RAM, 25GB SSD
• Linode Starting at $5/mo for 1 core, 1GB RAM, 25GB SSD
• Vultr Starting at $2.50/mo for 1 core, 512MB RAM, 10GB SSD
• AWS Lightsail Starting at $3.50/mo (first month free) for 1 core, 512MB RAM, 20GB SSD
• Time4VPS Starting at €3.99/month for 1 core, 2GB RAM, 20GB SSD
• VIRMACH Full Windows and Linux Desktop VPS starting at $7/mo and $1/mo respectively
• Netcup Starting at €2.62/mo for 1 core, 2GB RAM, 20GB SSD
• GitHub education Free credit and other offers for students
• Microsoft students Free credit for students
• Google Cloud free tier
• Pebblehost Starting at $3.00 1024MB DDR4 ECC, Intel Xeon E5-1630v3 / Intel i7-7700k
make sure that you changed the decorators for the commands to @commands.command
or app_commands
in the cog file im using app_commands
https://pastecode.io/s/0fr0dssa this is the main file
https://pastecode.io/s/qsk3kupj this is the cog file
the part where you load the cog
show that.
oh i see now
the reason your command doesn;t work is because
you don't have a self argument in the methods since it is inside a class
so it should be
async def command(self, ctx...)
oh wait yeah right thanks
and name ctx to interaction since app commands use interactions
yeah i left the whole thing in the cog file thanks
Can I run It on my Google Student account? I mean, is it legal? I have all the things unlocked and for free since its a students account so. If it its legal, can you show me how to set it up?
If Google provides you access to a VPS to run anything with such an account, I doubt it's against the law.
How can I set it up?
Google is your friend