#discord-bots

1 messages · Page 165 of 1

hushed galleon
#

!d discord.Guild.member_count

unkempt canyonBOT
#

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]`.
sick birch
#

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

#

Not sure I can help further, sorry 😦
My disnake knowledge is very limited

slate swan
#

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)

high mist
#

im new to python can anyone tell me how to fix this

sick birch
unkempt canyonBOT
#

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.

slate swan
#

!intents you need to provide the ~

#

robin W

high mist
#

ty

sick birch
slate swan
#

add an on_message that scans the TypeError from attachments and autoresponds

sick birch
#

Heh

high mist
#

okay thank you

tropic estuary
#

can someone help?```py
CommandRegistrationError: The alias bg is already an existing command or alias.

#

oh.

#

nvm

#

yeah got it :)

slate swan
#
 @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)
high mist
#

is anyone willing to help fix me and my friends code

steep estuary
#

hey, i have issues with the emojis

#

emojis aren't getting displayed on embeds

high mist
steep estuary
fair shuttle
#

can sm1 help me out

shrewd fjord
#

"Member is a required argument which is missing"

fair shuttle
#

oh

steep estuary
#

why the emojis are not showing up on the next embed?

fair shuttle
steep estuary
#

i am doing <:SE4: 1050808261751869532>

fair shuttle
#

oh

slate swan
fair shuttle
#

im still trying to figured out whre is da missing argument?

steep estuary
fair shuttle
#

yeah

#

other command work

#

but when i do /whois

#

its not working

steep estuary
#

use Optional

slate swan
#

Set a default value for the member parameter

slate swan
# steep estuary already enabled

Then I don't know, probably some other permissions-related issue, assuming you doubled-checks all the emojis are formatted properly

steep estuary
fair shuttle
#

yup ty loll

quick gust
steep estuary
#

i added here just to send the message

quick gust
#

ah okay

quick gust
steep estuary
#

it was not looping

#

but after i fixed the looping now it is not showing the emojis

naive briar
#

Does the bot have access to the emojis

steep estuary
#

yes

#

it is displaying the emojis in the first embed

naive briar
#

Like in the server that emoji is from

steep estuary
#

also it loops 3-4 times and then stops

steep estuary
quick gust
#

strange

steep estuary
#

should i get the emoji using bot.get_emoji(id) everytime rather than just sending <:SE4: 1050808261751869532> ?

quick gust
#

you can try

#

and u dont need to get it everytime

naive briar
#

Same thing

quick gust
#

get each once and store it

naive briar
#

They format it pretty much the same

quick gust
#

worth a shot tho

potent light
#

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.)?

unkempt canyonBOT
#

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}>'```
naive briar
potent light
quick gust
#

typo

#

oh? nvm

quick gust
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@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...
quick gust
#

yeah that

naive briar
#

:(

potent light
#

thanks!

potent light
quick gust
potent light
quick gust
#

sure

#

if u typehint it

potent light
#

Nice

naive briar
unkempt canyonBOT
#

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)...
potent light
#

Nice, it even works by nicknames

potent light
#

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.

slate swan
#

why does my discord button say this interaction faied after 3 minutes of being sent

potent light
torn sail
potent light
#
    @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'`
upbeat otter
potent light
upbeat otter
#

nvm I read it wrong

torn sail
# potent light wdym?

Well the autocomplete is just a hint for the user. They can still enter whatever they want.

potent light
#

lol

torn sail
torn sail
#

Huh then idk

potent light
potent light
#
    @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.
upbeat otter
#

changing a list comp to a simple for loop isn't the error, the autocomplete decorator is the one causing the error

potent light
#
    @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.
potent light
upbeat otter
#

yeah

#

are you inside a cog or smth?

potent light
upbeat otter
# potent light 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

fair shuttle
#

any1 know if theres a way to have a command to see how many boost we have in server

#

like a command like that?

slate swan
unkempt canyonBOT
slate swan
#

Or Guild.premium_subscribers returns a list of boosting members

fair shuttle
#

where do i put that in my command code?

potent light
#

Is there anyway to add a description to the choice when using autocomplete and fetching the options from the database?

potent light
# fair shuttle

You need to get the guild object using ctx.guild then getting the total boosts from it: ctx.guild.premium_subscription_count

fair shuttle
#

alrr

slate swan
potent light
#

Something like this @app_commands.describe(punishment_name = "The name of the punishment") but inside the autocomplete.

slate swan
#

, there's nowhere else you can do that

potent light
#

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}')```
upbeat otter
#

ok and

potent light
#

im thinking of how to use that

upbeat otter
#

ok

potent light
#

ohhh im dumb

#

I was confusing between an argument and a choice

calm jacinth
#

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 ?

sharp pawn
#

is chatgpt outdated or something?

calm jacinth
sharp pawn
#

show me the code and the error

calm jacinth
calm jacinth
sharp pawn
#

ah intents

#

give me a sec

calm jacinth
calm jacinth
sharp pawn
#

try this

#

in the fourth line, put this instead
bot = commands.Bot(command_prefix='!', intents=intents)

#

and in the third line

paper sluice
#

!intents

unkempt canyonBOT
#

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.

sharp pawn
#

intents = discord.Intents.default()
intents.members = True

calm jacinth
sharp pawn
#

you can either edit the fourth line or just completely erase it and put the one i provided you

sharp pawn
calm jacinth
calm jacinth
sharp pawn
#

refer to this

sharp pawn
#

make sure to leave a line

calm jacinth
#

I did

calm jacinth
timid spade
#

[<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?

calm jacinth
sharp pawn
calm jacinth
sharp pawn
#

holdup

calm jacinth
#

;-;

calm jacinth
sharp pawn
#

enable these three from the bot section in developer poryal

calm jacinth
#

kk

sharp pawn
#

alr alr

calm jacinth
sharp pawn
#

no worries man

calm jacinth
#

nvm it works

sharp pawn
#

what type of bot are u planning to make anyway

calm jacinth
sharp pawn
#

i see

#

you should try to

#

i guess make something thats not already there

#

maybe an rpg game bot or something

timid spade
# naive briar 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

naive briar
#

Then get it

timid spade
#

how

naive briar
#

Exact same but from list

timid spade
#

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?

naive briar
#

JUST get it from the list first

#

Do you know how lists works in general

timid spade
#

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?

timid spade
quick gust
#

u use a for loop

#

im hoping u know what that is

timid spade
#

yep ik

naive briar
#

!e

class Obj:
    value = "meow"


values = [Obj(), Obj()]
for item in values:
    print(item.value)

unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | meow
002 | meow
timid spade
#

ok wait

#

thanks

slate swan
#

because message is not a Message anylonger, you made it an integer

steep moon
#

anybody have idea on which lanuage dank memer bot was made?

vocal snow
#

javascript

#

don't make it an integer pithink

maiden fable
#

Nice

autumn helm
#

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)```
naive briar
#

Click what

autumn helm
#

the option in the dropdown

naive briar
#

You should get an error then

vocal snow
#

or "Interaction Failed"

naive briar
#

Your dropdown callback needs an argument that represents the dropdown

autumn helm
#

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'

naive briar
#

That's how Python classes work yert

autumn helm
#

how I do that? I'm new to python and coding

naive briar
#

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] == "":
        ...
autumn helm
#

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

naive briar
#

You already can do that 🤷

naive briar
unkempt canyonBOT
#

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.
calm jacinth
#

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 ;-;

calm jacinth
#

I also want to log everything that happens
like interactions with bot ;-;

#

@sharp pawn my man please help me

sharp pawn
#

hey man what's up

#

ah

#

got you man, just give me a second I'm almost done w my assignment

calm jacinth
sharp pawn
#

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

calm jacinth
#

nah Like playing games (custom)
or doing (custom)

calm jacinth
sharp pawn
#

alright man i got you

calm jacinth
#

:D can you also teach me how to convert my commands into "/" so that wheneevr someone types "/" in chat my bot pops up :D

sharp pawn
calm jacinth
sharp pawn
#

well

#

you should remove your existing bot event and replace it with this one

sharp pawn
#

also

calm jacinth
#

it shows an error

#

its a big error

sharp pawn
#

replace the fifth line w this,

bot = commands.Bot(command_prefix='/', intents=intents, activity=activity, status=discord.Status.idle

calm jacinth
#

:o oke

sharp pawn
#

you can change the idle to dnd

#

its a matter of choice

calm jacinth
sharp pawn
#

lmk if it works

calm jacinth
#

kk

calm jacinth
sharp pawn
#

what's the error

calm jacinth
calm jacinth
sharp pawn
#

mu bad

#

replace the fifth line w this,

bot = commands.Bot(command_prefix='/', intents=intents, activity=activity, status=discord.Status.idle)

sharp pawn
#

wait

#

show me a pic of ur code

calm jacinth
calm jacinth
# sharp pawn wait
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')
sharp pawn
#

im probably doing something wrong i just need a check

calm jacinth
calm jacinth
slate swan
#

you need to define the activity variable before using it

calm jacinth
sharp pawn
#
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

calm jacinth
#

:O i was bout to ping you

sharp pawn
#

wait

calm jacinth
sharp pawn
#

did it work?

calm jacinth
calm jacinth
upbeat otter
sharp pawn
#

ah

calm jacinth
upbeat otter
#

...

#

error.....

sharp pawn
#

@bot.command()
async def greet(ctx):
await ctx.send("hello!")

calm jacinth
slate swan
calm jacinth
sharp pawn
#

yes yes

calm jacinth
#

:o let me try

upbeat otter
#

it doesn't really matter tho

slate swan
#

😔b-but f strings make your code cool

calm jacinth
upbeat otter
sharp pawn
#

show me the code 🙏

jolly karma
#

Hey can someone help me with something

calm jacinth
upbeat otter
slate swan
calm jacinth
# sharp pawn show me the code 🙏
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')
upbeat otter
jolly karma
upbeat otter
#

lmao

#

I'm fine, what's the issue

#

anything after client.run won't work since it creates an endless loop

calm jacinth
jolly karma
slate swan
upbeat otter
#

above client.run

jolly karma
slate swan
upbeat otter
#

!pip aiohttp

unkempt canyonBOT
slate swan
#

!pip httpx bite me

unkempt canyonBOT
slate swan
#

extra dependency, but better for simple api reqs

sharp pawn
#

what's the error tho

calm jacinth
jolly karma
upbeat otter
#

uh....yeah?

slate swan
jolly karma
sharp pawn
slate swan
upbeat otter
#

ok

calm jacinth
#

it doesnt respond until i type
/greet @high isle Devil

jolly karma
upbeat otter
#

above client.run

loud junco
#

what do i do lmao

#

its been one week and its still like this

sharp pawn
#

ur using replit right? try reloading the website

calm jacinth
loud junco
upbeat otter
#

tf no

#

client.run should be at the last

#

all other code above it

loud junco
#

and why are there 2 client.run 🤣

sharp pawn
#

double client run??

calm jacinth
#

@sharp pawn doesnt work D:

loud junco
#

💀 nah nah

sharp pawn
calm jacinth
sharp pawn
#

maybe try replacing the " with '

slate swan
loud junco
#

what is he trying to do in def main

loud junco
calm jacinth
slate swan
#

😂

sharp pawn
#

need to leave a line space between time.sleep and client token

#

should start from a new line

loud junco
#

its weird
i dont have choice

calm jacinth
loud junco
#

i typed game and no window show up

slate swan
#

your bot will never start, while True is blocking

loud junco
#

oo it works now

slate swan
#

tags aren't fixed, you can make ur own

loud junco
#

i see

sharp pawn
#

switch to a new ide

loud junco
#

what is this guy trying to do
im so confused

calm jacinth
slate swan
#

now i really wanna make a discord bot

calm jacinth
#

but I am changing the from replit

slate swan
#

again

calm jacinth
#

to something better

loud junco
sharp pawn
#

we all should make discord bot together fr

loud junco
#

make a repo
and push it to some hosting server other than replit 💀

calm jacinth
calm jacinth
loud junco
#

i recommend railway.app

sharp pawn
#

hey man switch to Sublime text or vsc

sharp pawn
loud junco
#

i use railway.app and vsc

loud junco
slate swan
#

vsc I'll suggest

sharp pawn
#

and if ur gonna use replit then you can go along w uptime robot

loud junco
#

rate limits

calm jacinth
slate swan
sharp pawn
#

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

sharp pawn
loud junco
sharp pawn
#

its been a while since I've coded

loud junco
slate swan
loud junco
slate swan
loud junco
#

but im 16 man

#

i dont have cc
so i use railway.app

slate swan
#

same can't get a cc until i have a job

loud junco
#

lol

sharp pawn
#

is railway that good

loud junco
#

railway.app also support database

sharp pawn
#

i never really used it so i wouldn't know

loud junco
#

like really database instead of json 💀

slate swan
#

railway is decent, supports heroku builds docker and what not

sharp pawn
#

anyways

#

im planning to make an adventure rpg discord bot but it's too time consuming

#

the quest, missions, item crafting and shit

sharp pawn
#

ong?

loud junco
#

its in my bio check it out if u want definitely not advertising

sharp pawn
#

nah not minecraft

#

like a pure rpg game on discord

#

with a couple of starting character you can choose

loud junco
#

oo u mean mmo

slate swan
sharp pawn
#

with different powers, ability and attacks

loud junco
slate swan
#

send link

loud junco
#

alright let me explain

sharp pawn
#

its cool but again it's gonna drain me out

calm jacinth
loud junco
#

rpminecraft(public) = replit
rpminecraft beta(private) = railway.app

sharp pawn
loud junco
#

because i started the whole thing in replit
so im making a clone version of it without destroying it

sharp pawn
#

just download it and open a workspace

calm jacinth
loud junco
calm jacinth
sharp pawn
#

yes ofc

loud junco
#

alright the code updated every sunday part is a lie

slate swan
#

so you just don't have an option to make the source close lmao

loud junco
#

LOL

#

technically yes

calm jacinth
loud junco
sharp pawn
shrewd apex
loud junco
sharp pawn
#

i wouldn't use replit tbh

shrewd apex
#

student dev got like 6 months free

loud junco
#

now it makes me feel like hanging myself

#

terraforming json to sql

slate swan
loud junco
#

now i know why sarth and the bois tell me to switch long time ago

shrewd apex
#

well hopefully u jump to asyncpg directly and don't pit stop on sqlite

supple ridge
#

any idea how can i print the value of name number level and the percentage of this embedm

sharp pawn
#

@calm jacinth try using this code

shrewd apex
loud junco
#

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
🥹

calm jacinth
sharp pawn
#

`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

loud junco
#

what do i do now

#

or custom url

calm jacinth
loud junco
sharp pawn
#

origin did the code work for you

loud junco
calm jacinth
calm jacinth
loud junco
sharp pawn
calm jacinth
sharp pawn
#

anyway

#

did it work

calm jacinth
sharp pawn
#

lmk if any error occurs

calm jacinth
loud junco
#

take one step at a time dont rush
its not gonna end up well if u rush

calm jacinth
loud junco
#

minecraft???

slate swan
#

*me, i guess

calm jacinth
loud junco
calm jacinth
#

@sharp pawn the bot still doesnt reply ;c
anyway ty for help

loud junco
#

whats the problem

sharp pawn
#

damn

loud junco
#

about vsc

sharp pawn
#

the bot really trippin fr

loud junco
#

like copy paste it here

#

!paste

unkempt canyonBOT
#

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.

calm jacinth
loud junco
calm jacinth
# loud junco 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

sharp pawn
#

lemme find the errors

loud junco
#

its already that by default

loud junco
calm jacinth
sharp pawn
calm jacinth
#

but the bot no reply

loud junco
#

do u try all of the command?

#

or u only try greet

sharp pawn
#

im giving the revised code gimme a sec

slate swan
#

you don't have message_content intents ...

#

prefix cmds don't work without that

calm jacinth
loud junco
calm jacinth
#

no errors but bot no respond when i type /bye or /greetings

loud junco
#
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

loud junco
#

ignore the prefixxx alright?

slate swan
loud junco
#

pretend u never see that

calm jacinth
sharp pawn
#

`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')`

loud junco
sharp pawn
#

this should work

supple ridge
calm jacinth
slate swan
#

nvm im out

sharp pawn
#

ancestry try the above code

calm jacinth
sharp pawn
#

holy shit this should work

#

im giving up on python if it doesn't

loud junco
# calm jacinth what dat ??

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

shrewd apex
quick gust
calm jacinth
loud junco
#

the server link is in my bio just saying definitely not advertising

shrewd apex
supple ridge
#

like how to split?

loud junco
shrewd apex
slate swan
calm jacinth
#

@sharp pawn bot only replies when pinged

shrewd apex
#

!d str.split

unkempt canyonBOT
#

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:
shrewd apex
#

message content intent be like ducky_sphere

sharp pawn
shrewd apex
#

loooli u both need to get some python education nothing wrong with ide

loud junco
#

lo..LI???

sharp pawn
calm jacinth
#

ty for helping

loud junco
#

its like studying inside a warzone it works but not effective

shrewd apex
loud junco
#

i mean me too
but if u let me choose again i will start with vsc

shrewd apex
#

max level skill is writing in notepad

loud junco
#

nah

#

microsoft word
there is a video about it

shrewd apex
#

nah word has syntax highlighting

#

different colors and stuff

slate swan
#

@shrewd apex you have local pgsql server or use a remote host?

loud junco
#

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?
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀...

▶ Play video
#

@shrewd apex

#

🤣

shrewd apex
#

y? tho

loud junco
loud junco
slate swan
shrewd apex
shrewd apex
slate swan
loud junco
#

just look at this

shrewd apex
#

finish lore first

loud junco
#

paused from exceeding limits

slate swan
loud junco
#

anya?

shrewd apex
#

wdym dw its been a year now 😭

shrewd apex
slate swan
slate swan
shrewd apex
#

and thats y ur pedo

loud junco
#

oh my days

#

call 911

slate swan
shrewd apex
#

u got 6 year old pfp every alternate months hima, anya few others who idk

slate swan
shrewd apex
#

kek sarth on revenge mode brainmon

shrewd apex
#

idk

loud junco
#

👀

shrewd apex
calm jacinth
#

@sharp pawn is dis a good about me for my bot ?

slate swan
unkempt canyonBOT
#

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.
shrewd apex
#

who even looks at about me

slate swan
#

me

calm jacinth
shrewd apex
#

hmm fair enough

loud junco
#

alr i dumped json for sql

slate swan
#

atleast you didn't use txts

loud junco
#

so ye

loud junco
slate swan
#

i don't even use it for that 😈

calm jacinth
sharp pawn
#

yes yes

#

what was the need to kill power like fr

calm jacinth
calm jacinth
sharp pawn
#

isn't makima some sort of curse

#

alright we shouldn't talk abt anime in this channel

calm jacinth
#

yeah

calm jacinth
slate swan
#

!ot there's these channels

unkempt canyonBOT
calm jacinth
loud junco
slate swan
#

idky this exists but

calm jacinth
slate swan
#

someone got some nice Command ideas?
i plan to make a study bot

#

command/functionality ideas

sharp pawn
#

must be able to solve basic and complex arithmetic

#

must be able to look up definitions of terms

#

must have a study reminder

loud junco
sharp pawn
#

yes yes a quiz command

quick gust
slate swan
loud junco
#

💀

quick gust
slate swan
#

@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

sharp pawn
#

also, the bot must be able to summarise a large text into a small brief text

slate swan
quick gust
#

openAI is the only application i can think that does that, and its paid after 18$

slate swan
#

doing the reverse would have been easier

quick gust
slate swan
#

the first hard part would be how to take user inputs for those operations 💀

sharp pawn
#

there's textblob

quick gust
#

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

slate swan
#

time to kidnap doubtnet developers

quick gust
#

isnt it doubtnut

#

kidnap socratic developers

slate swan
#

maybe, i haven't used it much

quick gust
#

make them work for u

vague zephyr
glossy edge
#

Where can i find a guide to automatically pull updated code and restart the bot when the repository is updated (merged)?

sick birch
#

@feral timber I summon you to send this person the same link you sent me the other day

#

Kthxbye

sick birch
#

CC @glossy edge

glossy edge
feral timber
sick birch
#

If it makes you feel any better I gave up on this

feral timber
glossy edge
glossy edge
feral timber
sick birch
#

Containerizing isn't the issue for me it's the auto deployment

feral timber
sick birch
#

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

feral timber
# sick birch Deploy from there

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

glossy edge
#

Sure, I'm assuming you're talking about the if guard

solid orbit
#

can someone help me in game development channel?

#

do you maybe know why my code is not working?

#

idk the sollution

naive briar
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@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").
slate swan
#

!blocking , while True loops are blocking

unkempt canyonBOT
#

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!

slate swan
#

just using await doesnt mean your became async

calm jacinth
#

Is it legal to make a discord bot using chat gpt ?

vague zephyr
#

i'm pretty sure it is

mossy jacinth
#

I never had this error. Please help me

somber imp
#

Oh wait your view isn't a view

#

It's a modal

#

There should be a send_modal method on interaction

#

Call that

ember nest
#

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

vale wing
vale wing
#

Yk about regex?

ember nest
glad cradle
#

!regex

unkempt canyonBOT
#

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

ember nest
#

Hmm what's that lmao

vale wing
#

For links uncomplicated one would be https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@])*

#

Just made it myself hopefully this is right

lament depotBOT
vale wing
#

@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

ember nest
#

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?

vale wing
#

That's wrong regex sorry

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

['https://google.com', 'https://pythondiscord.com/pages/guides']
vale wing
#

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

vale wing
#

Subjective

alpine cove
#

its just a lot to learn

#

and will seem overwhelming at the beginning

#

but you'll get the hang of it easily

vale wing
#

You check what? Messages content

ember nest
#

So now after that

#

How to make the bot check if the message had that to delete on on_message

vale wing
#

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

ember nest
#

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

vale wing
#

Idk what else to explain without sending the full code

ember nest
#

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

vale wing
#

Explaining with code != spoonfeeding (giving the full ready working code)

ember nest
#

Unless I want to learn not just copy - paste

vale wing
ember nest
#

Oh

#

Hmmm but I can't understand how to use that in the if etc

vale wing
#

And you can handle situations if there is a link or if there's no link by checking length of returned list

ember nest
#

Hmmm

#

And can I make another pattern with discord links and add that new variable to the re.findall ?

vale wing
#

!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))```

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | True
002 | False
ember nest
#

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)
vale wing
ember nest
#

Oh

#

And add content with each one?

vale wing
#

Or you can merge patterns (that's not what I'd recommend to do)

vale wing
ember nest
vale wing
#

First check for links then for invites

vale wing
ember nest
#
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)
    
vale wing
#
LINKS_PATTERN2 = re.compile(r"discord\.(?:gg|com/invite)/[\w\d]+")```
Forgot the `r`
#

The rest is ok

ember nest
#

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

vale wing
#

Listen for on_message and apply that thing to message.content, then check for amount of links/invites ig

ember nest
#

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

vale wing
#

With?

vale wing
# ember nest 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

stone stream
#

Hello

#

How can I send code in colour ?

ember nest
vale wing
unkempt canyonBOT
#

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.

vale wing
stone stream
#

thank you

alpine cove
ember nest
vale wing
#

Happens

ember nest
#

But like I don't understand what you mean

vale wing
ember nest
#

I learned python for like 3-4 months before

vale wing
#

Time doesn't matter but the knowledge you got does

ember nest
#

Yeah it's kinda cool

#

But I don't understand what you meant like sorry my English is not that good tbh lol

vale wing
#

So do you know classes and objects

ember nest
vale wing
#

Ok great

#

Then I just gotta rephrase

ember nest
#

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

vale wing
#

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

stone stream
#
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

ember nest
# vale wing In `on_message` you receive a `message` object, you can access attributes of mes...

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?

stone stream
#

I am a beginer I began to code my bot this afternoon

vale wing
#

The tutorial you found is bad

stone stream
#

ok...

vale wing
#

In docs there's an actual tutorial iirc

alpine cove
ember nest
vale wing
#

For video tutorial to be good it requires the "teacher" to be good at coding (impossible) and be recent

ember nest
#

....

vale wing
#

I'm talking to 3 persons at the same time sry

#

I remember about everyone

ember nest
vale wing
#

You don't need that content at all, it was for example purpose

ember nest
#

So just do in message?

#

Like that

if len(links) or len(links2) in message:
    await message.delete()
vale wing
#

Tell me what does len() return in your opinion

ember nest
#

A list

vale wing
#

Negative

#

It returns amount of items in a sequence, i.e. length

#

You need to check if it's more than 0

ember nest
#

So

vale wing
#

This is becoming spoonfeeding fr

ember nest
#

I am kinda confused now idk how to do yhat

vale wing
#

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
        ...```
ember nest
#

So ```py
if len(links) > 0:
await message.delete()
return

oblique fern
#

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?

vale wing
#

Yes

vale wing
oblique fern
#

K, cool. I just finished rewriting so I want to test it

#

its a game, rounds are 10-15 mins

ember nest
#

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

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```
ember nest
#

Hmmm

#

But keep on @bot.event still will work right?

vale wing
#

Yes

ember nest
#

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?

glad cradle
unkempt canyonBOT
#
Out of the question.

No documentation found for the requested symbol.

ember nest
#

Hm

glad cradle
#

Well it won't find it but discord.Member.guild_permissions returns a Permissions object

#

and you could do

#

!d discord.Permissions.attach_files

unkempt canyonBOT
ember nest
#

So I can just do
user = mesage.author.guild_permissions.attach_files
@glad cradle

glad cradle
#

if you're inside a guild yes

ember nest
#

Alright lemme see

#

Not working @glad cradle

ivory shadow
#

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

sick birch
unkempt canyonBOT
#

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.

sick birch
#

Is how you fix your current issue @ivory shadow this

ivory shadow
cloud dawn
#

Robin is just very old so he gets it wrong sometimes.

ivory shadow
#

@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

sick birch
sick birch
#

Are you using prefix commands or application commands?

cloud dawn
#

If you're not is verified Robin~ 2022

#

I'll stop now.

sick birch
#

its been a long day ;(

ivory shadow
cloud dawn
ivory shadow
sick birch
#

Yup that's about your only course of action

ivory shadow
#

wait

#

so how should i update to application commands

sick birch
#

You basically just rewrite everything to use the new slash commands and buttons and whatnot

ivory shadow
#

oh

sick birch
#

It is a royal pain I know

ivory shadow
#

i have like a thousand something lines of code though

ivory shadow
sick birch
#

One thing you've got going is most of the actual logic for your commands should be a straight copy paste

ivory shadow
#

good point

cloud dawn
#

Hence why we recommend everyone to use slash commands from the start.

ivory shadow
cloud dawn
ivory shadow
#

wait no

sick birch
#

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

ivory shadow
#

before the thing

#

wait when was discord,py slash commands released

cloud dawn
#

I was also made before the thing.

sick birch
#

!d discord.ext.commands.Context.from_interaction

unkempt canyonBOT
#

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.
cloud dawn
ivory shadow
#

i guess i found out about them late

sick birch
#

They were only enforced Q2 or 3 of 2021

ivory shadow
#

yeah i didn’t update them in time

cloud dawn
#

Tough to be fair Discord.py only had them at the start of Q1 2021

ivory shadow
#

i took a break for like a year

cloud dawn
#

Late January or smth?

ivory shadow
#

oh okay i created my bot start of april 2021

cloud dawn
sick birch
#

Did I say something wrong

cloud dawn
#

No?

#

Do you think you did?

ivory shadow
#

so only option is to like rewrite my entire code

cloud dawn
#

When are you going to sleep? ducky_sphere

sick birch
#

Soon 😓

cloud dawn
sick birch
cloud dawn
ivory shadow
sick birch
#

Still a pain but logic is still the same

ivory shadow
#

but i don’t have intents in general, so i can still do it without them?

glad cradle
ivory shadow
sick birch
#

You shouldn't need message content intents for app commands

cloud dawn
#

tbh your bot shouldn't even be 1000+ lines, most of my commands are like at most 10 lines maybe sometimes 15.

ivory shadow
sick birch
#

They've probably just got a lot of commands

ivory shadow
#

i was planning on rewriting everything but then i got hit with that error

sick birch
#

You probably used discord.Intents.all()

cloud dawn
#

You prob need to re-invite it since you haven't selected the app commands scope.

ivory shadow
ivory shadow
cloud dawn
#

It's a scope not a permission.

sick birch
#

It may be one of the other 2 privileged intents you have explicitly enabled

#

IIRC its members and presences?

ivory shadow
ivory shadow
#

i’ll check again

cloud dawn
ivory shadow
# cloud dawn

how do i get there again (sorry i haven’t done this in like a year)

cloud dawn
hushed galleon
#

discord.py's hybrid commands could smooth over the transition too, though not perfectly by itself

cloud dawn
#

I Don't recommend hybrid commands.

ivory shadow
hushed galleon
#

they put a lot of work into those 🥺

cloud dawn
cloud dawn
hushed galleon
#

tbh i havent used them before, only seen what the docs describe

ivory shadow
cloud dawn
#

It's a generator.

ivory shadow
ivory shadow
#

alright so what do i do next

hushed galleon
# cloud dawn They did... but kinda useless.

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

cloud dawn
#

Well you'd still need message intents to make them work.

hushed galleon
#

just the slash part of it can work, again depending on what the original command does

ivory shadow
#

@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

cloud dawn
#

@ivory shadow

#

leaked my discord id...