#discord-bots

1 messages · Page 245 of 1

robust fulcrum
#

Use aiohttp

lucid galleon
#

ohk

robust fulcrum
#

What you trying to do with your code?

north kiln
lucid galleon
#

need a help on this error

naive briar
#

It just told you in the error

lucid galleon
#

ok

slate swan
#

how to fix that

#

while amount > count:

#

thats the code thats giving me a error

(btw its a amount: int)

thin raft
#

full code

#

and full traceback pls

#

because that shouldn't raise that error

#

!e

while 1 > "amount":
  pass
unkempt canyonBOT
#

@thin raft :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     while 1 > "amount":
004 |           ^^^^^^^^^^^^
005 | TypeError: '>' not supported between instances of 'int' and 'str'
naive briar
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print("uwu" + 139)
004 |           ~~~~~~^~~~~
005 | TypeError: can only concatenate str (not "int") to str
slate swan
#

btw i fixed that

bleak pollen
#

a

slate swan
#

discord.app_commands.errors.CommandInvokeError: Command 'csn' raised an exception: TypeError: can only concatenate str (not "float") to str
how do u fix that

#

!e ```py
print("string" + 1.23)

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     print("string" + 1.23)
004 |           ~~~~~~~~~^~~~~~
005 | TypeError: can only concatenate str (not "float") to str
slate swan
#

@slate swan you see whats wrong?

slate swan
#

you cant add number to a string

#

its not a string

#

its a int

#

the error says otherwise

#

hold up i have to check again

polar coyote
slate swan
polar coyote
slate swan
#

when ever u have 0 it gives u 500

polar coyote
#

show me your code

#

are you using a database?

slate swan
#

im trying to fix it its giving me lots of errors

lucid galleon
#

where to host discord bot for free?

formal basin
#

@client.event
async def on_message(message):
 embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
 if message.author.id == client.user.id:
        return 
 message.content
 if message.embeds:
        pass
 else:
     with open('blocked words.txt') as f:
        words = f.read()
        blockedwords = words.split()
        if any(word in message.content.lower() for word in blockedwords):
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
      
formal basin
#

example a blocked word is loser

#

and if i type lo it deletes

polar coyote
polar coyote
formal basin
polar coyote
lucid galleon
#

Tried

formal basin
polar coyote
lucid galleon
#

Replit and upload robot

polar coyote
formal basin
formal basin
lucid galleon
# polar coyote ?

I have connected my replit with uploadrobot. But by bot is not working like i wanted

#

I have used huggingface interface api. Uploadbot is making unnecessary request that's i closed my replit

formal basin
polar coyote
formal basin
polar coyote
formal basin
lucid galleon
#

Ok

slate swan
#

its giving str or int error idk

formal basin
slate swan
formal basin
slate swan
#

!e ```py
bannedWords = ["loser", "lay"] #write the code that grabs the words form the txt
message_content = "I am a los (we will see if it will delete it)"
message_words = message_content.lower().split(" ")
if any(word for word in message_words if word in bannedWords):
print("Banned word detected")
#delete the message
else:
print("Couldn't find the banned words in that message")
#pass ...

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

Couldn't find the banned words in that message
slate swan
#

@formal basin

#

its going to be something like that

#

!e ```py
bannedWords = ["loser", "lay"] #write the code that grabs the words form the txt
message_content = "I am a loser (we will see if it will delete it)"
message_words = message_content.lower().split(" ")
if any(word for word in message_words if word in bannedWords):
print("Banned word detected")
#delete the message
else:
print("Couldn't find the banned words in that message")
#pass ...

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

Banned word detected
slate swan
#

see?

formal basin
#

yes

slate swan
#

u can do the samething with ur code

formal basin
slate swan
#

idk if its allowed but wait

#
@client.event
async def on_message(message):
 embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
 if message.author.id == client.user.id:
        return 
 if message.embeds:
        pass
 else:
     with open('blocked words.txt') as f:
        words = f.read()
        blockedwords = words.split()
        user_message = message.content.lower().split(" ")        
        if any(word for word in user_message if word in blockedwords):
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)


slate swan
#

than a txt file

slate swan
spice zenith
#

does someone know how to do a command where u give 2 discord users and it show something like this with the name and profile picture of the user inside a preset photo and then insert 2 emotes with the profile pic of the users??

north kiln
#

I mean you essentially do what you said?

#

Create the image then attach to the embed to send it

quick gust
unkempt canyonBOT
whole shoal
#

Why does the unknown interaction error occur when I host the bot on a server when when I run it on my laptop it doesn't occur 🗿

slate swan
#

everytime I try to run this python auto closes

smoky sinew
#

run it from a terminal

merry cliff
twilit grotto
charred badge
#

Sorry for the slow response, irl and things on here didn’t leave me much time to try with it all. So I think is missing from my imports. When I try to do slash_commands or app_commands it says things aren’t defined, even when I try to test the code you linked to make sure at least something works with it, it says things like app_commands is not defined. Is there some module I have to install to make this work or something that I’m missing?

crisp meteor
#

does anyone know how i can make a last.fm command? i have the API set up

full lily
cunning gulch
#

if I've got a discord bot for rock paper scissors, and it's using options to decide what text it allows as a choice, but i added a variant of the code that adds more things to rps how would i set up it's options, i was told to ask here

mortal oak
#
import random


def random_string():
    random_list = ["Please try writing something more descriptive.",
        "Oh! It appears you wrote something I don't understand yet",
        "Do you mind trying to rephrase that?",
        "I'm terribly sorry, I didn't quite catch that.",
        "I can't answer that yet, please try asking something else."
        ]
    list_count = len(random_list)
    random_item = random.randrange(list_count)
    return random_list(random_item)
print(random_string())
``` it says that "list" object is not callable in line 13
potent spear
#

this is also pretty irrelevant for this chat 😬

surreal valve
#

for the return random_list(random_item)

#

also u can just do return random.choice(random_list)

naive briar
slate swan
#

how would i make somthing in discord.py i made a cooldown but i want some user not have the cooldown

surreal valve
misty portal
#

:)

slate swan
#

Someone help me with this weird error please.

import disnake as discord
from disnake.ext import commands


class Info(commands.Cog):

    def __init__(self, bot):
        self.bot: commands.InteractionBot = bot

    
    @ commands.slash_command(name='bot-info', description='Gives you information about the bot.')
    async def bot_info(self, inter: discord.AppCmdInter):
        embed = discord.Embed(...)
        embed.add_field(name='Developer', value='Shrey - `Shrey#2722`')

        embed.set_thumbnail(...)
        embed.set_footer(text='Use /help to get started!')

        await inter.send(embed=embed)


def setup(bot):
    bot.add_cog(Info(bot))

This is a very simple cog command bot it gives me error.

Traceback (most recent call last):
  File "d:\Shrey\Projects\3P Pie\Extensions\info.py", line 5, in <module>
    class Info(commands.Cog):
  File "C:\Users\Divi\AppData\Local\Programs\Python\Python311\Lib\site-packages\disnake\ext\commands\cog.py", line 195, in __new__
    raise TypeError(no_bot_cog.format(base, elem))
TypeError: Commands or listeners must not start with cog_ or bot_ (in method Info.bot_info)
north kiln
#

the traceback says it?

#

don't name your function bot_info

#

or anything that starts with cog_or bot_

slate swan
#

Commands or listeners must not start with cog_ or bot_

The world would be 10x better if people would take the time to read tracebacks, especially when they're very clear krThisIsFine

naive briar
#

Unfortunate

slate swan
slate swan
twilit grotto
#

we all start somewhere, just read tracebacks.

#

thats what they're there for.

slate swan
#

It's not about coding here, it's about reading and understanding tracebacks

#

i read it, i got this error first time thats why i was confused

#

thx for the help btw

twilit grotto
#

well, now you know :)

#

if you aren't understanding a traceback, reread your code & the traceback

vale wing
#

I wish docker would give tracebacks why tf it returns empty bodies in a certain container however everything's fine outside 🧐

vale wing
#

Raged about it the whole yesterday's evening gonna rage even more today

charred badge
smoky sinew
formal basin
#

This isn’t giving the role

#

I’m typing the command and nothing is happening no errors

formal basin
north kiln
#

Do you have message content intent

formal basin
charred badge
smoky sinew
formal basin
smoky sinew
#

your command is probably not running then

formal basin
smoky sinew
#

show your full code

formal basin
#

!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.

smoky sinew
#

is the role above the bot and are you typing !verify

smoky sinew
#

which question

formal basin
smoky sinew
#

i asked two questions

formal basin
formal basin
formal basin
slate swan
formal basin
slate swan
#

Are you sure the bot is running

formal basin
naive briar
#

Doubt that

formal basin
slate swan
formal basin
#

the other commands work

naive briar
#

What other commands

formal basin
slate swan
#
@client.command()
async def verify(ctx: commands.Context) -> None:
    role_id = 1088500965759520838
    role = discord.utils.get(ctx.guild.roles, id=role_id)
    if role:
        await ctx.author.add_roles(role)
        await ctx.send("Role was added successfully.")
    else:
        await ctx.send("Role not found.")

Perhaps try this to verify it's finding the role.

naive briar
#

I doubt that you can even run the bot, honestly. Your code at the line 25 is already incorrect

client.remove_command(help)

help isn't defined anyway

slate swan
formal basin
naive briar
#

That's why it's incorrect

slate swan
formal basin
naive briar
#

What does makes a help command even means

#

The point is, the help name isn't defined anywhere

formal basin
slate swan
naive briar
#

I already know that

naive briar
#

But, your help name still isn't defined

slate swan
formal basin
slate swan
#

Iirc having more than one event causes commands to stop working? @naive briar

naive briar
#

No, if you override the on_message event without calling process_commands method, the bot will not, well, process the commands

charred badge
smoky sinew
#

you have to import app_commands from discord

#

that's the error you got

charred badge
#

I’m either an idiot or I never tried that… swore I did… tyvm! Will make sure the slashes actually get uploaded but I really appreciate your time and patience

robust fulcrum
#

Hi guys , which are the basic python concepts one should know to use discord.py easily?

smoky sinew
smoky sinew
#

if you learn the two above you will probably already know the smaller ones

robust fulcrum
#

I know both , so i can make bots easily , thanks for telling

haughty geyser
#

P

serene lynx
#

Excuse me, I want to ask, what is the name of the attribute to check roles that have access to certain channels

vale wing
serene lynx
serene lynx
vale wing
whole shoal
merry cliff
#

ok

whole shoal
#

Oh yeah the server dpy version was outdated thanks for the help guys

stark socket
#

hi i have a discord bot and i want him to get all the members in a discord server but when i do this
"member = get(discServer.members, name=datajson[key])"
i only get the bot as a member

obsidian fable
#
class PlayButton(ui.Button):
        async def callback(self, interaction: discord.Interaction):
            await interaction.response.defer(thinking=True)
            songlink = f"https://api.lonelil.dev/fetch/{songlink}"
            file_bytes = b_download_track(songlink)
            custom_path = "./music/org/"
            with open(f"{custom_path}{name}.ogg", "wb") as f:
                f.write(file_bytes)
            with open(f"{custom_path}{name}.ogg", "rb") as f:
                message = await interaction.response.send_message(f"`{name} by {artists}`:", file=File(f, filename=f"{name}.ogg"))
                await interaction.response.edit_message(message, content=f"`{name} by {artists}` (updated)")

why does it say that the interaction has already been responded?

stark socket
#

do i need to reevinte the bot?

vocal snow
#

Have you enabled the members intent in your code?

stark socket
#

its the name

stark socket
#

do i need to enable it on the code?

vocal snow
vocal snow
#

!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.

obsidian fable
stark socket
#

thanks

vocal snow
obsidian fable
vocal snow
#

Can you show your new code?

obsidian fable
#

yes

#
class PlayButton(ui.Button):
        async def callback(self, interaction: discord.Interaction):
            await interaction.response.defer(thinking=True)
            songlink = f"https://api.lonelil.dev/fetch/{songid}"
            file_bytes = b_download_track(songlink)
            custom_path = "./music/org/"
            with open(f"{custom_path}{name}.ogg", "wb") as f:
                f.write(file_bytes)
            with open(f"{custom_path}{name}.ogg", "rb") as f:
                await interaction.followup.send(f"`{name} by {artists}`:", file=File(f, filename=f"{name}.ogg"))
vocal snow
#

Hmm this looks fine, can you show the full traceback?

obsidian fable
#

sorry about that

vocal snow
#

Your code which interacts with the api is blocking, you should make it async

#

If you're using requests, switch to aiohttp

obsidian fable
vocal snow
#

It won't pause the entire program when it makes a request and waits for the response

obsidian fable
#

I will try and implement that

#

thank you

whole shoal
#

@merry cliff
It's still giving the same error
`File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "spikey.py", line 154, in ping
await ctx.response.send_message(f'Pong! {round(client.latency*1000)}ms')
File "/home/container/.local/lib/python3.8/site-packages/discord/interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "/home/container/.local/lib/python3.8/site-packages/discord/webhook/async
.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/container/.local/lib/python3.8/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction`

edgy veldt
#

I'm trying to host my code on Railway, it's an app that puts Flask and Discord.py together in the same place. The goal is that when you send a post request to the API (flask), the discord bot creates a text channel

but I don't know why when I upload my app to Railway, an infinite loop starts and the app doesn't work

code:

main.py

...
# <--- TRHEADS --->
def run_bot(): bot.run(os.environ.get("TOKEN"))
def run_api(): app.run(port=5000, debug=False)

# <--- RUN --->
flask_thread = threading.Thread(target=run_api)
bot_thread = threading.Thread(target=run_bot)

flask_thread.start()
bot_thread.start()

flask_thread.join()
bot_thread.join()
Procfile

web: gunicorn main:run_api
worker: python main.py run_bot
whole shoal
twilit grotto
whole shoal
#

Kinda

twilit grotto
#

thats the only reason i've had that issue before

whole shoal
#

I need to find a better host

naive briar
terse elbow
#

I need help, I want to create a slash command within a cog and I can't create it as self.tree:

    def __init__(self, client):
        self.client = client
        self.guild = 1053710120493776926
        self.tree = app_commands.CommandTree(client)

    @self.tree.command()```
hushed galleon
#

commands.Bot comes with its own command tree so you dont need to create another one

#

as for defining the slash commands, use @app_commands.command() and dpy will recognize it when you add the cog

terse elbow
#

Thanks

hushed galleon
#

for every command in the cog or just one?

terse elbow
hushed galleon
#

apply @app_commands.guilds(1234, 5678) to the top of your class

#

hmm i thought there was an example of this in the docs

terse elbow
#

Thanks, I'm outdated I've used to create discord bots before there were slash commands

hushed galleon
#

well if you dont mind your commands being a single group you can go that route, otherwise you'll have to apply the decorator to each application command

terse elbow
hushed galleon
#

if you specify guilds() then it can only be synced to whatever guilds you listed, not globally

terse elbow
#

Ok thanks

terse elbow
#

Why the slash command isn't displaying?

    def __init__(self, client):
        self.client = client

    @app_commands.command(name="rolldice")
    @app_commands.guilds(discord.Object(id=1053710120493776926))
    @app_commands.describe(num="number")
    async def dice_roll(self, interaction: discord.Interaction, num: int):
        print(f"{interaction.user.mention} said {num}")


async def setup(client) -> None:
    await client.add_cog(DiceRoll(client))```

It worked before using tree
north kiln
#

how are you syncing your tree

mortal oak
#

which library is better for discord bots?

meager chasm
#

Whichever you find more easy to use

mortal oak
#

which one is more beginner friendly?

vocal plover
#

It depends really on what you're looking for, if you want something widely used and 'normal' in the Python ecosystem then discord.py/nextcord/disnake are good choices, depending on your preferred method of doing things (discord.py uses a command tree type thing for slash commands, nextcord and disnake opted for slash commands more similar to normal text commands with decorators), if you want something more explicit/with more precise control then hikari is a good choice

meager chasm
mortal oak
#

i still dont know what async def does

#

neither i know what await does

meager chasm
vocal plover
meager chasm
#

It's essentially a way for parts of your program to pause and unpause inorder to reduce waiting time during I/O operations to allow for a feeling of parallel execution

terse elbow
#

Does anyone know why my slash command isn't working?
My main file:

import asyncio
import discord
import os
from discord.ext import commands
from assets import TimeLoops

MY_GUILD = discord.Object(id=1053710120493776926)


class MyBot(commands.Bot):
    async def on_ready(self):
        TimeLoops(self).check_tables()
        self.loop.create_task(TimeLoops(self).mute_loop())
        self.loop.create_task(TimeLoops(self).mute_loop())
        print("Ready!")

    async def load(self):
        for filename in os.listdir('/'):
            if filename.endswith('.py'):
                await self.load_extension(f'cogs.{filename[:-3]}')

    async def setup_hook(self):
        await self.tree.sync()


intents = discord.Intents.all()
client = MyBot(command_prefix="!", intents=intents)


async def main():
    await client.load()


asyncio.run(main())

client.run(secret)
asyncio.run(client.setup_hook())

My command file:

    def __init__(self, client):
        self.client = client

    @app_commands.command(name="rolldice")
    @app_commands.guilds(discord.Object(id=1053710120493776926))
    @app_commands.describe(num="number")
    async def dice_roll(self, interaction: discord.Interaction, num: int):
        print(f"{interaction.user.mention} said {num}")


async def setup(client) -> None:
    await client.add_cog(DiceRoll(client))
naive briar
terse elbow
#

@naive briar explain

naive briar
#

You should have notice it immediately. In your load method, you're getting a list of files in your current directory, not in the cog folder that you're trying to load it from

terse elbow
#

as for now, they are in the same directory

naive briar
#

Then load in from the current directory

terse elbow
#

Oops

#

I've changed it to await self.load_extension(f'{filename[:-3]}') but it's still not working

naive briar
#

Any errors? It's not working doesn't make me understand your problem

terse elbow
#

No error. just not showing the slash commend

#

@naive briar Do you have any idea what the problem might be? I've enabled applications.commands

naive briar
#

You enabled it, but did you invite your bot with it?

potent spear
#

fixed
please don't crosspost
(his cogs weren't even loaded in properly in the first place)

naive briar
#

lmao

terse elbow
#

@naive briar Do you have any idea what the problem might be now?

import asyncio
import discord
import os
from discord.ext import commands
from assets import TimeLoops

MY_GUILD = discord.Object(id=1053710120493776926)


class MyBot(commands.Bot):
    async def setup_hook(self):
        for filename in os.listdir('/'):
            if filename.endswith('.py'):
                await self.load_extension(f'{filename[:-3]}')

        #TimeLoops(self).check_tables()
        #self.loop.create_task(TimeLoops(self).mute_loop())
        #self.loop.create_task(TimeLoops(self).mute_loop())

        await self.tree.sync()
        print("Ready!")


intents = discord.Intents.all()
client = MyBot(command_prefix="!", intents=intents)


client.run(secret)

command file:

class DiceRoll(commands.Cog):
    def __init__(self, client):
        self.client = client

    @app_commands.command(name="rolldice")
    @app_commands.guilds(discord.Object(id=1053710120493776926))
    @app_commands.describe(num="number")
    async def dice_roll(self, interaction: discord.Interaction, num: int):
        print(f"{interaction.user.mention} said {num}")


async def setup(client) -> None:
    await client.add_cog(DiceRoll(client))
slate swan
#

You get the errors/logs/outcome, we're not interpreters - you tell us

terse elbow
#

I got no error. the slash command simply not appearing on my server.

potent spear
terse elbow
slate swan
#

Why are you doing a listdir over /

#

If you want the current folder it's ./ which is clearly different

potent spear
#

myeah, just putting your cogs in cogs folder would make that less of an issue

slate swan
#

And you should put your cogs in a cogs folder and load from ./cogs

potent spear
#

(which is used in the docs too)

slate swan
#

a question guys

#

is it possible to make buttons inside an embed?

#

i was thinking on maybe making an interface for the users

#

in my bot

#

like an UI, so peoples could use the bot easier

#

inside, no

#

below, yes

#

okay it seems that i will need to make tutorial of how to use my bot later

#

i can predict that it can still get overcomplicated

vale wing
#

Bobux bot got such a good tutorial how to use

vale wing
slate swan
slate swan
#

okay i will need to understand this, since i'm implementing the database into a file outside the bot, gonna be overwhelming, but i need to try my best

#

okay let me see if i understood the code
the setup hook is the part where it will pre-generate the tables
and the close method is to close the database
and the init is to conect or something to the database
the bot class is the class of the bot
but since i'm using a file outside the bot file... I have no idea how i will implement

#

what do i change at the class bot and init thing since i'm using a file different from the bot file?

#

guess i will need to change Bot to database, but... there is the command.Bot thing

#

i will need to change something here

#

but something is missing

formal basin
#
idiot 
i d i o t 
i-d-i-o-t 
i_d_i_o_t 
i.d.i.o.t"
stupi 
s-t-u-p-i 
s_t_u_p_i 
s.t.u.p.i 
s t u p i  
dum 
d-u-m 
d_u_m 
d.u.m 
d u m 
nerd 
n-e-r-d 
n_e_r_d 
n.e.r.d 
n e r d 
sucker 
s-u-c-k-e-r 
s_u_c_k_e_r 
s.u.c.k.e.r 
fat 
f-a-t 
f_a_t 
f.a.t 
f a t
loser
l o s e r
l.o.s.e.r
l-o-s-e-r
l_o_s_e_r```
#

why is it deleting: i didnt

#
@client.event
async def on_message(message):
 await client.process_commands(message)
 embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
 if message.author.id == client.user.id:
        return 
 if message.embeds:
        pass
 else:
     with open('blocked words.txt') as f:
        words = f.read()
        blockedwords = words.split()
        user_message = message.content.lower().split(" ")        
        if any(word for word in user_message if word in blockedwords):
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
          print(f"Toxicity detected by {message.author.name}: {message.content}")

slate swan
#

Because you're doing blockedwords = words.split()

#

So you're splitting on every whitespace

#

Considering you have s t u p i

#

i will be an element in blockedwords

#

Which will trigger i didn't because it contains i as well

formal basin
#

oh

slate swan
#

You likely want a words.split("\n")

formal basin
#

ok

#

thanks

slate swan
#

You also shouldn't really open the file on every message but rather keep the content of the file, or the blockedwords directly, cached somewhere in a bot variable for example

formal basin
# slate swan Which will trigger `i didn't` because it contains `i` as well
@client.event
async def on_message(message):
 await client.process_commands(message)
 embed = discord.Embed(title="please dont say that", color=discord.Color.blue())
 if message.author.id == client.user.id:
        return 
 if message.embeds:
        pass
 else:
     with open('blocked words.txt') as f:
        words = f.read()
        blockedwords = words.split("/n")
        user_message = message.content.lower().split(" ")        
        if any(word for word in user_message if word in blockedwords):
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
          print(f"Toxicity detected by {message.author.name}: {message.content}")
``` like this
slate swan
#

Looks better

formal basin
formal basin
slate swan
#

Well here the issue is that you consider s t u p i a bad word

#

So that will never be found

#

And no you shouldn't split with new lines user messages

#

user messages should be split with spaces

slate swan
#

But if someone sends s t u p i it won't get caught since the user message will be split to s, t, u, p and i

#

And none are in your blacklist obviously

slate swan
#

You can't really do anything against that as a beginner

slate swan
#

I'd rather use some online service where you send the content and it checks for toxicity and you get the result whether it's toxic or not, or use some algorithm - although those have lots of false positives

formal basin
formal basin
#

but still doestnt work

slate swan
#

Use an online service to check against profanity, Perspective is free and performant

formal basin
slate swan
#

There even is example code in Python :)

slate swan
#

since it means that you have brains

formal basin
#

thats why

slate swan
#

People call others "donkey" in a bad way as well

#

Just like lots and lots of other words

#

it's like "banana" from my country

#

That's why APIs like Perspective do what you need, they check context with machine learning etc.

#

originally it's to refer to a fruit

#

but here it's to refer as a bad way

#

like calling someone "um banana"

#

or saying "a preço de banana"

vocal plover
# formal basin people call other people that in a bad way

just my 2 cents as someone who does a lot of moderation stuff, I'd really discourage filtering automatically like this, while you can do this it'll result in a community that people don't want to engage in if there's a lot of filters that take commonly said things and always assume the context is bad

#

simple text filters cannot replace humans reading context and taking action, ML-based stuff is better but not perfect

formal basin
# vocal plover just my 2 cents as someone who does a lot of moderation stuff, I'd really discou...
blockedwords = ["idiot", "i d i o t", "i-d-i-o-t", "i_d_i_o_t", "i.d.i.o.t", "stupi", "s-t-u-p-i", "s_t_u_p_i", "s.t.u.p.i", "s t u p i",  "dum", "d-u-m", "d_u_m", "d.u.m", "d u m", "nerd", "n-e-r-d", "n_e_r_d", "n.e.r.d", "n e r d", "sucker", "s-u-c-k-e-r", "s_u_c_k_e_r", "s.u.c.k.e.r", "fat", "f-a-t","f_a_t", "f.a.t", "f a t", "loser", "l o s e r", "l.o.s.e.r", "l-o-s-e-r", 
                        "l_o_s_e_r"]
        if any (word in message.content.lower() for word in blockedwords):
          await message.delete()
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=10)
          print(f"Toxicity detected by {message.author.name}: {message.content}")
``` it doesnt work i tried to change it
potent spear
slate swan
#

but i guess it's way too heavy

vocal plover
#

we've got something like ~15 words actually blocked and they're all ones that pretty much cannot be used in a non-malicious context, and moderation is still easy enough, you can honestly just stick a few slurs in native automod and be fine tbh

#

(you may be able to tell I'm not a fan of naive text filters kek)

vocal plover
#

or just placing a single joiner character, ner.d

slate swan
#

yeah

#

honestly just enable that and do manual moderation

#

the feature you're working on is kind of pointless

slate swan
vocal plover
#

that would get flagged

#

since its now doing striung in string rather than string in list

slate swan
#

ah yeah changed the check in-between

shrewd apex
slate swan
#

Hey what IDE/IDLE do I use to make a discord bot

vocal plover
#

Any IDE that supports python

slate swan
#

Which one would you call the best in terms of features?

vocal plover
#

the most popular ones are visual studio code (vscode) and pycharm, both are pretty much as good as eachother, though for some features in pycharm you need a paid license/to be a student

slate swan
#

Oh okay thank you

vocal plover
#

np

slate swan
vocal plover
#

yeah that too

slate swan
#

Though the base functionalities are free and should be enough for beginners

#

Or even advanced people

vocal plover
#

i just stick with vsc because I don't want to bother with the hassle of getting pycharm stuff running and I have a good config already

slate swan
#

Yeah makes sense

vocal plover
#

but either will do you just as well really

slate swan
#
pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program.
#

How do I fix this

#

I'm trying to install discord in the terminal

#

I did

pip install discord
hushed galleon
#

on windows you likely have the py python launcher, so install with py -m pip install discord.py instead (discord is a mirror of discord.py)

slate swan
#

what does -m stand for

hushed galleon
#

or you can create and activate a virtual environment which should provide its own pip

hushed galleon
slate swan
#

Oh I don't know what those are

#

is it like a library?

vocal plover
#

yes, module/package/library are used essentially interchangably in discussion about python

hushed galleon
slate swan
#

Hey I'm reading a documentation on the discord module, and I don't know what intents means, can someone help?

client = discord.Client(intents=intents)
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
#

What's the gateway

vocal snow
slate swan
#

Man this is so overwhelming

#

How much do I need to know in python

ocean mango
#

Is there any way to make a bot output 9 images in a 3x3 grid?

slate swan
#

I think my level is at PCEP

shrewd apex
ocean mango
# shrewd apex format the image urself?

the position of the image on the 3x3 is not constant, I should probably use Pillow or something, theres no way to do it using embeds or normal file upload?

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @ocean mango until <t:1685043966:f> (10 minutes) (reason: attachments spam - sent 9 attachments).

The <@&831776746206265384> have been alerted for review.

shrewd apex
#

dont think its gonna show up as 3x3 matrix on discord

vale wing
plain pollen
#

!unmute 627192394399350795

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @ocean mango.

ocean mango
#

ty

plain pollen
#

oops, you sent the same image 9 times and it triggered the bot filter :P

ocean mango
#

was trying to demonstrate what I meant

plain pollen
#

ahhh, i see

merry cliff
#

Sounds a bit iffy tho

shrewd apex
#

i am 70% sure it will show up with

| a | b |
| a | c |

ocean mango
merry cliff
#

So you know how when you create an embed you can give the title a irl

ocean mango
#

yes

merry cliff
#

If it’s the same for multiple embed with images then it will stick all the embeds into one and have multiple images

ocean mango
shrewd apex
ocean mango
merry cliff
shrewd apex
#

just make sure embed url is same

merry cliff
#

Might not work with nine

ocean mango
#

then i just ouput that 3 times separately

merry cliff
#

If it’s three it won’t be in a row discord will make one larger and the other two smaller

#

To fit them in a square

ocean mango
#

I see

merry cliff
#

Just curious why do u need 3x3 images?

ocean mango
merry cliff
#

Can you explain the idea

ocean mango
merry cliff
#

Oh

#

I think PIL will be better for that honestly

ocean mango
#

yes

merry cliff
#

For a smooth image

ocean mango
merry cliff
ocean mango
#

ty

merry cliff
#

Do that but 9 times

cunning gulch
#

how do i set up a list of what my bot will accept as a response for a command, example: rock paper scissors bot only accepts the answer rock paper or scissors for a command, if anything else is said it ignores it and waits for one of the options stated?

ocean mango
#

if-else

cunning gulch
#

?

#

lets say i wanted a bot to only respond to the options rock, paper, scissors, lizard, spock
how would i do that using if else

#

idrk how discord bots work im really new to all of it

formal basin
cunning gulch
#

uhh

#

can i dm you what it looks like so far?

#

or is it ok to post big messages here

formal basin
#

!pastr

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.

cunning gulch
#
@bot.slash_command(
    name="rpsls",
    description="Play rock, paper, scissors, lizard, spock against a computer"
)
async def rps(interaction: nextcord.Interaction):
    channel = interaction.channel
    embed = nextcord.Embed(title="Rock Paper Scissors Lizard Spock", description="Choose rock, paper, scissors, lizard, or spock.", color=0x7c00ff)
    prompt_message = await interaction.send(embed=embed)
    timedoutembed = nextcord.Embed(title="Timed Out", description=f" <@{interaction.user.id}> The game has been canceled as you did not respond in time.", color=0xff0064)

    def check(m):
        return m.content in options and m.channel == channel and interaction.user.id == m.author.id

    try:
        msg = await bot.wait_for('message', check=check, timeout=30.0)
    except nextcord.NotFound:
        await interaction.followup.send(embed=timedoutembed)
        return
    except asyncio.TimeoutError:
        await interaction.followup.send(embed=timedoutembed)
        return

    computer = random.choice(options)

    if msg.content == computer:
        result_message = f"I chose {computer}. It's a tie."
        result_color = 0xffae42  # Yellow Orange
    elif msg.content == "rock" and computer == "scissors":
        result_message = f"I chose {computer}. You won."
        result_color = 0x00ff00  # Green
    elif msg.content == "paper" and computer == "rock":
        result_message = f"I chose {computer}. You won."
        result_color = 0x00ff00  # Green
    elif msg.content == "scissors" and computer == "paper":
        result_message = f"I chose {computer}. You won."
        result_color = 0x00ff00  # Green
    elif msg.content == "lizard" and computer == "spock":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    elif msg.content == "lizard" and computer == "paper":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    elif msg.content == "spock" and computer == "rock":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    elif msg.content == "spock" and computer == "scissors":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    elif msg.content == "paper" and computer == "spock":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    elif msg.content == "rock" and computer == "lizard":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    elif msg.content == "scissors" and computer == "lizard":
        result_message = f"I chose {computer}. You won"
        result_color = 0x00ff00  # Green
    else:
        result_message = f"I chose {computer}. You lose!"
        result_color = 0xff0000  # Red

    result_embed = nextcord.Embed(title="Rock Paper Scissors Lizard Spock", description=result_message, color=result_color)
    await interaction.send(embed=result_embed)
#

im trying to make it only respond to rock paper scissors lizard and spock

cunning gulch
#

my normal rps command uses the options method but idk how to make another one and not have them interfere

#

this one still has it there rn because i just copied the code to add lizard and spock im not finished yet

cunning gulch
#

oh

#

alr

slate swan
#

What does try do?

merry cliff
unkempt canyonBOT
#
Error handling

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

slate swan
#

He didn't use any except here why?

merry cliff
#

I don’t see a try either

#

So there’s no need for an except

slate swan
#

Oh sorry I'm a bit sleepy, this was another file

#

😅

merry cliff
#

Np

slate swan
#

I'm still watching the video, he hasn't done the except part yet

merry cliff
#

What year was the tutorial u are watching made

#

Or how many years ago

#

It looks a bit outdated

#

Also you kind of peaked your bot token

#

You should reset it ASAP from the dev portal @slate swan

slate swan
#

Oh no this isn't mine hehe

#

It's from a video I'm watching

merry cliff
#

Oh ok

slate swan
#

I'm away from my computer at the moment so I'm just trying to understand what's going on

slate swan
merry cliff
#

Wait what

slate swan
#

!await

merry cliff
#

That’s for asynchronous stuff

slate swan
merry cliff
#

So it can run at the same time as other stuff

slate swan
#

All I know is asynchronous means not happening at the same time

unkempt canyonBOT
#
Concurrency in Python

Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.

This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.

To call an async function we can either await it, or run it in an event loop which we get from asyncio.

To create a coroutine that can be used with asyncio we need to define a function using the async keyword:

async def main():
    await something_awaitable()

Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function

To run the top level async function from outside the event loop we need to use asyncio.run(), like this:

import asyncio

async def main():
    await something_awaitable()

asyncio.run(main())

Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().

To learn more about asyncio and its use, see the asyncio documentation.

slate swan
merry cliff
#

Not really

#

Basically it’s so that more than one person can use the bot at a time

#

But what are you trying to make specifically?

#

Video looks a bit odd for a basic bot

slate swan
#

It says easiest discord chatbot

#

I just want to work my way up because I just finished the basics of python, and all this stuff in Discord being introduced me such as API, async, await, threads, coroutines, had never been taught to me.

merry cliff
#

Maybe start off with a basic bot then, this one looks like it is teaching bad practices such as handling commands with on_message

slate swan
#

Oh

#

Where do I start with a basic bot

merry cliff
#

Which library are u using

slate swan
#

discord

merry cliff
slate swan
#

Yeah

merry cliff
#

Ok

#

I would teach you myself but I’m on phone rn so unless ur willing to wait like 3 hours then search on yt for a basic discord.py tutorial made in 2022 at the latest

slate swan
#

I can't stay up for 3 hours more. It's already late 😔

merry cliff
#

Yeah

#

Not a great idea

slate swan
#

I wouldn't use YT for discord.py personally, there are plenty of examples in their docs and on GitHub. A lot of the YT videos out there can be misleading

merry cliff
#

Yeah

merry cliff
slate swan
#

Thank you

#

I'm gonna go sleep now, good night

tall condor
#
@client.slash_command(name="registar", description="Regista o teu perfil na plataforma")
async def registar(ctx: discord.ApplicationContext):
    try:
        cursor.execute("SELECT userId FROM users WHERE userId = %s", [(ctx.author.id)])
        row = cursor.fetchone()
        if row is None:
            if ctx.author.nick is None:
                await ctx.respond("`` ❌ `` Não tens um apelido válido.")
            else:
                callsign = str(ctx.author.nick[0:3])
                nome = str(ctx.author.nick[6:100])
                for role in ctx.author.roles:
                    if str(role.id) in roles:
                        patente = str(role.id)
                    else:
                        continue
                cursor.execute("SELECT id FROM patentes WHERE role = %s", [(patente)])
                row = cursor.fetchone()
                if row is None:
                    await ctx.respond("`` ❌ `` Não tens uma patente válida 1.")
                else:
                    cursor.execute("INSERT INTO users (nome, patente, callsign, userId) VALUES (%s, %s, %s, %s)", [(nome), (row[0]), (callsign), (ctx.author.id)])
                    await ctx.respond("`` ✅ `` Perfil registado com sucesso.")
#

The code above is supposed to check if the user has a role that is listed in a list and if it has keeps the role id in a var, only that.

#

can someone help?

gilded oxide
#
    @commands.Cog.listener()
    async def on_reaction_add(self, reaction, user):
        print(f"guild length is {len(self.bot.guilds)}")
        for guild in self.bot.guilds:
            print(f"found guild: {guild.name}")
            for channel in guild.text_channels:
                print(f"{channel.name}: {channel.id}")
        #your starboard channel object (so you can send messages to that channel)
        starboard_channel = self.bot.get_channel(1111417168307961896)
        #an if statement which checks if the reaction was a ⭐
        if str(reaction.emoji) == "⭐":
        #a variable which stores the content of the message a star was given to
          message_content = reaction.message.content
          if message_content:
              # sends a message to the starboard channel with what the message said (won't do embeds for now, that's another story)
              await starboard_channel.send(message_content)
          elif reaction.message.embeds:
              await starboard_channel.send(embed=reaction.message.embeds[0])
          else:
              await starboard_channel.send(f"Someone starred something, here's the link: {reaction.message.jump_url}")``` How do I make an embed for the image, or text that was starred?
copper swallow
#

Hello can anyone help with py-cord

merry cliff
unkempt canyonBOT
#
Seek

In the context of a file object, the seek function changes the stream position to a given byte offset, with an optional argument of where to offset from. While you can find the official documentation here, it can be unclear how to actually use this feature, so keep reading to see examples on how to use it.

File named example:

foobar
spam eggs

Open file for reading in byte mode:

f = open('example', 'rb')

Note that stream positions start from 0 in much the same way that the index for a list does. If we do f.seek(3, 0), our stream position will move 3 bytes forward relative to the beginning of the stream. Now if we then did f.read(1) to read a single byte from where we are in the stream, it would return the string 'b' from the 'b' in 'foobar'. Notice that the 'b' is the 4th character. Also note that after we did f.read(1), we moved the stream position again 1 byte forward relative to the current position in the stream. So the stream position is now currently at position 4.

Now lets do f.seek(4, 1). This will move our stream position 4 bytes forward relative to our current position in the stream. Now if we did f.read(1), it would return the string 'p' from the 'p' in 'spam' on the next line. Note this time that the character at position 6 is the newline character '\n'.

Finally, lets do f.seek(-4, 2), moving our stream position backwards 4 bytes relative to the end of the stream. Now if we did f.read() to read everything after our position in the file, it would return the string 'eggs' and also move our stream position to the end of the file.

Note
• For the second argument in seek(), use os.SEEK_SET, os.SEEK_CUR, and os.SEEK_END in place of 0, 1, and 2 respectively.
os.SEEK_CUR is only usable when the file is in byte mode.

copper swallow
#

Hello can anyone help with py-cord

merry cliff
slate swan
#

okay, i think i'm close to what i desire:

#

but i don't know how to import client from my bot file

merry cliff
#

what lib is that?

merry cliff
#

my bad u didnt say

copper swallow
#

Hello can anyone help with py-cord

#

My slash command dont work

vale wing
# slate swan okay, i think i'm close to what i desire:

You should take a look at the example how it's done, right now it makes little sense and the modules naming convention is incorrect https://github.com/Exenifix/disnake-bot-template-postgres

GitHub

A template for speeding up development of discord bots using disnake and postgresql - GitHub - Exenifix/disnake-bot-template-postgres: A template for speeding up development of discord bots using d...

#

Specifically take a look at utils.database.Database, how it's connected to utils.bot.Bot and how it's used in cogs

west comet
#

Why does my code not work

vale wing
# west comet Why does my code not work

Uh dude we don't have technologies that make us able to read the whole problem from mind of a discord user remotely, could you please share your code, explain what doesn't work and provide errors traceback if applicable?

naive briar
#

🐈

slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
west comet
#

!d

unkempt canyonBOT
vale wing
#

🧐

strange barn
vale wing
west comet
#

Is there youtube tutorial for a button which opens a hidden channel

vale wing
#

There's no youtube tutorial for everything but there's documentation and examples

#
class HiddenChannelView(discord.ui.View):
    @discord.ui.button(label="Unlock")
async def unlock(self, interaction: discord.Interaction, button: discord.ui.Button):
    channel = interaction.guild.get_channel(...)
    await channel.set_permissions(interaction.user, read_messages=True)
    await interaction.response.send_message("Yes")


await send("Press button for secret channel access!", view=HiddenChannelView())```
#

Very basic example

vale wing
#

There are plenty of ticket bots on github ig

west comet
vale wing
#
GitHub

GitHub is where over 100 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and fea...

proven pendant
#

edit : Sorry for ping! I had a question regarding this thats why i had pinged you, but i figured it out now ^^

slate swan
#

🗿

slow wing
#

helo

#

python Main.py
Traceback (most recent call last):
File "Main.py", line 2, in <module>
from discord.ext import commands
ModuleNotFoundError: No module named 'discord'
exit status 1

when i run import discord in replit

#

it gives me this shit someone hallpppppppp

slow wing
#

did

#

pip install discord
An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'in-tree-build')

slate swan
#

@slow wing do

#

Ig

slow wing
#

i got discord in replit

#

still its saying that

slate swan
#

Hm

#

Make new repl then

slow wing
#

hm okok lets try

#

Traceback (most recent call last):
File "main.py", line 18, in <module>
import discord
ModuleNotFoundError: No module named 'discord'

#

@still plover

#

man u there @still plover

slate swan
#

No need to spam ping people, we're not your personal assistants

slow wing
#

ok

#

sorrry

slate swan
#
python -m pip uninstall discord
python -m pip install discord.py
python main.py
slow wing
#

An error occurred during configuration: option use-feature: invalid choice: 'content-addressable-pool' (choose from '2020-resolver', 'fast-deps', 'in-tree-build')

slate swan
#

Re-install pip

slow wing
#

in replit how to

slate swan
#

Or delete the entire conf file

#

replit e_skulllaugh

slow wing
#

woah nice skull

slate swan
#

Better to ask them out, not sure how they handle pip and python packages

slow wing
#

ahh idk anymore leave it

slate swan
#

You can try to add a requirements.txt file and write discord.py in it

#

Maybe replit auto-installs

slow wing
#

did that

#

still not working

slate swan
#

Yeah then replit skill issue, should ask them

#

Shouldn't use it either way

slow wing
#

hmmmm

still plover
#

Copy code

#

And do in new project

naive briar
slow wing
#

yes theres file named poetry

naive briar
#

So, just poetry add discord.py or literally just use their packages tab

slow wing
#

[[package]]
category = "main"
description = "A mirror package for discord.py. Please install that instead."
name = "discord.py"
optional = false
python-versions = "*"
version = "1.0.1"

#

then this

Replit: Updating package configuration

--> poetry remove discord
exec: "poetry": executable file not found in $PATH

Replit: Package operation failed.

#

if i try to remove the existing discord

vale wing
#

Just accept that replit took the L and switch to VSC or pycharm

#

Or notepad if you are real pro

slate swan
#

how do I run my discord bot

#
python3 zephyrith.py

Doesn't work

#

Error code:

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
slate swan
#

only true pros

vocal snow
slow wing
#

what SCcatVIBINGcry

slate swan
#

doesn't work

slow wing
#

i closed all the stuff out of frustration

#

btw tell me how

#

thats some public code btw

slate swan
slow wing
#

i was trying to run it

#

but cant

#

ok

slate swan
#
client = commands.Bot(command_prefix = '!')

@client.event
async def on_ready():
    print("Zephyrith is active.")
    print("--------------------")

@client.command()
async def hello(ctx):
    await ctx.send("Hello")

client.run(TOKEN)

Error Code:

client = commands.Bot(command_prefix = '!')
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'

What are intents

slow wing
#

stonk

slate swan
#

!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.

slate swan
#

The shared IP part is probably the most important point

#

As well as underpowered machines but yeah, if you make some private bot it's not that relevant eventually

slow wing
#

so i copy everything that person uploaded on replit and past it on my computer and run it?

slate swan
#

I'm watching a tutorial

oak warren
#

i mean its just a variable

slate swan
#

I know it doesn't make sense, but it's trial and error 😦

oak warren
#

i have told it multiple times here already

vocal snow
#

discord.py tutorials are usually outdated and the ones on youtube are infamous for their bad quality

oak warren
#

i know pep and all that but still variable is a variable

vocal snow
slate swan
#

I only know the basics of python such as for loops, while loops, 2D arrays, arrays, and functions

#

What do I learn

#

what's OOP

oak warren
# vocal snow that does not mean you should call apples oranges

it depends on the programmer with what they want to call it

I get its a good practice to name it correctly for future and code sharing purposes but while you are starting just to be comfortable you should name it as you want so that you can understand what you are doing and later on update it

oak warren
slate swan
#

Oh, do you have any recommendations

vocal snow
north kiln
oak warren
#

i was here to ask about how to go about with using cooldowns in databases

slate swan
#

After I finish OOP what do I do

vocal snow
#

I would recommend understanding the async/await pattern, that will be quite useful

slate swan
vocal snow
#

they are keywords, not functions

slate swan
#

oh what do the keywords do

oak warren
#

yea i know the difference but again most are gonna follow an outdated tutorial so it really wont matter at this point sadly

oak warren
#

so i actually wanted 2 commands one slash and one prefix both in different files to have the same cooldown because it replies to one database but i asked elsewhere and i found no solution so i thought to moving the cooldown from the default system to a database

#

command and no hybrid because i am not using discord.py i am using disnake

#

i dont want to learn tree commands

slate swan
#

Guys, coroutines are functions that can be stopped and resumed when executed right?

oak warren
#

yes this will not work for 2 different commands in 2 different files.

#

more specfically 2 different types of commands

#

look the prefix and the slash command does the same thing

#

thats why i want to make a database for cooldown

vale wing
#

Disnake's pretty much the same

#

Except the import

oak warren
#

my god..

#

i have a cooldown i just want to convert it to a database based cooldown

north kiln
#

I mean how would a database have cool down built in

oak warren
#

thats the reason i am asking

vocal snow
vocal snow
oak warren
#

again not for 2 different type of commands

vocal snow
#

read again. It accepts a callable that returns the cooldown.

#

and I believe disnake has no seperate module for app commands like dpy has

oak warren
#

let me repeat it once more

i have a prefix command and a slash command that do the same thing and same cooldown but if one is used the other can be too and i like to keep my code clean so these are in 2 different files

i tried multiple methods of linking the cooldown ( inbuilt to the library ) and it didnt work and figured it will be easier to just move the cooldown to a database because i already have one

#

and i want to know how should i be doing it " the right way "

slate swan
#

guys

#

async is the keyword to make a coroutine function?

vocal snow
#

cooldowns = {(user_id, command_name): datetime_when_cd_expires}
#

a simple mapping like that, then you can have a check on your commands that make a simple dict lookup

slate swan
#

!e print('hi')

#

!e print('test')

north kiln
#

this is not #bot-commands

vocal snow
oak warren
#

okay i shall try that thank you

#

i understand what you mean now

#

i was trying with the message and not command name

vocal snow
#

I just hope disnake supports checks on slash commands

oak warren
#

it does

slate swan
#

Hey what is instance considered to be in programming

unkempt canyonBOT
#
Classes

Classes are used to create objects that have specific behavior.

Every object in python has a class, including lists, dictionaries and even numbers. Using a class to group code and data like this is the foundation of Object Oriented Programming. Classes allow you to expose a simple, consistent interface while hiding the more complicated details. This simplifies the rest of your program and makes it easier to separately maintain and debug each component.

Here is an example class:

class Foo:
    def __init__(self, somedata):
        self.my_attrib = somedata

    def show(self):
        print(self.my_attrib)

To use a class, you need to instantiate it. The following creates a new object named bar, with Foo as its class.

bar = Foo('data')
bar.show()

We can access any of Foo's methods via bar.my_method(), and access any of bars data via bar.my_attribute.

vocal snow
#

in the second example, bar is an instance of Foo

#

the same way 10 is an instance of int, or "hello world" is an instance of str

slate swan
#

bar is an instance of Foo?

vocal snow
#

yes

#

bar is an instance of the class Foo

#

bar = Foo('data')

slate swan
#

Oh I don't know what Foo is

vocal snow
slate swan
#

So classes give behavior to instances

#

what's foo doing

vocal snow
#

there is no foo

slate swan
#

Foo

vocal snow
#

what about Foo

#

it's code is right there

slate swan
#

I've never seen someone in my life write a function like this init

vocal snow
#

it takes some data, assigns it as an attribute and has a method that prints that attribute

vocal snow
slate swan
#

okay

vocal snow
#

as well as dunder methods and other OO concepts like inheritance

slate swan
#

I thought I was missing out or something

#

cause he said Instantiating

#

I've never learnt that thing

#

I had to search it up

#

Thanks for the help though

#

Hey @vocal snow

#

In python when I'm using an instance and then a dot after it then another word. Does that mean I'm creating new fields in a database

#

or is the whole thing just a variable

vocal snow
#

think of it as a variable which is attached to the instance

slate swan
#

oh it just reminded me of SQL

#

thanks

vocal snow
#

you could think of it as a table, but the data isn't actually persistent

#

consider a table Employee: ```sql
CREATE TABLE Employee (
id INTEGER PRIMARY KEY,
name TEXT
);

#

this is similar to the class definition: ```py
class Employee:
def init(self, id: int, name: str):
self.id = id
self.name = name

#

in the table, each row (called a record) is like an instance

marble wasp
#

why doesnt my bot give roles or remove them on update, nor posting embeds into specified channel

vocal snow
#

do you have member intents enabled?

slate swan
marble wasp
vocal snow
naive briar
#

!e

class AClass:
    def __init__(self, arg):
        pass

a = AClass(123)
print(a.arg)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     print(a.arg)
004 |           ^^^^^
005 | AttributeError: 'AClass' object has no attribute 'arg'
twilit grotto
#

i believe you have to do
self.arg = arg

#

then you can access it properly.

marble wasp
#
@client.event
async def on_member_update(before, after):
    if isinstance(after.activity, discord.CustomActivity) and after.activity.name == "discord link":
        role = discord.utils.get(after.guild.roles, name="Your Role Name")
        await after.add_roles(role)

        channel = bot.get_channel(channel_id)
        embed = discord.Embed(title="Custom Activity Update", description=f"User {after.name} now has the custom activity 'discord link'.", color=discord.Color.green())
        await channel.send(embed=embed)
    elif isinstance(before.activity, discord.CustomActivity) and before.activity.name == "discord link":
        role = discord.utils.get(after.guild.roles, name="Your Role Name")
        await after.remove_roles(role)

        channel = bot.get_channel(CHANNEL_ID)
        embed = discord.Embed(title="Custom Activity Update", description=f"User {after.name} no longer has the custom activity 'discord link'.", color=discord.Color.red())
        await channel.send(embed=embed)

doenst give role PepeShrug nor posting embeds

naive briar
slate swan
#

I don't understand, why is there first argument/instance considered to be a variable

vocal snow
slate swan
#

Why is it like that

vocal snow
naive briar
marble wasp
#

oh right

slate swan
#

the function was called after the variable, how does the function know that emp_1 is self

#

is it just a thing we do

vocal snow
#

emp_1 is just a name given to the instance afterwards

#

Employee('Corey', 'Schafer', 50000) is itself the instance

slate swan
#

where is the argument for self?

#

!self

unkempt canyonBOT
#
Class instance

When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.

class Foo:
    def bar(self):
        print('bar')

    def spam(self, eggs):
        print(eggs)

foo = Foo()

If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.

Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').

Why is this useful?

Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.

Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.

slate swan
#

Self is passed by python lets say

vocal snow
#

also should note that Employee('Corey', 'Schafer', 50000) doesn't call the __init__ first, it calls __new__ which creates the object, calls the _init_ and returns the object

#

although for now you can just think of it as python passing self implicitly

slate swan
#

So to summarize it self is an instance used to call methods in a class

#

because methods in a class can't be called directly without an instance which builds a link to call the method

#

am I right?

#

self is instance object in class

naive briar
slate swan
#

I'm now confused again

naive briar
slate swan
# slate swan

isn't emp_1 a variable that's sent as an argument to self

#

not really

#

I really don't understand then

#

So, what's being sent to self

naive briar
#

What's so confusing

naive briar
slate swan
# slate swan

There are 4 arguments here, the guy calls the function but there are 3 arguments

#

what part is the instance

naive briar
#

self

slate swan
#

how does the computer know that self isn't Corey or Test

#

Cause its 1st argument always

#

I don't really understand

#

he inputted 3 arguments but the function has 4 arguments in the parameters

naive briar
#

Sigh

slate swan
#

Does it magically know

#

1st argument is always instance

#

or is there hidden code which does that

#

Cause self is passed automatically as first argument always in methods

naive briar
#

Python does it in the background

slate swan
#

or does this apply to every class function

#

Every method in class gets self as first parameter

naive briar
#

To every method, except staticmethods

slate swan
#

Not only init

#

Exceptions are staticmethods and classmethods

slate swan
# slate swan

in

emp_1 = Employee('Corey', 'Schafer', 50000)

Would self become emp_1

#

not the variable

#

but inherit the name emp_1

slate swan
#

thank you

slate swan
slate swan
#

thank you

#

so are classes just used to store functions?

slate swan
# slate swan so are classes just used to store functions?

Classes are primarily used to create your own type of objects, with their own set of attributes, and their own set of methods.

Yes, they can also be used to "organise" functions in a way.
You can decorate a function within a class using the @classmethod decorator and you'd then call that method on the class itself, rather than having to create an instance of the class and call the method on the instance. But be mindful that classmethods use the cls parameter in place of self.

slate swan
slate swan
#

Yeah you're right

#

thanks

#

so can i say attributes are like properties?

#

Properties are something slightly different, so call them attributes

slate swan
#

ok

slate swan
#

Yo @slate swan @vocal snow

#

Check out what I did with Class and Instance variables

#

It's great to see people getting into new stuff and making it work, but maybe you missed the purpose of the #discord-bots channel

vocal snow
# slate swan

Just a tip, try to name your classes with PascalCase (it's just convention)

slate swan
#

Oh ok

#

thanks

west steeple
#

can someone tell me what Im doing wrong im trying to create a ticket bot

#

?

unkempt mauve
grim robin
#

does anyone else have an issue with activities not being returned when querying the API?
using discord.py and user.activity or user.activities (user is discord.Member) always returns ()
(intents are set to all() and intent.presence returns True when queried)

slate swan
#

Probably better not to cross-post in multiple servers but focus your question in one first

#

Can anyone see mine help post

slate swan
#

yepa CatJAM

north kiln
#

I don't even know what I did that my bot logging used to provide full tracebacks but now traceback.format_exc() just gives NoneType: None brainmon

formal basin
#
normalmsg = ['hello']
 res = f"Hello {message.author.mention}", f"Hi {message.author.mention}"
 if any (word in message.content.lower() for word in normalmsg):
       await message.channel.send(random.choices(res))
 
 if message.content.lower().startswith("hi"):
   await message.channel.send(random.choice(res))
``` my bot is sending ['Hi @formal basin']
#

instead of Hi @formal basin

north kiln
#

!d random.choices

unkempt canyonBOT
#

random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").

If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
north kiln
#

^^^

#

Returns a list

whole shoal
#

Why does this error occur?

#

Cause it ran fine for the first 15 iterations

formal basin
whole shoal
formal basin
whole shoal
#

Why did it not happen for the first 15 iterations then

formal basin
#

so you need to put the webhook token

formal basin
#

so you need to put a new token into it

whole shoal
#

Man im not even using webhook

formal basin
whole shoal
#
class No_prot_pot(discord.ui.View):
  #some unrelated code here

    
    async def on_timeout(self): 
        for item in self.children:
            item.disabled=True
        await self.message.edit(view=self)
hushed galleon
#

how long did you set your timeout?

#

and where do you assign message to?

#

cause i think that error message means your interaction has expired

whole shoal
whole shoal
whole shoal
hushed galleon
#

your interaction token hadnt yet expired

#

yeah i checked discord developers, 401 invalid webhook token is what you get when using an interaction past its 15 minute lifespan

upbeat badge
#

can anybody tell me how to implement RedPajama-INCITE-Chat-3B-v1 into the chatbot? it is basically a open source database

#

i am trying so hard but unable to do that

vocal snow
slate swan
#

is there a way to get thsi to send as an embed? or do interactions have to be normal messages


class ApplyModal(discord.ui.Modal, title="Builder"):
    t = discord.ui.TextInput(label="Embed Title", placeholder="   ", style=discord.TextStyle.short)
    v = discord.ui.TextInput(label="Embed Description", placeholder="    ", style=discord.TextStyle.long)
    n = discord.ui.TextInput(label="Image URL", placeholder="    ", style=discord.TextStyle.short)
    f = discord.ui.TextInput(label="Footer", placeholder="    ", style=discord.TextStyle.short)
    
    async def on_submit(self, interaction: Interaction):
        await interaction.response.send_message(f"Success!", ephemeral=True)
        
        channel = discord.utils.get(interaction.guild.channels, name="embed-test")
        
        embed = discord.Embed(name=f"{self.t}", color=discord.Color.random())
        embed.add_field(value=f"{self.v}")
        embed.set_image(url=f"{self.n}")
        embed.set_footer(text=f"{self.f}")
        await channel.send(embed=embed)
        
@client.tree.command(name="embed", description="Build an embed")
async def embed(interaction: discord.Interaction):
    await interaction.response.send_modal(ApplyModal())
whole shoal
# vocal snow how is `self.message` defined?
            else:
                selector_list=No_prot_pot(ctx,player_list)
            
                    
          
            embed102=discord.Embed(title=f'__**Round {client.round_info[ctx.guild.id]}**__',
                        description=f''
                        colour=discord.Colour.random())
            #embed.set_image(url="g")
            #ctx=await ctx.original_response()
            selector_list.message=await ctx.followup.send(embed=embed102, view=selector_list)
vocal snow
vocal snow
#

maybe just send a message to the channel directly

#

via interaction.channel.send

whole shoal
#

Will webhookmessage.fetch work?

#

new_message= await message.fetch()?

vocal snow
#

doubt so since it seems like discord invalidates the followup webhook itself after 15 minutes

whole shoal
slate swan
vocal snow
#

await interaction.response.send_message(embed=embed, ephemeral=True)

slate swan
#

ok ok

snow coral
#

i keep getting this error

TypeError: bad operand type for unary +: 'str'

#

im trying to get a random number, and have the bot say it

vocal snow
#

code please

snow coral
#

oh

snow coral
#

lemme get it

vocal snow
#

you have a comma after the string literal

#

and would recommend using an fstring

#

!fstring

unkempt canyonBOT
#
Format-strings

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

snow coral
#

tysm

#

how can i get the up arrow and down arrow reactions on the message below it

snow coral
vocal snow
#

channel.send will return the Message object, call add_reaction on that

swift acorn
#

How would I go about checking which invite code a member joined with in the on_member_join event?

vocal snow
#

although I really dislike how your code is structured, it only allows for one game session at a time

#

and if someone reacts with 👍 before the attribute is set then it's going to crash

#

you should just wait for a reaction_add event in the command

whole shoal
snow coral
#

i could try that

harsh marsh
#

hey

#

can I make embed pagination with this ?

shrewd apex
unkempt canyonBOT
#

A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.

shrewd apex
#

this one is good^^

harsh marsh
#

i arldydid with reaction

#

it is working good but I want to change with slash command

#

so the code is no longer the same

#

button are more appropriate but more difficult too

ebon island
#

Has anyone here fully set up Discord.py 2.0 and wavelink along with working slash commands and preferably also that menu pagination and would be willing to spend an hour tops setting up a base project doing all of the above? I'd be willing to pay 50$ for a confident and capable hand in it. I am a full stack software engineer and have an existing large-scale project using disnake[discord] and wavelink but the disnake[discord] wrapper is no longer supported and refactoring has been a big roadblock so just a guiding hand in terms of the syntax and all of that to run through it quickly would be very helpful. I have looked at the documentation and understand it but I want someone knowledgeable who has built a project at scale to show me if there are any shortcuts or optimizations I would be missing and things of that nature that might make the process of making the transition easier and less stressful since it is already going to be a large refactor. Let me know and I will be happy to pay upon completion of the above described effort!

hushed galleon
unkempt canyonBOT
slate swan
#

does anyone know how to send a color with embed in webhooks? i have this so far

#
            if embed:
                data["embeds"] = [
                    {
                        "description": description,
                        "title": title,
                    }
                ]```
whole shoal
#

color=discord.Color.colname()

slate swan
#

i literally just said through webhooks

slate swan
#

"color": 10201343 (or whatever integer from 0 to 16777215) sets the embed colour if I remember correct

thorn leaf
#

It's the same thing as putting the number for the same color there

#

Oh, you're confused about the key name

naive briar
#

They're probably talking about sending a webhook message without a client library

snow coral
#

i keep getting this error

NameError: name 'message' is not defined

sick birch
snow coral
#

okay

#

wait

sick birch
#

And which line is the error happening in?

snow coral
#

@sick birch wrong link

sick birch
#

No worries feel free to send the corrected link

snow coral
sick birch
snow coral
#

lemme try that

sick birch
#

on_ready isn't good for much more than simply printing out that you're logged in (like you already have done)

snow coral
#

now i got IndentationError: unindent does not match any outer indentation level

sick birch
#

!indents

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

sick birch
#

Python works off indentation - make sure it's consistent

#

E.g everything you want to be part of an if statement should be indented one step further:

if some_condition:
  something # indented to be inside if statement
  something_else # indented to be inside if statement
not_indented # not indented, it's not part of the if statement
snow coral
#

new error
SyntaxError: 'await' outside function

sick birch
#

You may have indented it too far now

#

The if should be indented one time so it's inside on_message
If you indent it 0 times, then it's outside the on_message

#

E.g

async def on_message():
  if some_condition:
    do something
  do more stuff
snow coral
#

and im still getting it

sick birch
#

Can you paste the whole function?

snow coral
#
async def on_message(message):
    if message.author == client.user:
        return

if '$hilo' in message.content.lower():
  random_number = str(random.randint(1, 100))

if message.content.startswith('$hilo'):
  sent_message = await message.channel.send('Welcome to HiLo! Would you like to start a game?')
  await sent_message.add_reaction('👍')
  await sent_message.add_reaction('👎')

  client.game_message_id = sent_message.id
sick birch
#

Yeah notice how everything starting with if '$hilo' in message.content.lower() isn't indented?

#

That means it's not part of the on_message function

snow coral
#

ohhhh

sick birch
#

If you're on VSCode you can pretty much highlight the entire section that's not indented, press tab and VSCode will indent all of it for you

snow coral
#

im on replit

sick birch
#

I don't use replit but it shouldn't be too difficult to do it by hand either

snow coral
#

im just confused on where to indent and where not to

twilit grotto
#
@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if '$hilo' in message.content.lower():
        random_number = str(random.randint(1, 100))

    if message.content.startswith('$hilo'):
        sent_message = await message.channel.send('Welcome to HiLo! Would you like to start a game?')
        await sent_message.add_reaction('👍')
        await sent_message.add_reaction('👎')

    client.game_message_id = sent_message.id
#

there you go

naive briar
#

How hard can it be

sick birch
#

I'm trying to guide them to getting it right on their own

snow coral
#

wait, i think i got it

#
async def on_message(message):
  if message.author == client.user:
    return

    if '$hilo' in message.content.lower():
      random_number = str(random.randint(1, 100))

    if message.content.startswith('$hilo'):
      sent_message = await message.channel.send('Welcome to HiLo! Would you like to start a game?')
      await sent_message.add_reaction('👍')
      await sent_message.add_reaction('👎')

  client.game_message_id = sent_message.id```
this is working
sick birch
#

Syntactically?

#

Or does it actually work when you run it

snow coral
sick birch
#

What error?

naive briar
#

!e 🐈

if False:
    cat = 0

print(cat)
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     print(cat)
004 |           ^^^
005 | NameError: name 'cat' is not defined