#discord-bots
1 messages · Page 165 of 1
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Changed in version 2.0: Now returns an `Optional[int]`.
The reload slash command isn't showing up?
Did you sync?
Not sure if disnake has the same sync as discord.py
ah yikes looks like they changed it
give me a sec do so some research lol
https://docs.disnake.dev/en/stable/ext/commands/slash_commands.html#slash-commands-start has information on "syncing"
Not sure I can help further, sorry 😦
My disnake knowledge is very limited
is the command defined before or after bot.run(), could you show the full file
and the command doesn't appear in the server whose ID you provided?
did you reload your discord Client?
go to server integrations, your bot, and see if the command is there or not
was your bot invited with application commands scope?
add this to your main function and see: ```py
await bot.create_guild_command(sgi[0], reload)
im new to python can anyone tell me how to fix this
!intents
Using intents in discord.py
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.
ty
it's so common these days i may as well set up a macro for it
add an on_message that scans the TypeError from attachments and autoresponds
Heh
do you know where i should put it?
client = commands.Bot(command_prefix = prefix)
client.remove_command('help')
okay thank you
can someone help?```py
CommandRegistrationError: The alias bg is already an existing command or alias.
oh.
nvm
yeah got it :)
@commands.command()
async def close(self, ctx):
await ctx.message.add_reaction(':white_check_mark:')
print(f'Bot terminated by {ctx.author} at {datetime.datetime.utcnow()}.')
await self.bot.close()
When I call self.bot.close() for the first time after starting my bot up, it seems to immediately log itself back in (I get another logging in using static token... in my console immediately afterwards).
When I call it a second time it seemingly closes the connection to Discord for good and the bot goes offline.
Does anyone know why this is happening?
(Discord.py)
My console:
2022-12-28 04:50:08 INFO discord.client logging in using static token
2022-12-28 04:50:08 INFO discord.client logging in using static token
2022-12-28 04:50:08 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: ccd2000a047aa5fdc9fc91e4a333fda2).
2022-12-28 04:50:08 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: ccd2000a047aa5fdc9fc91e4a333fda2).
Bot terminated by Delliott#2003 at 2022-12-28 04:50:12.370192.
2022-12-28 04:50:12 INFO discord.client logging in using static token
2022-12-28 04:50:12 INFO discord.client logging in using static token
2022-12-28 04:50:13 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: e5d4b6d4d9fb9342ba9e8e797e169251).
2022-12-28 04:50:13 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: e5d4b6d4d9fb9342ba9e8e797e169251).
Bot terminated by Delliott#2003 at 2022-12-28 04:50:17.065597.
Process finished with exit code -1073741819 (0xC0000005)
is anyone willing to help fix me and my friends code
here
nvm we figured it out ty for responding though
read the "error"
"Member is a required argument which is missing"
oh
i am doing <:SE4: 1050808261751869532>
oh
Try enable external emoji permissions for the everyone role if you haven't already, I had a similar issue and that was the fix for me
ohk
im still trying to figured out whre is da missing argument?
already enabled
how you are using the command ?
use Optional
Set a default value for the member parameter
Then I don't know, probably some other permissions-related issue, assuming you doubled-checks all the emojis are formatted properly
try member: discord.Member=None
yup ty loll
can u try without leaving a space in between?
there is no space in between in my code
i added here just to send the message
ah okay
and it was working before?
Does the bot have access to the emojis
Like in the server that emoji is from
also it loops 3-4 times and then stops
yes
strange
should i get the emoji using bot.get_emoji(id) everytime rather than just sending <:SE4: 1050808261751869532> ?
Same thing
get each once and store it
They format it pretty much the same
worth a shot tho
async def add_warning(self, interaction: discord.Interaction, punishment_name: str, warnings_amount: int, punishment_duration: int):
what's the best way to add a description to the arguments (punishment_name, etc.)?
discord/emoji.py lines 137 to 140
def __str__(self) -> str:
if self.animated:
return f'<a:{self.name}:{self.id}>'
return f'<:{self.name}:{self.id}>'```
!d discord.app_comamnds.describe
Depends on what you want to do with it. bot.get_emoji(id) is an object so you can use something like name() on it. <:SE4: 1050808261751869532> is a str and I believe that the emojis methods and attributes don't work on it.
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
yeah that
:(
thanks!
It means that you didn't give an argument to the command when using it.
❌ !whois proplayer (as proplayer is a str).
✅ !whois @proplayer (this will work as @proplayer is a member object. The ID of the member like 116549849849847 should work as well.
yeah i figured
theyre typehinting it to discord.Member so even just the name will work if the member exists
So !whois Infernum would work as Infernum will be considered an object?
Nice
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
Nice, it even works by nicknames
I want to make a dynamic options slash command. The concept is basically to get the options from the database rather than directly setting them within the code like:
@app_commands.command()
@app_commands.choices(choices = [data_fecthed_from_db]
async def foo()
Is there any good method other than autocomplete? not even sure if autocomplete will do it.
why does my discord button say this interaction faied after 3 minutes of being sent
Autocomplete is the only way
Do you respond to it?
Alright, Matser
You may have to check the value of the autocomplete because a user doesn’t have to follow the autocomplete options
wdym?
@app_commands.command()
async def fruits(interaction: discord.Interaction, fruit: str):
await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
@fruits.autocomplete('fruit')
async def fruits_autocomplete(
interaction: discord.Interaction,
current: str,
) -> typing.List[app_commands.Choice[str]]:
fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
return [
app_commands.Choice(name=fruit, value=fruit)
for fruit in fruits if current.lower() in fruit.lower()
]```
`TypeError: unknown parameter: 'fruit'`
the timeout of the view that the buttons are contained in is lesser than 180 seconds
it's frui not friut
What line?
nvm I read it wrong
Well the autocomplete is just a hint for the user. They can still enter whatever they want.
lol
Just in case you didn’t already know
idts they can
Huh then idk
I think I get what you mean
though what's wrong with this?!
@app_commands.command()
async def fruits(interaction: discord.Interaction, fruit: str):
await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
@fruits.autocomplete('fruit')
async def fruits_autocomplete(
interaction: discord.Interaction,
current: str,
) -> typing.List[app_commands.Choice[str]]:
data = []
fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
for fruit in fruits:
data.append(app_commands.Choice(name = fruit, value = fruit))
return data```
same error.
changing a list comp to a simple for loop isn't the error, the autocomplete decorator is the one causing the error
@app_commands.command()
async def fruits(interaction: discord.Interaction, fruit: str):
await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}')
@fruits.autocomplete('fruit')
async def fruits_autocomplete(
interaction: discord.Interaction,
current: str,
) -> typing.List[app_commands.Choice[str]]:
data = []
fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry']
"""for fruit in fruits:
data.append(app_commands.Choice(name = fruit, value = fruit))"""
return data```
same error.
@fruits.autocomplete('fruit') this part
yes I am
you need to add a self in the methods then
just copying the docs examples and expecting it to work isn't gonna work too well every time
worked, thanks!
any1 know if theres a way to have a command to see how many boost we have in server
like a command like that?
!d discord.Guild.premium_subscription_count
The number of “boosts” this guild currently has.
Or Guild.premium_subscribers returns a list of boosting members
Is there anyway to add a description to the choice when using autocomplete and fetching the options from the database?
You need to get the guild object using ctx.guild then getting the total boosts from it: ctx.guild.premium_subscription_count
alrr
you could add it in the autocomplete name itself maybe, there's nowhere else you can do that
I want to add a description not a name
Something like this @app_commands.describe(punishment_name = "The name of the punishment") but inside the autocomplete.
, there's nowhere else you can do that
Ooooooooh!! hold on
@app_commands.command()
async def ban(interaction: discord.Interaction, member: discord.Member):
"""Bans a member
Parameters
-----------
member: discord.Member
the member to ban
"""
await interaction.response.send_message(f'Banned {member}')```
ok and
im thinking of how to use that
ok
Hey I am trying to make a discord bot in replit (since my laptop can't handle it properly)
but all of my codes are not working
can someone help me ?
is chatgpt outdated or something?
what's the error
its says
line #
init() not found
smth like that
show me the code and the error
alright 1 min
here is the error
@sharp pawn my code
try this
in the fourth line, put this instead
bot = commands.Bot(command_prefix='!', intents=intents)
and in the third line
!intents
Using intents in discord.py
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.
intents = discord.Intents.default()
intents.members = True
i put this in the 4th line ?
you can either edit the fourth line or just completely erase it and put the one i provided you
not this
yeah got it
this in the 3rd line
refer to this
I did
[<ActionRow children=[<SelectMenu type=<ComponentType.select: 3> custom_id='somethingunique' placeholder=None min_values=1 max_values=1 options=[<SelectOption label='Light Purple' value='Light Purple' description=None emoji=None default=False>, <SelectOption label='Purple' value='Purple' description=None emoji=None default=False>, <SelectOption label='Dark Purple' value='Dark Purple' description=None emoji=None default=False>] disabled=False channel_types=[]>]>] anyone know how can i get values only from this list?
should i erase the last code?
bot.run()
go to the discord developer page
then ?
nah
;-;
waiting
kk
alr alr
it worked
tyty
no worries man
what type of bot are u planning to make anyway
a fun/mod bot
i see
you should try to
i guess make something thats not already there
maybe an rpg game bot or something
Just get it?
like i wanna store all the value= in another list with different index of each
the list i typed here has only 0 index and saved everything in it
i want the label\values only from the list
Then get it
how
Exact same but from list
i cant just go like var1 = list.value or something
the value will change for every interaction
is there any function or method which will return the value part only?
well i cant understand what you are saying
can you like show my the lines i have to type?
list = [<ActionRow children=[<SelectMenu type=<ComponentType.select: 3> custom_id='somethingunique' placeholder=None min_values=1 max_values=1 options=[<SelectOption label='Light Purple' value='Light Purple' description=None emoji=None default=False>, <SelectOption label='Purple' value='Purple' description=None emoji=None default=False>, <SelectOption label='Dark Purple' value='Dark Purple' description=None emoji=None default=False>] disabled=False channel_types=[]>]>]
imagine this is the list
how will you get the value only into another variable without typing the value by hand?
for loop
yep ik
!e
class Obj:
value = "meow"
values = [Obj(), Obj()]
for item in values:
print(item.value)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | meow
002 | meow
because message is not a Message anylonger, you made it an integer
anybody have idea on which lanuage dank memer bot was made?
Nice
Hey, so I'm tying to create a dropdown menu. When I click it, nothin happens. How can I fix that? ```python
class MyView(discord.ui.View):
def init(self):
super().init(timeout=None)
@discord.ui.select(
placeholder="Suche eine Option aus",
custom_id="dropdown",
options=[
discord.SelectOption(label="Ticket öffnen", description="Öffne ein neues Ticket!")
]
)
async def select_callback(self, interaction: discord.Interaction):
if self.values[0] == "Ticket öffnen":
guild = interaction.guild
username = interaction.user.name
user = username.lower()
channel_name = f"ticket-{user}"
existing_channel = discord.utils.get(guild.channels, name=channel_name)
if existing_channel:
await interaction.response.send_message(f"Sie haben bereits ein Ticket.",
ephemeral=True)
else:
await guild.create_text_channel(channel_name)
for channel in guild.channels:
if channel.name == f"{channel_name}":
channel_id = channel.id
new_channel = guild.get_channel(channel_id)
await new_channel.edit(topic=f"Ticket von {interaction.user}")
await new_channel.set_permissions(interaction.user, read_messages=True, send_messages=True)
await new_channel.set_permissions(guild.default_role, read_messages=False,
send_messages=False)
await new_channel.set_permissions(interaction.guild.get_role(team), read_messages=True,
send_messages=True)
embed = discord.Embed(color=discord.Color.blurple(), title=f"Ticket von {interaction.user.name}",
description="Dein Ticket wurde erfolgreich erstellt. "
"Ein Teammitglied kümmert sich so "
"schnell wie möglich um dich. "
"In der Zeit, beschreibe dein Anliegen so "
"genau wie möglich!")
await interaction.response.send_message(f"Ihr Ticket wurde unter dem Namen <#{channel_id}> erstellt.",
ephemeral=True)
await new_channel.send("@oblique needle", embed=embed)```
Click what
the option in the dropdown
You should get an error then
or "Interaction Failed"
Your dropdown callback needs an argument that represents the dropdown
I have this and when I click the option this error comes: 2022-12-28 12:57:07 ERROR discord.ui.view Ignoring exception in view <MyView timeout=None children=1> for item <Select placeholder='Suche eine Option aus' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Ticket öffnen' value='Ticket öffnen' description='Öffne ein neues Ticket!' emoji=None default=False>]> Traceback (most recent call last): File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 425, in _scheduled_task await item.callback(interaction) File "C:\Users\Documents\coding\discord\ticket_bot.py", line 134, in select_callback if self.values[0] == "Ticket öffnen": AttributeError: 'MyView' object has no attribute 'values'
That's how Python classes work 
how I do that? I'm new to python and coding
Add an argument to the callback
Like select: ui.Select
Then get the value from that argument
async def select_callback(self, interaction: discord.Interaction, select: discord.ui.Select):
if select.values[0] == "":
...
ok, thank you very much
one more question, how can I make, that you can use the dropdown unlimited times?
I set the timeout to None and set an custom_id but it doesn't work
You already can do that 🤷
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
Can someone tell me how do i add status in my bot ?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def greet(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def add(ctx, a: int, b: int):
await ctx.send(a+b)
@bot.command()
async def multiply(ctx, a: int, b: int):
await ctx.send(a*b)
@bot.command()
async def greetings(ctx):
await ctx.send(f"Greetings {ctx.author.mention}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def bye(ctx):
await ctx.send(f"Bye {ctx.author.mention}")
bot.run('token')
btw I want to convert my bot comands to "/" so that whenever anyone type "/" it shows my bot commands. How can i do it? (also an excuse the remove the author mention ;-;
i did not put my bot token here for safety
I also want to log everything that happens
like interactions with bot ;-;
@sharp pawn my man please help me
hey man what's up
ah
got you man, just give me a second I'm almost done w my assignment
thank you man. I really appreciate your help.
please forgive me if I am being annoying to you ;c
not at all dude
its really fine
what kind of status do you want?
a status like "hello im (bot)" or similar?
doesn't really matter u can edit the text
nah Like playing games (custom)
or doing (custom)
like this
@sharp pawn ;-;
alright man i got you
:D can you also teach me how to convert my commands into "/" so that wheneevr someone types "/" in chat my bot pops up :D
@bot.event
async def on_ready():
activity = discord.Game(name="you can edit this to whatever you like", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
#here, you can change the status of the bot
print("the bot is ready")
can you tell me at which line I should put it ?
you can look here :D
:o oke oke
also
replace the fifth line w this,
bot = commands.Bot(command_prefix='/', intents=intents, activity=activity, status=discord.Status.idle
:o oke
the fifth line contains the command prefix :o
lmk if it works
kk
it shows syntax error
what's the error
where does the bracket close?
mu bad
replace the fifth line w this,
bot = commands.Bot(command_prefix='/', intents=intents, activity=activity, status=discord.Status.idle)
D:
alrighty
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents, activity=activity, status=discord.Status.idle)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def greet(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def add(ctx, a: int, b: int):
await ctx.send(a+b)
@bot.command()
async def multiply(ctx, a: int, b: int):
await ctx.send(a*b)
@bot.command()
async def greetings(ctx):
await ctx.send(f"Greetings {ctx.author.mention}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def bye(ctx):
await ctx.send(f"Bye {ctx.author.mention}")
bot.run('token')
im probably doing something wrong i just need a check
sure mate no problem :D
ping me u r done :o
you need to define the activity variable before using it
can you help me on that ?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
activity = discord.Game(name="you can edit this to whatever you like", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
#here, you can change the status of the bot
print("the bot is ready")
@bot.command()
async def greet(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def add(ctx, a: int, b: int):
await ctx.send(a+b)
@bot.command()
async def multiply(ctx, a: int, b: int):
await ctx.send(a*b)
@bot.command()
async def greetings(ctx):
await ctx.send(f"Greetings {ctx.author.mention}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def bye(ctx):
await ctx.send(f"Bye {ctx.author.mention}")
bot.run('token')
try this
:O i was bout to ping you
wait
tysm
can you help me with something ?
i am very sorry but can you help me remove {ctx.author.mention}?
since i have to ping my bot after running every command ;-;
did it work?
yesh brother :D
wdym?
how do i remove the ctx.author.mention
backspace :<
ah
it shows error if i do it
@bot.command()
async def greet(ctx):
await ctx.send("hello!")
i can send a ss
don't change(/suggest changing) your client's presence in an on_ready event
https://www.pythondiscord.com/pages/guides/python-guides/setting-different-statuses-on-your-bot/
How to personalize your Discord bot status
i remove the f ?
yes yes
:o let me try
it doesn't really matter tho
😔b-but f strings make your code cool
shit doesn work D:
just stop using strings
show me the code 🙏
Hey can someone help me with something
alrighty
sending the code
no
yes, use binaries and create string using a map
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
activity = discord.Game(name="Minecraft", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
#here, you can change the status of the bot
print("the bot is gaming!")
@bot.command()
async def greet(ctx):
await ctx.send("Hello")
@bot.command()
async def add(ctx, a: int, b: int):
await ctx.send(a+b)
@bot.command()
async def multiply(ctx, a: int, b: int):
await ctx.send(a*b)
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}")
@bot.command()
async def bye(ctx):
await ctx.send(f"Bye {ctx.author.mention}")
bot.run('token')
just don't use strings
I can give you an evolution stone :3
lmao
I'm fine, what's the issue
anything after client.run won't work since it creates an endless loop
@sharp pawn brothr here is my code ;o
Its just that i wanna make a dscord bot that can have an api that sends a request to my website
unfair behaviour towards the most convenient data type in python
use aiohttp
don't use python 😔
above client.run
Is that sum Library?
yeah no that's all i know when it comes to programing languages
yep yep
it's the same library that discord.py uses internally
!pip aiohttp
!pip httpx bite me
extra dependency, but better for simple api reqs
the command should work just fine
what's the error tho
it doesnt respond until i mention the bot
Im actually more familiar with pycord
pycord isn't even related to discord bots
uh....yeah?
pycord is discord.py under the shadows, it used the same
Yep
you just have to say /greet and the bot should respond with hello
pycord-v3 wants to know yr location
ok
i did
it doesnt respond until i type
/greet @high isle Devil
🗿
above client.run
ur using replit right? try reloading the website
alright
trust me buddy
use other platform such as railway
dont use replit
and why are there 2 client.run 🤣
double client run??
@sharp pawn doesnt work D:
💀 nah nah
i provided you the most general hello code
:o
maybe try replacing the " with '
so u r 16 now gg, go to your bot's profile and add tags as per it's category on the portal
what is he trying to do in def main
i did this
yes i am 16 now ;-; i waited for 10 months
kk
😂
need to leave a line space between time.sleep and client token
should start from a new line
its weird
i dont have choice
i give up making discord bot ;c
i typed game and no window show up
your bot will never start, while True is blocking
oo it works now
tags aren't fixed, you can make ur own
i see
you shouldn't. the code is perfectly fine actually maybe just
switch to a new ide
what is this guy trying to do
im so confused
i am saving the code
now i really wanna make a discord bot
but I am changing the from replit
again
to something better
save the code into ur pc
we all should make discord bot together fr
make a repo
and push it to some hosting server other than replit 💀
fr
which serevr should i host ?
i recommend railway.app
hey man switch to Sublime text or vsc
heroku
i use railway.app and vsc
heroku is cringe now
vsc I'll suggest
and if ur gonna use replit then you can go along w uptime robot
rate limits
teach me
send me a vid if u can
heroku now needs a credit card, might switch to oracle at this point
i recommend you to code with vcs first and then shift the code to replit once ur done, then u can make ur code online 24/7 with the help of uptime robot
that's the most general way
damn didn't know that
i dont recommend replit cuz it will get u rate limited very frequently
its been a while since I've coded
shits so buggy dude
oracle also need one if my memory serves
might also want to read this
#965291480992321536 message
ude?
exactly what i wanna say, if you're using a credit card why not use it on oracle lol
same can't get a cc until i have a job
lol
is railway that good
railway.app also support database
i never really used it so i wouldn't know
like really database instead of json 💀
railway is decent, supports heroku builds docker and what not
anyways
im planning to make an adventure rpg discord bot but it's too time consuming
the quest, missions, item crafting and shit
im making one
ong?
rpminecraft
its in my bio check it out if u want definitely not advertising
nah not minecraft
like a pure rpg game on discord
with a couple of starting character you can choose
oo u mean mmo
open source? 🤔
with different powers, ability and attacks
yup
send link
alright let me explain
its cool but again it's gonna drain me out
send me a vid on how to use it
rpminecraft(public) = replit
rpminecraft beta(private) = railway.app
vsc isn't that difficult
because i started the whole thing in replit
so im making a clone version of it without destroying it
just download it and open a workspace
i am dumb ;-;
youtube how to download visual studio code
wai u talkin abot visual studio code?
yes ofc
im not sure how to give replit's source but maybe this
https://replit.com/@JUANHAN/RPMinecraft#main.py
alright the code updated every sunday part is a lie
so you just don't have an option to make the source close lmao
;-;
i will make the release version open source
but the beta version will be close source
what's wrong
u have if u on hacker plan
but they know i dont have cc
i wouldn't use replit tbh
even with cc hacker plan is paid
student dev got like 6 months free
json 💀
now it makes me feel like hanging myself
terraforming json to sql
ik but he's not using it
now i know why sarth and the bois tell me to switch long time ago
well hopefully u jump to asyncpg directly and don't pit stop on sqlite
any idea how can i print the value of name number level and the percentage of this embedm
@calm jacinth try using this code
well ez way split at special charcter complicated way use regex match groups then
formatted string ig?
using postgres
the downside of railway.app is it only works for 21 days a month so basically now im waiting for 1 jan 2023
people celebrate 1 jan for new year
i celebrate it for my bot
🥹
???
`import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
activity = discord.Game(name="Minecraft", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
print("The bot is now online and ready to accept commands!")
Create a dictionary of greetings with personalized responses
greetings = {
"hello": "Hello, how are you?",
"hi": "Hi there! How's it going?",
"hey": "Hey, how's it going?",
"greetings": "Greetings! How are you today?",
}
@bot.command()
async def greet(ctx, greeting):
if greeting.lower() in greetings:
# If it is, send the corresponding response
await ctx.send(greetings[greeting.lower()])
else:
# If it's not, send a default response
await ctx.send("Hello there!")
@bot.command()
async def add(ctx, a: int, b: int):
result = a + b
await ctx.send(f"The result of adding {a} and {b} is {result}")
@bot.command()
async def multiply(ctx, a: int, b: int):
result = a * b
await ctx.send(f"The result of multiplying {a} and {b} is {result}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}! It's nice to see you.")
@bot.command()
async def bye(ctx):
await ctx.send(f"Goodbye {ctx.author.mention}! I hope you have a great day.")
bot.run('token')`
make sure to replace token with ur bot token
what do u use to host your bot ?
railway.app
origin did the code work for you
u need to make a repo in github and link it to there
who is origin :o
please teach me
let me send u the tutorial
that's a tough one
;-; sorry
testing
lmk if any error occurs
kk
- install visual studio code
- migrate ur code from replit to visual studio code
- create a github account
- follow this tutorial -> https://www.youtube.com/watch?v=iv8rSLsi1xo|
- link ur repo here -> https://railway.app
take one step at a time dont rush
its not gonna end up well if u rush
visual studio code makes a lot of prob for mc
minecraft???
*me, i guess
me*
oo
@sharp pawn the bot still doesnt reply ;c
anyway ty for help
whats the problem
damn
about vsc
the bot really trippin fr
mind showing the whole thing?
like copy paste it here
!paste
Pasting large amounts of code
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.
the code ?
of course 💀
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
activity = discord.Game(name="Minecraft", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
print("The bot is now online and ready to accept commands!")
# Create a dictionary of greetings with personalized responses
greetings = {
"hello": "Hello, how are you?",
"hi": "Hi there! How's it going?",
"hey": "Hey, how's it going?",
"greetings": "Greetings! How are you today?",
}
@bot.command()
async def greet(ctx, greeting):
if greeting.lower() in greetings:
# If it is, send the corresponding response
await ctx.send(greetings[greeting.lower()])
else:
# If it's not, send a default response
await ctx.send("Hello there!")
@bot.command()
async def add(ctx, a: int, b: int):
result = a + b
await ctx.send(f"The result of adding {a} and {b} is {result}")
@bot.command()
async def multiply(ctx, a: int, b: int):
result = a * b
await ctx.send(f"The result of multiplying {a} and {b} is {result}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}! It's nice to see you.")
@bot.command()
async def bye(ctx):
await ctx.send(f"Goodbye {ctx.author.mention}! I hope you have a great day.")
bot.run(')
@sharp pawn made this for me
lemme find the errors
await bot.change_presence(status=discord.Status.online, activity=activity)
```why this 💀
its already that by default
:o wot
do u get any errors tho
no errors
just in case if he wants to change the status from online to idle or dnd
but the bot no reply
lmao i see
do u try all of the command?
or u only try greet
im giving the revised code gimme a sec
all
none of it works?
nopee
no errors but bot no respond when i type /bye or /greetings
intents = discord.Intents.default()
intents.members = True
prefixxx = ['rpm ', 'Rpm ', 'RPM ', 'RPm ']
bot = commands.Bot(command_prefix = prefixxx, case_insensitive=True, activity=discord.Game(name="rpm start"),intents=intents)
```alright this is mine
i recommend u to add the case_insensitive part
NOICE
ignore the prefixxx alright?
✨ moment of enlightenment ✨
pretend u never see that
alright but what bot u makin ?
`import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='/', intents=intents)
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.online)
print("the bot is now online and ready to accept commands.")
greetings = {
"hello": "Hello, how are you?",
"hi": "Hi there! How's it going?",
"hey": "Hey, how's it going?",
"greetings": "Greetings! How are you today?",
}
@bot.command()
async def greet(ctx, greeting: str):
if greeting.lower() in greetings:
#if it is, just in case, send the corresponding response
await ctx.send(greetings[greeting.lower()])
else:
# and if it's not, send a default response
await ctx.send("hello there")
@bot.command()
async def add(ctx, a: int, b: int):
result = a + b
await ctx.send(f"The result of adding {a} and {b} is {result}")
@bot.command()
async def multiply(ctx, a: int, b: int):
result = a * b
await ctx.send(f"The result of multiplying {a} and {b} is {result}")
@bot.command()
async def hello(ctx):
await ctx.send(f"Hello {ctx.author.mention}! It's nice to see you.")
@bot.command()
async def bye(ctx):
await ctx.send(f"Goodbye {ctx.author.mention}! I hope you have a great day.")
bot.run('ur token goes here')`
rpm
this should work
how to identify special string?
what dat ??
nvm im out
ancestry try the above code
lets try
wait you dont know what rpm is? its just a small discord rpg minecraft bot that im currently working on and it has reached 100 servers in first week of release
wdym identify a special string
sarth got brain damage
:o noice
how do u release bots ;-;
the server link is in my bio just saying definitely not advertising
wouldn't be the first time
i meant special character
like how to split?
i submit it to top.gg and it got approved
copy the character then use the split method
honestly yeah 💀 why don't people read until they are being spoonfeeded
@sharp pawn bot only replies when pinged
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
message content intent be like 
u need to switch to a new ide fr man
loooli u both need to get some python education nothing wrong with ide
i mean ¯_(ツ)_/¯
lo..LI???
then it should work right?
but u cant learn well without a good ide ig?
its like studying inside a warzone it works but not effective
i started on repl and python idle 
i mean me too
but if u let me choose again i will start with vsc
max level skill is writing in notepad
@shrewd apex you have local pgsql server or use a remote host?
In this video, I tell you the best IDE to use for programming. No matter what kind of programming you do.
Music by Joy Ngiaw:
https://www.joyngiaw.com/
https://www.instagram.com/joyngiaw/
HOW CAN YOU SUPPORT ME?
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
Have a video idea? Suggest it here: https://joma.tech/help
HOW DO I GET A TECH JOB?
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀...
@shrewd apex
🤣
got local but remote works too no host tho
y? tho
imagine a newcomer watched this and thought it was real
let me present to u railway.app
gonna start rewriting anya, need a pgsql server
500 hrs limit
mf i am gonna kill u
lemme introduce you too credits limit hit already
just look at this
finish lore first
paused from exceeding limits
dw I'll do it after lore only
anya?
wdym dw its been a year now 😭
his discord bot gf
a discord bot i started but never completed
bitch she's 6
and thats y ur pedo
thats not what i mean when i say i love kids
u got 6 year old pfp every alternate months hima, anya few others who idk
he's tripping a girl rejected him yesterday cuz of his pokemon fantasies
kek sarth on revenge mode 
umaru and chidori
idk
getting rejected is better than getting dumped
👀

@sharp pawn is dis a good about me for my bot ?
!d json.dump life of an average "i learned from YouTube" discord bot developer
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).
If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.
If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
who even looks at about me
me
someone people does
hmm fair enough
👀
alr i dumped json for sql
atleast you didn't use txts
so ye
i only txt i use is requirements.txt ¯_(ツ)_/¯
i don't even use it for that 😈
makima sucks
she da villian tbh
(only manga readers know why)
come in dms
so that she can see denji suffer
becuz denji killed gun devil
yeah
come in dms
!ot there's these channels
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
me meanwhile
xD :O
personal preference
idky this exists but
sucky sucky
someone got some nice Command ideas?
i plan to make a study bot
command/functionality ideas
must be able to solve basic and complex arithmetic
must be able to look up definitions of terms
must have a study reminder
let them put notes in and quiz them
yes yes a quiz command
W
reminders, noteits, googling a problem, a special calculator for complex maths
@loud junco @sharp pawn ty for the suggestions 🫡
ill also add some voice levelling features etc
the the last 2 ones can be archived by some simple apis
also, the bot must be able to summarise a large text into a small brief text
💀 this gonna be a bit hard lol
openAI is the only application i can think that does that, and its paid after 18$
👍
doing the reverse would have been easier
oh i never saw an api for complex maths
the first hard part would be how to take user inputs for those operations 💀
there's textblob
hm in that case
they can take a screenshot/picture of the problem and look for the solution
u can try to read the problem from the image
gonna be hard but worth it definitely if you plan on making the bot public
time to kidnap doubtnet developers
maybe, i haven't used it much
make them work for u
she's a devil lol
Where can i find a guide to automatically pull updated code and restart the bot when the repository is updated (merged)?
You're looking for GitHub actions CI/CD pipeline to auto deploy on prod
@feral timber I summon you to send this person the same link you sent me the other day
Kthxbye

plz hold plz thanks
https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions
This one?
It's a bit general
CC @glossy edge
Is there a specific GitHub action I'm supposed to use?
You can see how we do it here -
We have a workflow that builds a Docker container and pushes it to GitHub's registry:https://github.com/python-discord/bot/blob/main/.github/workflows/build.yml
And then all our deploy action has to do is login and give the server the new version:https://github.com/python-discord/bot/blob/main/.github/workflows/deploy.yml
We do have Kubernetes so that handles the replacing the container for us
If it makes you feel any better I gave up on this
Not really, it depends on what you're using on your server
i.e., if you have K8s you should use the K8s action, Docker for Docker, SSH? for bare metal as a last resort, etc, etc
They're all valid strategies, so it just depends on how you want to setup your server
One sec
@glossy edge you probably need this https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Oh I see, I'm not using any Kubernetes, I run the bot through a tmux pane. Thanks for the info.
I will look into this also, thank you very much.
I should really take a look at these sometime
Though I do think the self-hosted runner is a bit much
@sick birch - What do you think birdo? Could this work for you?
I do dockerize my bots usually.
Pretty sure I even reviewed that PR for the page Exenifix linked, haha
Containerizing isn't the issue for me it's the auto deployment
What have you tried?
Nothing really
Just daunting
I think I'm gonna go with the option you mentioned the other day of pushing to ghcr
Deploy from there
Yeah that's my guide
That's what I do BTW
I still manually pull and restart the container when I want to
I want to add a webhook that kicks off a docker pull and restarts the container if the image changes
Then all GHA has to do is hit that webhook. Literally just a single web request
Sure, I'm assuming you're talking about the if guard
can someone help me in game development channel?
do you maybe know why my code is not working?
idk the sollution
!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").
!blocking , while True loops are blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
just using await doesnt mean your became async
Is it legal to make a discord bot using chat gpt ?
i'm pretty sure it is
I never had this error. Please help me
I'm pretty sure you have to send some message content along with the view
Oh wait your view isn't a view
It's a modal
There should be a send_modal method on interaction
Call that
So I've been making that my bot auto delete any links sent in the server so I made a link that ends with .com or starts with http but some links like discord . gg etc doesn't contain any of them so what can I do
You can recognise invites with regex discord\.(?:gg|com/invite)/[\w\d]+
Hmmm what do you mean?
Yk about regex?
Uhh no
!regex
Regular expressions
Regular expressions (regex) are a tool for finding patterns in strings. The standard library's re module defines functions for using regex patterns.
Example
We can use regex to pull out all the numbers in a sentence:
>>> import re
>>> text = "On Oct 18 1963 a cat was launched aboard rocket #47"
>>> regex_pattern = r"[0-9]{1,3}" # Matches 1-3 digits
>>> re.findall(regex_pattern, text)
['18', '196', '3', '47'] # Notice the year is cut off
See Also
• The re docs - for functions that use regex
• regex101.com - an interactive site for testing your regular expression
Hmm what's that lmao
For links uncomplicated one would be https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@])*
Just made it myself hopefully this is right
.bm
Click the button to be sent your very own bookmark to [this message](#discord-bots message).
@ember nest as said in embed it's tool for finding patterns in strings
So if you want to search for all links you just do
LINKS_PATTERN = re.compile(r"https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@])*")
links = re.findall(LINKS_PATTERN, message.content)```
Like lemme demonstrate
So like it check if message have more than 1 of the strings that in https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@])* and if it's true it should delete the message?
!e ```py
import re
LINKS_PATTERN = re.compile(r"https?://[-\w]+.\w{2,4}(?:/[-\w%&?=#@]+)*")
content = "Hello please follow https://google.com then https://pythondiscord.com/pages/guides"
links = re.findall(LINKS_PATTERN, content)
print(links)```
That's wrong regex sorry
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
['https://google.com', 'https://pythondiscord.com/pages/guides']
Ok now it's right
Forgot the +
@ember nest you don't really need to worry about pattern if you aren't familiar with regex, it's a pretty complicated thing although very useful and should be learned, however for now you can use provided patterns
discord\.(?:gg|com/invite)/[\w\d]+ for discord invites
https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)* for links
its not that complicated
Subjective
its just a lot to learn
and will seem overwhelming at the beginning
but you'll get the hang of it easily
What is contect for
You check what? Messages content
So now after that
How to make the bot check if the message had that to delete on on_message
Sorry, I am not a spoonfeeder. You have got 2 patterns and you receive message content in on_message, can be accessed via message.content attribute
You use re.findall function for getting all substrings matching pattern in given string
But I mean like that if someone just sending message any message(and any of this pattern things in the message) his message will be deleted as well
Idk what else to explain without sending the full code
Explaining with the code is better tbh I always understand like that
I am trying to imagine how that would be in my head but I can't get it
Explaining with code != spoonfeeding (giving the full ready working code)
Unless I want to learn not just copy - paste
If someone sends a message with no links, re.findall() will return an empty list
And you can handle situations if there is a link or if there's no link by checking length of returned list
Hmmm
And can I make another pattern with discord links and add that new variable to the re.findall ?
!e ```py
import re
LINKS_PATTERN = re.compile(r"https?://[-\w]+.\w{2,4}(?:/[-\w%&?=#@]+)*")
def has_links(txt: str) -> bool:
return len(re.findall(LINKS_PATTERN, txt)) > 0
text_with_links = "Hello please follow https://google.com then https://pythondiscord.com/pages/guides"
text_with_no_links = "Hello my name is Joe"
print(has_links(text_with_links))
print(has_links(text_with_no_links))```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | False
Such as that
LINKS_PATTERN = re.compile(r"https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*")
LINKS_PATTERN2 = ("discord\.(?:gg|com/invite)/[\w\d]+")
content = "Hello please follow https://google.com then https://pythondiscord.com/pages/guides"
links = re.findall(LINKS_PATTERN, LINKS_PATTERN2, content)
This would be okay as well?
You gotta do findall separately for each pattern
Or you can merge patterns (that's not what I'd recommend to do)
Yeah
Nah that would be a mess tbh
First check for links then for invites
2nd pattern should be compiled as well
LINKS_PATTERN = re.compile(r"https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*")
content = "Hello please follow https://google.com then https://pythondiscord.com/pages/guides"
links = re.findall(LINKS_PATTERN, content)
LINKS_PATTERN2 = re.compile("discord\.(?:gg|com/invite)/[\w\d]+")
links2 = re.findall(LINKS_PATTERN2, content)
Like that ? @vale wing
LINKS_PATTERN2 = re.compile(r"discord\.(?:gg|com/invite)/[\w\d]+")```
Forgot the `r`
The rest is ok
Alright
Now the compile and findall is done
So now how to make the bot search if it's link to delete messages and if nots not link to ignore it
Listen for on_message and apply that thing to message.content, then check for amount of links/invites ig
So someone like ```py
@bot.event
async def on_message(message):
LINKS_PATTERN = re.compile(r"https?://[-\w]+.\w{2,4}(?:/[-\w%&?=#@]+)*")
content = "Hello please follow https://google.com then https://pythondiscord.com/pages/guides"
links = re.findall(LINKS_PATTERN, content)
LINKS_PATTERN2 = re.compile(r"discord\.(?:gg|com/invite)/[\w\d]+")
links2 = re.findall(LINKS_PATTERN2, content)
if message.content in links or message.content in links2:
await message.delete()
Something like that?
@vale wing
- Use
@bot.listen()instead of@bot.eventfor reasons if you'd like me I can tell - Why are you checking hardcoded content? You're supposed to check
message.content - Incorrect condition, you should be checking
len()of yourlinksandlinks2
With?
Wdym about 2.
You need to check content of received message right? Not of the thing you made up that is same on every message
Elaborate, does it give any error?
What's expected behaviour and what's actual
So how can I do that
I read that a lot but I can't understand bruh
!code ?
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Well what's your python knowledge level? OOP or lower
thank you
for loops
Kinda middle range
Happens
I've been learning discord.py for around 1 month
But like I don't understand what you mean
I learned python for like 3-4 months before
Time doesn't matter but the knowledge you got does
Yeah it's kinda cool
But I don't understand what you meant like sorry my English is not that good tbh lol
So do you know classes and objects
Yeah
I didn't get in classes much though
I focused more on the more used things
Since I am just learning alone for fun without any courses
In on_message you receive a message object, you can access attributes of messages via it. The attribute you need to check is message.content. It is a string with message content. Then you need to use re.findall on the message.content to find links the content contains
import discord
client = discord.Client(intents=discord.Intents.default(), command_prefix="!")
@client.event
async def on_ready():
print("Bot is ready.")
@client.event
async def on_message(message):
print(message.content)
client.run("TOKEN")
The print message.content doesn't works
So like that ```py
@bot.event
async def on_message(message):
LINKS_PATTERN = re.compile(r"https?://[-\w]+.\w{2,4}(?:/[-\w%&?=#@]+)*")
content = "Hello please follow https://google.com then https://pythondiscord.com/pages/guides"
links = re.findall(LINKS_PATTERN, content)
LINKS_PATTERN2 = re.compile(r"discord\.(?:gg|com/invite)/[\w\d]+")
links2 = re.findall(LINKS_PATTERN2, content)
if len(links) or len(links2) in message.content:
await message.delete()
Like this?
message_content intent required
.
👀 what's that
I am a beginer I began to code my bot this afternoon
The tutorial you found is bad
@vale wing
ok...
In docs there's an actual tutorial iirc
funfact: most are
Dude am I right? @vale wing
99% of video tutorials are
For video tutorial to be good it requires the "teacher" to be good at coding (impossible) and be recent
....
Alright so is my code correct?
No you're still checking content and it will always be the same, it's not message.content
You don't need that content at all, it was for example purpose
So just do in message?
Like that
if len(links) or len(links2) in message:
await message.delete()
Tell me what does len() return in your opinion
A list
Negative
It returns amount of items in a sequence, i.e. length
You need to check if it's more than 0
So
This is becoming spoonfeeding fr
I am kinda confused now idk how to do yhat
Ok let it be ig
Forgive me for being a spoonfeeder but I am tired fr
@ember nest please look at the correct version of code, I really hope you won't just copypaste but will figure it out
LINKS_PATTERN = re.compile(r"https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*")
INVITES_PATTERN = re.compile(r"discord\.(?:gg|com/invite)/[\w\d]+") # constants are not defined inside functions
@bot.listen()
async def on_message(message):
links = re.findall(LINKS_PATTERN, message.content)
invites = re.findall(INVITES_PATTERN, message.content)
if len(links) > 0:
# found at least 1 link
...
return
if len(invites) > 0:
# found at least 1 invite
...```
So ```py
if len(links) > 0:
await message.delete()
return
Where can I find people to test updates to my discord game? It needs at least 2 players but I feel like it might not be fit to ask here. What do you think?
Yes
Asking someone to help with testing something is totally fine here
K, cool. I just finished rewriting so I want to test it
its a game, rounds are 10-15 mins
So I have other level system codes on on_message function as well so making it @bot.listen() instead of @bot.event won't effect them ? @vale wing
You only need to remove bot.process_commands is it's there
And the cool thing about .listen is that you can run several functions for one event at the same time
@bot.event
async def on_message(...):
long_thing1()
long_thing2()
Can be turned into this
@bot.listen("on_message")
async def func1(...):
long_thing1()
@bot.listen("on_message")
async def func2(...)
long_thing2```
Yes
What was the command that to check if member has permission attach_files etc
I forgot it and can't remember
Is there anything like Member.has_permission?
!d discord.Member.guild_permissions.attach_files
No documentation found for the requested symbol.
Hm
Well it won't find it but discord.Member.guild_permissions returns a Permissions object
and you could do
!d discord.Permissions.attach_files
Returns True if a user can send files in their messages.
So I can just do
user = mesage.author.guild_permissions.attach_files
@glad cradle
if you're inside a guild yes
what do I do here?
code listed below:
bot = abot()
what version should I be on? I followed two pages of stack overflow, and one said to update to 2.0.0. I did that then I hit another error which told me to update to 1.7.3
2.0 is the latest stable major so you'd want to be on that version
!intents
Using intents in discord.py
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.
Is how you fix your current issue @ivory shadow 
oh okay thank you
tysm
is 2.1 stable?
Yes
Robin is just very old so he gets it wrong sometimes.
@sick birch I think I know what the error is, even after I added that bit I got the same error. I think this is because I don't have privledged intents (my bot is verified). So, I think that's why it keeps giving me an intents error
Agh I just lose track of all but major releases at this point
If you're not verified you'll have to request discord for message content intents which they (probably) won't grant unfortunately
Are you using prefix commands or application commands?
its been a long day ;(
yeah i’m pretty sure i got declined like last year
Get some sleep, you earned it.
prefix commands but i’m trying to switch to application commands right now
Yup that's about your only course of action
You basically just rewrite everything to use the new slash commands and buttons and whatnot
oh
It is a royal pain I know
i have like a thousand something lines of code though
yeah 😔
One thing you've got going is most of the actual logic for your commands should be a straight copy paste
good point
Hence why we recommend everyone to use slash commands from the start.
oh i started coding before slash commands were made
More than 2 years ago?
wait no
It's probably possible to construct mock context objects and pass interaction via them to keep your code the same but we would not recommend it at all
I was also made before the thing.
!d discord.ext.commands.Context.from_interaction
classmethod await from_interaction(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a context from a [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). This only works on application command based interactions, such as slash commands or context menus.
On slash command based interactions this creates a synthetic [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") that points to an ephemeral message that the command invoker has executed. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the member that invoked the command.
In a message context menu based interaction, the [`Context.message`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.message "discord.ext.commands.Context.message") attribute is the message that the command is being executed on. This means that [`Context.author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") returns the author of the message being targetted. To get the member that invoked the command then [`discord.Interaction.user`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.user "discord.Interaction.user") should be used instead.
New in version 2.0.
15 December 2020
They were only enforced Q2 or 3 of 2021
yeah i didn’t update them in time
Tough to be fair Discord.py only had them at the start of Q1 2021
i took a break for like a year
when was Q1
Late January or smth?
oh okay i created my bot start of april 2021
Robin.
Did I say something wrong
so only option is to like rewrite my entire code
When are you going to sleep? 
Soon 😓
Well.... if you want to do it properly, yes.
This tone made it sound like I said completely wrong haha

hmmmmmm i see i see
It's not as bad as it may seem
Still a pain but logic is still the same
but i don’t have intents in general, so i can still do it without them?
Well you're probably doing something wrong
yeah but how do i do this wihtout intents again
You shouldn't need message content intents for app commands
tbh your bot shouldn't even be 1000+ lines, most of my commands are like at most 10 lines maybe sometimes 15.
i was just messing around so i added like every command possible for fun (back when i started coding)
They've probably just got a lot of commands
wait why did i get the intents error?
i was planning on rewriting everything but then i got hit with that error
You probably used discord.Intents.all()
You prob need to re-invite it since you haven't selected the app commands scope.
i’m pretty sure i didn’t so i don’t think that’s the problem
it has all the permissions
It's a scope not a permission.
It may be one of the other 2 privileged intents you have explicitly enabled
IIRC its members and presences?
oh yeah my bad
i think i got denied for all the intents i requested
i’ll check again
how do i get there again (sorry i haven’t done this in like a year)
Discord developer portal
discord.py's hybrid commands could smooth over the transition too, though not perfectly by itself
I Don't recommend hybrid commands.
where in the portal?
they put a lot of work into those 🥺
They did... but kinda useless.
Url generator.
tbh i havent used them before, only seen what the docs describe
oh you’re correct, i had nothing checked for some reason
That's the default.. lol.
It's a generator.
i’m so dumb 😂
oh yeah that’s what i thought but i wasn’t completely sure
alright so what do i do next
why are they useless tho? even if discord's cracking down on prefix commands, shouldnt they still be helpful for large code bases needing to migrate? i guess it depends on how much their existing commands can cleanly translate
Well you'd still need message intents to make them work.
just the slash part of it can work, again depending on what the original command does
@cloud dawn i selected the scopes and permissions but how do i get the url for these scopes, or is it just the bot id


