#discord-bots

1 messages · Page 254 of 1

slate swan
#

Programming feels like a lucky guess game

#

you can choose names for your varriables but not for predefined classes

alpine oar
slate swan
#

Though it isn't

alpine oar
#

i forgot a whole abt python

slate swan
#

If the class is named Button

alpine oar
#

me dumb as hell

alpine oar
slate swan
#

You may want to create a variable button that is an instance of Button

#

So button = Button(...), just like that

#

if you dont understand basic python knowledge why are you starting a discord bot project its not a good idea for a beginner

alpine oar
slate swan
#

Forgetting how to create a variable is probably some sign of Alzheimer

alpine oar
left dew
#

hello, i keep getting weird webhook errors, but i dont use webhooks. it doesnt allow some users to interact with a button:

    data = await adapter.edit_original_interaction_response(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found 
(error code: 10015): Unknown Webhook```
slate swan
#

i don't use webhooks

Yes you do, interaction responses are webhooks

alpine oar
#

it was so long ago i coded

left dew
slate swan
slate swan
alpine oar
left dew
#

when a user presses the button, it sends en ephmeral message whilst its thinking then edits it when the thinking is done, does it edit it too quickly?

alpine oar
#

i think ima make an whole new bot and start over so my mind refreshes

slate swan
#

I'd go over Python basics again before doing that

alpine oar
#

yea ofc

left dew
#

of the button?

slate swan
#

yes

calm timber
#

@thin raft it works!! Thank You!!

slate swan
#

first thing that i notice is that arguments order is wrong in this line async def button_callback2(self, button, interaction_1st:discord.Interaction):

#

interaction should be before button

left dew
#

okay

waxen notch
#

I need help. I'm trying to make a sweepstakes bot for my Discord server, but when I add the giveaway feature I didn't want to start because of a bug in the console.

console:

Traceback (most recent call last): File "main.py", line 1, in <module> import discord File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/discord/__init__.py", line 25, in <module> from .client import Client File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/discord/client.py", line 27, in <module> import asyncio File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module> from .base_events import * File "/home/runner/RustyDirtyDefinitions/venv/lib/python3.8/site-packages/asyncio/base_events.py", line 296 future = tasks.async(future, loop=self)

slate swan
left dew
#
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Administrator\Desktop\sparkles_bot\main.py", line 315, in button_callback2
    await interaction_1st.edit_original_response(content=f"**Slow Down! You're on cooldown.**")
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 428, in edit_original_response
    data = await adapter.edit_original_interaction_response(
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
slate swan
#

possibly cause you are using edit_original_response

left dew
#

is there something i should change it to?

slate swan
#

you may want to try using interaction.response.send_message() or if it does not work interaction.followup.send()

left dew
#
await interaction_1st.response.send_message(content=f"**Slow Down! You're on cooldown.**")```
#

that?

left dew
#

okay

left dew
slate swan
#

maybe other users are not on cooldown

waxen notch
#

The code is very extensive

slate swan
#

then show what you added and made it stop working

waxen notch
#

I don´t can pass you

#

The code is very extensive

#

+2,000 caracters

upbeat ice
waxen notch
#

Thank you

slate swan
#

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

waxen notch
upbeat ice
slate swan
#

bot.loop.create_task(winner_picker()) pretty sure this may cause error but will know when you provide traceback

slate swan
slate swan
open narwhal
#

is there a limit to how many options can be shown in the options section, such as the add and rename option

upbeat ice
#

25

open narwhal
#

thank you very much

slate swan
open narwhal
#

tyty ill do that

slate swan
#

choices? array of application command option choice Choices for STRING, INTEGER, and NUMBER types for the user to pick from, max 25

open narwhal
#

but its 25 at a time right, there can be more than 25 options but it will only render 25 at a time. Am I correct

upbeat ice
#

Last I remember if you try to render more than 25 it errors

slate swan
#

when it says max 25 it is max

open narwhal
#

when you type into the field and the options change, is that considered different thing from the pic I posted

upbeat ice
#

It's the same field so it as well can only show 25

#

You can create an auto complete function and show 25 different options as the user enters text

slate swan
#

i belive you can have more than 25 when you use autocomplete

#

Same field, so no, still 25

#

26 🧐

open narwhal
#

I see, thank you guys

#

wait I think I should mention the use case in case you guys have an recommendations

I wanted a command like the screenshot I posted above
and when the user types something, matching names from a list of around 1.2k unique strings show up.

Is there any way to make this work

slate swan
#

Hello, just wanted to check if this was an appropriate place to ask for some guidance on a problem I have with a discord bot I've put together?

#

For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.

Not sure

#

To be honest the fact I can't read has probably contributed to the issue I'm having

#

Throw it away and we'll see bravemmlol

upbeat ice
open narwhal
slate swan
open narwhal
#

sorry I missed that, my bad 🥴

slate swan
#

Trying to think how to word my question. Basically I have a really simple bot, one of its functions is to pull data from a small dataset when a user uses a command. The dataset consists of a list of 'players' and then 5 different stats for each player.

The command '!fact' responds with a random player and a random stat for that player

'!fact (player name)' responds with a random stat for that specific player

'!fact (player name) (stat)' responds with the specific stat for the specific player.

The problem I'm having is that there are two stats that are two words, I don't know what is causing the issue but when I use the command '!fact (player name) (two-word stat)' The bot responds to say that, paraphrasing, "(player name two-word stat) does not exist".

I.e. the bot thinks I'm looking for a player with the name of all four words combined.

All the single-word stats work fine, even for players with more than 3 names.

I've tried fiddling about with chatGPT to see if that could help but just went round in circles. I've tried making the two-word stats one word then creating a dictionary so that when the user puts the two words in it will know what they're after and it will format the response correctly. But that didn't work either.

#

I'm a complete novice, hence the probably daft question, apologies.

slate swan
#

Is there a way to post it in a proper.. like.. format?

#

!paste yep

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.

slate swan
midnight oracle
slate swan
#

Cheers, I used the paste thing above so it's now in that link

midnight oracle
#

Oh, okay

upbeat ice
#

What are you passing in for query

slate swan
#

Sorry, I don't know what that means 🙃

midnight oracle
#

hehehe

slate swan
#

Nextcord good ?

#

first project, haven't done any theory since about 2 hours on codecademy 3 years ago

upbeat ice
sick birch
slate swan
#

or just (player name)

#

Or no arguments (which just picks a random player and random stat)

slate swan
sick birch
#

Documentation?

slate swan
sick birch
#

Hm. You might prefer disnake

Though personally I would recommend discord.py (even if the docs aren't very good) since there's more support from more people that use it

upbeat ice
slate swan
#

Ok that makes sense

midnight oracle
#

How difficult is it to make a moderation bot?

#

Like, for a 50 people server

upbeat ice
slate swan
upbeat ice
#

Anywhere from very easy to intermediate

midnight oracle
#

Sounds like something fun to try, uh?

slate swan
slate swan
upbeat ice
midnight oracle
#

What you think?

#

Eating the documentation xd

upbeat ice
#

Yeah I think that would be a good challenge for learning

midnight oracle
#

:D

upbeat ice
#

Look into databases

midnight oracle
#

:D -> your profile face :D

midnight oracle
#

Jsons could do it?

upbeat ice
#

You'll need a database to manage mutes and bans

#

JSON "could" do it but it doesn't mean it should lol

midnight oracle
#

Yeah xD

#

But, but I will test it in a friend's server, no more than 50 as I said, so I guess I can try first with JSON

#

And then, Docker maybe?

#

(noob moment ^^)

upbeat ice
#

For databases I recommend PostgreSQL or SQLite

midnight oracle
#

Never used it before

#

Something new to learn

#

great :v

upbeat ice
#

Exactly!

slate swan
potent spear
#

where your command arguments would look like
ctx, player, *, stat
instead of
ctx, player, stat

#

which means that when using
!fact <player> eats beans daily
when using the first example arguments
stat will be equal to "eats beans daily"
when using the second example arguments
stat will be equal to "eats"

slate swan
#

Thanks, yea I think I already have that operator;

async def fact(ctx, *, query=None):

slate swan
#

command in cogs don't work and there is no problem

potent spear
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.

potent spear
#

all commands in that cog? or just 1?
are you sure your cog is even loaded?

main wind
#

stop askin dumb questions just google it lol

slate swan
#

is there an example for a .py

that opens a modal when a button is clicked?

sick birch
#

I have the same system for some of my internal tooling

slate swan
sick birch
#

You just do the interaction.response.send_modal stuff but inside the button callback

slate swan
#

something like this?

#

class Test(discord.ui.Modal):
    def __init__(self):
        super().init__()
        
    @discord.ui.button(label="Test", style=discord.ButtonStyle.red)
    async def testbutton(self, interaction: discord.Interaction, button:discord.ui.Button):
        await interaction.response.send_modal(Test())

@client.command()
@commands.has_permissions(administrator=True)
async def supportsystem(ctx):
    view = Test
    about = discord.Embed(title="Moon Solutions", description="This is our placeholder for our support system while we work on it!")
    about.set_thumbnail(url="https://cdn.discordapp.com/attachments/1117391977516896370/1120006300835778641/6665-moon-foil-balloon.png")
    about.set_footer(text="Moon Solutions")
    await ctx.send(embed=about, view=view())

sick birch
#

You need 2 separate classes: one for the view containing the button, and one for the modal

winter hare
turbid condor
#

That is what the error is telling u

winter hare
#

so im not setting it up right?

#
    await client.add_cog(cog2(client))
turbid condor
#

This is correct tho

#

Make sure that this inline with your class cog2

winter hare
#

does it have to be within the class?

#

its aligned with the class cog2

turbid condor
#

Then it's ok

#

Is your other cog loading?

winter hare
#

no

#

im confused because it worked before

naive briar
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

winter hare
naive briar
#

Is your rip command inside a class (or cog)

#

If it is, you need to add a self argument as the first parameter

winter hare
#

the commands name is test and it is inside a cog and self is the first parameter

#
    def __init__(self, client: commands.Bot):
        self.client = client

    @app_commands.command(name='test', description='interesting')
    async def test(interaction: discord.Interaction):
        await interaction.response.send_message(content='interesting')
naive briar
#

Really?

naive briar
turbid condor
#

And in here too no self in your function

winter hare
#

where exactly should i put it?

naive briar
#

As the first parameter??

async def test(self, interaction):
    ...
turbid condor
#

Before interaction:discord.Interaction it's a required arg for cogs

naive briar
#

I already said it

winter hare
naive briar
#

Show your full code of the extension file

winter hare
#
import discord
from discord.ext import commands
from discord import app_commands



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

    @app_commands.command(name='test', description='interesting')
    async def tests(self, interaction: discord.Interaction):
        await interaction.response.send_message(content='interesting')



async def setup(client: commands.Bot) -> None:
    await client.add_cog(cog2(client))

winter hare
naive briar
#

What file is this from?

#

Because your traceback came from cog1.py

winter hare
#

Do u need the main

silk wasp
# winter hare ``` import discord from discord.ext import commands from discord import app_comm...

this might be a issue since you are using .ext import commands and app_commands i would suggest this code instead

import discord
from discord.ext import commands


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

    @discord.slash_command(
        name='test',
        description='interesting'
    )
    async def tests(self, interaction: commands.Interaction):
        await interaction.response.send_message(content='interesting')


def setup(client: commands.Bot):
    client.add_cog(Cog2(client))
naive briar
#

There is no such thing

#

!d discord.app_commands.command there's only this

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
naive briar
silk wasp
#

sorry my mistake

#

or instead of slash command, you could use regular command such as the following:

import discord
from discord.ext import commands


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

    @commands.command(
        name='test',
        description='interesting'
    )
    async def tests(self, ctx):
        await ctx.response.send_message(content='interesting')


def setup(client: commands.Bot):
    client.add_cog(Cog2(client))
naive briar
#

Regular commands used contexts, not interactions

winter hare
#

Is there a proper extension file

naive briar
silk wasp
#

i usees nextcord lib

naive briar
naive briar
winter hare
#

So do I add that in the main or the extension file

naive briar
#

What

#

I just asked for the code in the file

winter hare
naive briar
#

The cog1.py file, or is that its contents?

winter hare
#

I'm confused are you asking for the full code?

#

That's the only code in the file

silk wasp
#

hey could you clue me in on what problem you are facing?

#

because after reading your previous message im lost

winter hare
#

my other cog is almost the complete same and it works fine

silk wasp
#

alright, do you have a function or a for loop to load all your cogs file in your main.py?

winter hare
#
self.cogslist = ['cog1','cog2']
    
    
    async def setup_hook(self):
         for ext in self.cogslist:
            await self.load_extension(ext)
silk wasp
#

could i see your working cogs full code ? and your cog that not working full code?

silk wasp
naive briar
#

No point

naive briar
silk wasp
#

tbh at this point i would rather you screenshare your project and see what wrong with it

potent spear
#

his project is rather small, just making him share the code of both the cogs he's trying to load is good enough

potent spear
#

he's either not showing us the correct file, or just not saving

#

I opt the former

winter hare
winter hare
winter hare
#

im sorry im giving yall a hard time

potent spear
#

alr, can you only load 1 cog and see what that brings?

silk wasp
silk wasp
#

i think ik why

potent spear
#

your main file (containing your bot) and your cogs are all in the same folder, right?

silk wasp
#

because you define your command for test and tests as the same name name='test'

potent spear
#

good remark

#

but that shouldn't really give an error I'd think

naive briar
#

The error they sent said that the error came from a function named rip 🤷

potent spear
#

seems like a saving issue then

naive briar
#

But the code they sent doesn't match it

winter hare
#
Traceback (most recent call last):
  File "c:\Users\trace\Desktop\MU LFG\.vscode\main.py", line 49, in <module>
    client.run('')
  File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)

  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 649, in run_until_complete
    return future.result()
  File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 621, in login
    await self.setup_hook()
  File "c:\Users\trace\Desktop\MU LFG\.vscode\main.py", line 23, in setup_hook
    await self.load_extension(ext)
  File "C:\Users\trace\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1011, in load_extension
    raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cog1' could not be loaded.```
potent spear
#

because that seems to be like a no

#

not even sure why you'd put your main file in the .vscode folder in the first place...

silk wasp
#

ExtensionNotFound(name)

#

is your file name same as the one you put in the list

winter hare
silk wasp
potent spear
winter hare
potent spear
#

you can, don't worry about it

silk wasp
#

u can have the file name and class name be the same

#

im just askign is your name of your cog 1 file this: cog1.py

silk wasp
#

under self.cogslist = ['cog1', 'cog2']

winter hare
#

yes?

silk wasp
#

ok

#

is your cog1 file and your main.py same directory?

winter hare
#

yes

silk wasp
#

ok

winter hare
silk wasp
#

wait

#

quick question have you put your token in?

winter hare
#

in the file or in the haste bin?

silk wasp
#

in the file under:

client.run(TOKEN)

#

token will be your discord bot token string

winter hare
#

yes i just removed it from the hastebin

silk wasp
#

ah ok

naive briar
winter hare
potent spear
potent spear
#

I bet my money on

  1. he's either never saving
  2. running a completely different file
#

he just has to show his project's file tree structure

#

do the command tree in your project folder & show us the output

winter hare
silk wasp
#

it okay.-.

winter hare
#

i didnt save 😢

silk wasp
#

.-.

potent spear
#

jackpot

silk wasp
#

pain

winter hare
#

im sorry

potent spear
#

gl hf!

silk wasp
#

hahaha it okay

winter hare
#

ok quick question is there a way to add multiple commands under a cog?

naive briar
#

Just add more

#
class Cog(commands.Cog):
    ...

    @commands.command()
    async def command_1(self, ctx):
        ...

    @commands.command()
    async def command_2(self, ctx):
        ...

    @commands.command()
    async def command_3(self, ctx):
        ...
silk wasp
#

personally i would just put all my cogs in a 'cog' folder to be organised

real harness
#

!e

print(chr(1423)
unkempt canyonBOT
#

@real harness :x: Your 3.11 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     print(chr(1423)
003 |          ^
004 | SyntaxError: '(' was never closed
real harness
#

!e

print(chr(1423))
unkempt canyonBOT
#

@real harness :white_check_mark: Your 3.11 eval job has completed with return code 0.

֏
fiery jetty
#

!e
print(chr(1423))

slate swan
#

Me when people use random commands

fiery jetty
#

Sorry

vale wing
slate swan
#

And I thought cogs were gears ⚙️

slate swan
#

technically are.

#

Relieved

slate swan
glad cradle
#

plugins when

torpid frigate
#

Quick question about ephemeral interactions.

#
async def my_command(ctx):
    await ctx.send('This is a private message.', ephemeral=True)
#

this test function doesnt work for me when a user does $test

slate swan
#

A bot command is not an interaction

torpid frigate
#

i understand that emphereal only works with slash commands, buttons etc? is there a way to make it work with my $ commands?

slate swan
#

Interactions are slash commands, buttons, etc.

#

And ephemeral only works with responses to interactions

#

You can't send an ephemeral message just like that

torpid frigate
#

hmm. For some context I have a command called $leaderboard, it shows the scores for the user who uses it. I got it working where the bot DMs the user but I felt that was a little annoying. Was wondering if there was a way for only the user to see the scores in the same channel/chat

slate swan
#

No

#

use slash commands and you're good to go

torpid frigate
#

aight ty will switch over to / from $ 👍

slate swan
#

🫢 ephemeral doesn't have to be slash commands btw.

#

That's exactly what was said above, thanks

tidal folio
#

Why Errol?

slate swan
#

!indent

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

tidal folio
slate swan
#

Yes just did

#

Read the embed

tidal folio
jade flare
# tidal folio

it means if you miss out on adding tabs or spaces between your lines of code you will get this error

jade flare
tidal folio
#

Look

tidal folio
jade flare
#

?

tidal folio
#

Look didn't fix it

slate swan
#

On line 20 you use 4+ spaces

#

Have the same amout of spaces or use tabs

#

Most basic python knowledge you should have bravemmlol

tidal folio
slate swan
#

Then learn python basics

#

First lesson: Indentation

slate swan
# unkempt canyon

And read/translate/screen read/whatever that message and the links related to indentation

slate swan
unkempt canyonBOT
#

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

001 |   File "/home/main.py", line 3
002 |     print(2) # four spaces
003 | IndentationError: unexpected indent
slate swan
#

when you choose amount of indentation you use you must be consistent

cloud dawn
unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

2
cloud dawn
#

your welcome

slate swan
pliant hinge
#

Hi

silk wasp
vale wing
cloud dawn
#

Speaking about that, I've nearly graduated. I'm finished juli 10.

grand hazel
#

i try putting timestamp in embed but instead jt shows this

vocal snow
#

Looks like you forgot to await timestamp()?

grand hazel
tidal folio
grand hazel
tidal folio
grand hazel
#

thank you

tidal folio
grand hazel
#

oh sorry i use discordpy only

tidal folio
#

But send it to me because it doesn't make much difference

vocal snow
#

It should be the same as discord.py (since they are forks and I doubt there's much debate over the implementation of embeds)

tidal folio
grand hazel
# tidal folio <@820199993452265472>

heres an example i found online

import discord

# Create a new client instance
client = discord.Client()

@client.event
async def on_ready():
    print(f"We have logged in as {client.user}")

@client.event
async def on_message(message):
    if message.content.startswith('!send_embed'):
        embed = discord.Embed(
            title="Example Embed",
            description="This is an example embedded message.",
            color=discord.Color.blue()
        )
        embed.set_author(
            name="Your Name",
            icon_url="https://example.com/your-icon.png"
        )
        embed.add_field(
            name="Field 1",
            value="Value 1",
            inline=False
        )
        embed.add_field(
            name="Field 2",
            value="Value 2",
            inline=False
        )
        embed.set_footer(text="This is a footer")

        channel = message.channel
        await channel.send(embed=embed)

# Replace 'YOUR_TOKEN' with your bot token
client.run('YOUR_TOKEN')
grand hazel
tidal folio
grand hazel
#

anywhere actually, theres tons of information everywhere

#

youtube google even chathpt

tidal folio
#

Thank you So much.

slate swan
turbid condor
#

which ever u are used to

tidal folio
turbid condor
#

then use that

tidal folio
slate swan
#

They use what they know

tidal folio
#

Wich one?

slate swan
#

Neither

#

Choose whatever you want

#

They have different ways of doing things, there's no better and worse

tidal folio
#

What problem

slate swan
#

3 problems:

  1. you should not name Bot instance client its impractical
  2. there is no such event named on you are possibly looking for on_ready event Event reference: https://discordpy.readthedocs.io/en/stable/api.html#event-reference
  3. you showed your token reset it and dont do that again (also when coding on replit dont put your token right away everybody can see your code which means they can see your token as well)
slate swan
tidal folio
#

Only Replit

slate swan
#

well you can code on the IDE on your computer like Visual Studio Code

#

if you still want to stick to replit there is something called Environment Varriables

torpid frigate
#

hey so i have import interactions but its not working. done the pip install got the latest version but still getting "Import "interactions" could not be resolvedPylance"

slate swan
#

installed on your pc

torpid frigate
#

if I do python --version It just says 3.10.8

slate swan
torpid frigate
#

how do I check for multiple versions. im on mac

slate swan
torpid frigate
#

nope just a 3.10 folder

slate swan
#

okay do you code in vs code?

torpid frigate
#

yea

slate swan
#

do you see Python 3.x.x on the botton of your screen when on vs code

torpid frigate
#

yes

#

3.10.7

slate swan
#

click on it

#

and you should see a prompt to choose interpreter

torpid frigate
#

yea

slate swan
#

choose the one that says 3.10.8

torpid frigate
#

done but still not working

#

do I have to select the path?

slate swan
#

no just select the one with 3.10.8

#

looks like you have many python versions installed

torpid frigate
#

ill do a clean uninstall of all my pythons

hushed galleon
#

/usr/bin/python3 is your system python so dont uninstall that

torpid frigate
#

okay I got it to work but now im running into a different issue. Use interactions.slash_command instead. they made some changes from v4 to v5. im doing a small scale test to learn it before trying to add it to my actual bot: ```from interactions import slash_command

client = interaction.Client(token="token")

@client.command(
name="ping",
description="Ping pong",
scope="server_ID"
)
async def _ping(ctx: interactions.CommandContext):
await ctx.send("Pong!")

@client.event
async def on_ready():
print("Ready!")

client.start()

#

the import is working but client = interaction.Client.... doesnt register.

slate swan
#

Look at your imports

torpid frigate
#

also wanted to know if I wanted my bot to be used on different servers how would I get around the scope="sserver_ID"

slate swan
#

Do you see interaction anywhere

#

i think you misspelled that

torpid frigate
#

no even with the s

#

it doesnt work

slate swan
#

ok but why would it work without s if you dont even import interaction

torpid frigate
#

was a typo when I took the screenshot

#

ffs damn sorry lol.

slate swan
#
class AutomaticModal(ui.Modal, title="Support"):
    def __init__(self):
        super().__init__()
        
    issue = ui.TextInput(label="What is your issue?", placeholder="Please describe your issue here in as much details as possible!", style=discord.TextStyle.long)
    
    async def on_submit(self, interaction: discord.Interaction):
        if self.issue == "embed":
            await interaction.response.send_message("lol")
        else:
            embed=discord.Embed(title=" ", description="Our database wasn't able to find your issue in our database. If you would still like support on this issue, please create a ticket describing your issue!", color=discord.Color.red())

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

is there a way to detect if a message in a modal is the same as one that is saved it will respond with a different message than if something else is typed?
potent spear
#

"is saved" where exactly?

slate swan
potent spear
#

but yeah, if you can store that in some DB & react based on what your return value is, then that's perfectly possible

slate swan
#

would it not work with something like that?

potent spear
#

not if you were to restart the bot

#

self.issue would be None then

slate swan
#

nah ill show u rq

potent spear
#

if the issue already exists?

slate swan
#

its like an automatic support system for a bot but im just wondering if i can set it to respond with like different links when the modal input is something else?

potent spear
#

just store your issues in a DB...
if it doesn't already exist, proceed, else tell the user with an ephemeral message he would be posting a duplicate

slate swan
#

no like ur not understanding

#

so if they have the flagship bot in their server and they come into the "support server" then they can type the issue like "embed generating" in the modal and it will respond with a docs link or something

potent spear
#

yeah, and why wouldn't a database storing the responses based on a given input be a bad idea?

slate swan
#

would it not be possible for it to just be in the .py file?

#

for like "if self.issue == "embed":
await interaction.response.send_message("link")
else:
await interaction.response.send("get more help")

potent spear
#

you could hardcode it, sure, but if you wanted to add new responses based on certain input, you'd have to restart your bot every time

slate swan
#

how would i hardcore it?

potent spear
#

you just did...

slate swan
#

that doesnt work

slate swan
potent spear
#

the error message says it literally
"our DATABASE..."

#

I'm not sure why you're avoiding that implementation

slate swan
potent spear
#

you're not even using a db, lol

slate swan
#

im not gonna write "the .py file cant find ur issue"

#

Our database wasn't able to find your issue in our database.

bravemmlol

#

ite u got it fr

#

How many times do you want to say "our database"

Yes.

potent spear
#

I'll show you in a dict format

issue_inputs_dict = {
  "embed": "I like turtles",
  "hurting knee": "ask a kiss on it",
  "default": "nothing was found"
}```

```py
appropriate_response = issue_inputs_dict.get(self.issue)
if appropriate_response is None:
   await ... send_message( ... issue_inputs_dict.get("default") )
else:
  await ... send_message( ... appropriate_response  )
#

see what I did here?
based on a given input, we'll send an appropriate response

#

ofc, this implementation is for educational purposes & you should use a database instead

slate swan
#

JSON my beloved

slate swan
#

how many command categories in a help command is generally good? like a range of what is too much and what is fine

potent spear
slate swan
#

i've got a select menu for that with a paginator, and the first embed is just like some info stuff about the bot

potent spear
slate swan
#

right but, it has information like choose from the category below, what should i change then? what should the first page have?

fallen imp
#

help me .-.

vocal snow
#

dotenv

fallen imp
vocal snow
#

yes, and the whole point of using environment variables is so that you don't need to keep your token in your script

#

please reset your token and remember to never share it

#

also I'm guessing you haven't installed the python-dotenv package which is why the import is underlined

slate swan
spice aurora
slate swan
slate swan
spice aurora
#

the thing is

#

u cant do anything with them without client secret

#

its basically useless

potent spear
slate swan
spice aurora
#

yo wot

#

skem

#

where do i store it ee

#

@slate swan

slate swan
#

Dunno, replit is shit imo

spice aurora
#

well free

slate swan
#

Well that's one of the downside of such a free service, your data is free for users as well

upbeat ice
#

thats not even the biggest issue with replit

slate swan
#

Replit has lots of issues

upbeat ice
#

they use a shared ip for everything running on the service

spice aurora
#

well cant complain abt a free service

#

now the storing part is a problem tho

slate swan
spice aurora
slate swan
#

i suggest supabase, u get a free 500mb of db storage

spice aurora
#

ooo

#

ty, will look into it

formal basin
#

is there anything better than better-profanity?

slate swan
#

Perspective API is pretty neat

slate swan
#

whats the difference between the has_permissions and the default_permissions decorator

glad cradle
# slate swan whats the difference between the has_permissions and the default_permissions dec...

has_permissions is a bot side check; default_permissions enforce permissions in discord (admins can overwrite them)

so for example if you have an application command that uses has_permissions and that requires the administrator permission the slash command will be visible to all the members but they won't be able to use it (since you have that permission check)
instead if you use default_permissions the slash command will be visible only to members that have the administrator permission (though if an administrator change the permissions of a command from the settings of the guild the command will be visible and usable according to the modified permissions)

slate swan
slate swan
glad cradle
slate swan
#

if you want for example the command to be only available for you as the bot owner you will need to use has_permissions

#

oh, but i have my own check for developers, so if i want to use it for lets say a kick command default permissions is more flexible for server owners as well no?

slate swan
#

okay so use default permissions for commands that are used by others than me pretty much

#

possibly

#

Add Media Channels as an premium perk

bravemmlol

glad cradle
#

sigh

slate swan
#

I have problem in cogs

#

Everything good and cogs loaded

#

But there is no response to commands

#

Console errors?

#

No errors

#

But i can't use the / command

#

Then we'll need code, screenshots of what happens when executing command etc.

glad cradle
#

probably he/she is not syncing them

slate swan
#

Wouldn't say there's no "response" to the command in that case

#

Unless they missed the point of slash commands that it's not prefix commands with / as prefix

versed swallow
#

Hello, I am trying to create a discord bot that will analyze stock news and tell if it is good or not, please DM me if you are interested in collaboratign

slate swan
#

is it possible to make a discord.py that uses buttons if 2 people click the same button it will create a text channel linking to a database

sick birch
#

How do you link to a database?

slate swan
#

like a whole new client

sick birch
#

What are you trying to do?

swift edge
#

quick question
guys is it possible to put a link in a set_footer(text="link here")

swift edge
#

oh ok

#

thats all i needed

slate swan
# sick birch What are you trying to do?

something like a queue system where there is buttons attached to an embed and then someone will clikc it and it will place them in a queue until someone clicks it and then it create a text channel

#

so when 2 people interact with the button it creates a new channel

swift acorn
#
class changenamebutton(View):
    def __init__(self):
        super().__init__(timeout=20)
        
    @button(label="Change Name", style=discord.ButtonStyle.blurple, custom_id="namechange", emoji="📝")
    async def gemtransfer(self, interaction: discord.Interaction, button: Button):
        await interaction.response.send_modal(namechangemodal())

    async def on_timeout(self):
        for button in self.children:
            button.disabled = True

I can't figure out how to edit the original message with the disabled buttons after I have disabled them in the on_timeout function

normal jasper
swift acorn
naive briar
#

You need to set the message attribute

swift acorn
# naive briar Show the code where you use this view

for now not being properly used I was just testing some stuff with the bot, but

@bot.event
async def on_message(message):
    if message.guild == None and message.author.id != 1120682150639968296:
        await message.channel.send("test", view=changenamebutton())
potent spear
#

have a database
store all user IDs of allowed members in there

have an event (on_member_update) which checks when someone gets a role => if not in database, remove given role

#

no, you'll need an actual database
because once your bot restarts, you'll ofc want to keep your list and not start all over

#

unless you hardcode those user IDs and will never change them in the future...

#

then you can use a botvariable with a list of user IDs, sure

#

should have a before and after argument
if it's in a class, it also needs the self first ofc

#

irrelevant
if you're in a class, you just add self, else you only need the 2 parameters I told you

#

make sure you have member intents enabled
else that event will never trigger

winter hare
#

so i made a cog class using commands.GroupCog afterwards when i went to go and run the main file it didnt register the command i had in the main file

formal basin
#

when i press run in vscode this comes up vscode % /usr/bin/python3 /Users/zagzag/vscode/main.py but nothing happens how do i fix?

torn solar
#
intents.messages = True
intents.message_content = True
intents.presences = True
intents.members = True

bot = commands.Bot(command_prefix=prefix, intents=intents)

@bot.event
async def on_ready():
    await bot.change_presence(status=status, activity=presence)
    print(f'Loaded {bot.user}')
        
async def on_message(message):
    print(f"{message.author}: {message.content}")
    if message.content == "setupInfo":
        await bot.wait_until_ready()
        print(f'worked')
        channel = bot.get_channel(1120938903487131648)
        await channel.send(embed=info_embed)```
#

the onready works, but my onmessage embed thing doesnt

#

it worked when i used a client not a bot

#

can someone tell me why and how to fix it

slate swan
#

Where's the event decorator

torn solar
#

omg

#

ty

slate swan
#

Also if you have all these intents enabled, you can just do

bot = commands.Bot(command_prefix=prefix, intents=discord.Intents.all())
torn solar
#

anything else that would not make it work

slate swan
#

And messages is already included in default so that one is already redundant

torn solar
#

i was trying everything to fix it

#

thats why i did it

slate swan
#

Oh yeah makes sense LULW

#

Try out if it works now

torn solar
#

worked thanks so much

slate swan
slate swan
#

aren't custom emoji's <a:name:id> or <:name:id>? or are they just <a:name:> or <:name:>?

naive briar
#

With IDs

slate swan
#

so that would just be <:pithink:> right?

naive briar
slate swan
#

o.o how do I get the id #?

naive briar
slate swan
#

ooooo ty!

naive briar
slate swan
#

ooo so u have to send it

#

interesting

shrewd apex
#

u dont really need the name u can substitute it with a placeholder also

#

<:_:id> will work too

naive briar
slate swan
#

\😻

unique lichen
#

how to remove the page counter in pagination

astral ether
#

hello i have this code for send an embed when a member join a guild :

guild_id = client.get_guild(member.guild.id) # This function is called get_guild so presumably it returns a Guild object
channel = guild_id.get_channel(recuperer_valeur(member.guild.id, "config_bienvenue_id"))
        
await channel.send(embed=embed)

but i have this error :

File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event await coro(*args, **kwargs) File "/home/container/bot proto/main.py", line 33, in on_member_join await channel.send(embed=embed) ^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'send'

slate swan
#

channel is none

#

use something like

channel = guild_id.get_channel(...) or await guild_id.fetch_channel(...)
#

So that you first try to get from cache and otherwise make an API call

unique lichen
#

how to make something to send a message at sharp midnight

swift acorn
#
class changenamebutton(View):
    def __init__(self):
        super().__init__(timeout=20)
        
    @button(label="Change Name", style=discord.ButtonStyle.blurple, custom_id="namechange", emoji="📝")
    async def gemtransfer(self, interaction: discord.Interaction, button: Button):
        await interaction.response.send_modal(namechangemodal())

    async def on_timeout(self):
        for button in self.children:
            button.disabled = True
@bot.event
async def on_message(message):
    if message.guild == None and message.author.id != 1120682150639968296:
        await message.channel.send("test", view=changenamebutton())

Hey, I am trying to disable my button after timeout but self.message.edit(view=self) does not work, would anyone know how to edit the message?

slate swan
#

Well

#

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

You need to specify time

unique lichen
slate swan
#

!source remind

unkempt canyonBOT
#
Command: remind

Commands for managing your reminders.

Source Code
slate swan
#

You can check out how the remind command is done here

tidal folio
#

.....

slate swan
#

!d disnake.Embed

unkempt canyonBOT
#

class disnake.Embed(*, title=None, type='rich', description=None, url=None, timestamp=None, colour=..., color=...)```
Represents a Discord embed...
tidal folio
twilit grotto
#

indentation lmao

torpid frigate
#

Hello. Im trying to convert a $ command to an interaction. would anyone know how to convert this part? ```@bot.command(name='score')
async def show_score(ctx, user: discord.Member = None):
guild_id = ctx.guild.id
target_user = user if user else ctx.author
owes_text = []
owed_text = []

#

ive got this so far: ```my_guild = discord.Object(id='server_id')

class MyClient(discord.Client):
def init(self, *, intents: discord.Intents):
super().init(intents=intents)
self.tree = app_commands.CommandTree(self)

async def setup_hook(self):
    self.tree.copy_global_to(guild=my_guild)
    await self.tree.sync(guild=my_guild)

intents = discord.Intents.default()
client = MyClient(intents = intents)

@client.tree.command(description = 'display the score to the user')
async def score(interaction: discord.Interaction):```

#

having issues with ctx and how to change it with regards to interactions

slate swan
#

interaction.guild.id and interaction.user 3HC_what

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
slate swan
#

Just look through the attributes and methods there and use what you need

swift acorn
normal jasper
#
reminder = await self.bot.api_client.post(
            "bot/reminders",
            json={
                "author": ctx.author.id,
                "channel_id": ctx.message.channel.id,
                "jump_url": ctx.message.jump_url,
                "content": content,
                "expiration": expiration.isoformat(),
                "mentions": mention_ids,
            }
        )

Hello, i saw this in reminder's source code. Is this some kind of personal database for bots?

naive briar
#

Yes

normal jasper
slate swan
#

It's most likely a custom API that is only made for @unkempt canyon

#

So you cannot use it, make your own

normal jasper
slate swan
#

Learn web development and make an API that accepts POST request and the JSON body as shown above and then saves everything in a database

slate swan
#

i just need some visual advice, does it look good when bots add the "Requested by {whatever} | time" at the bottom of the embed or does it not look good

#

Depends for what

#

Sometimes it's useful and nice to have, sometimes it's just pointless - people can scroll the chat or look up to know who requested it - and the time, well it's shown on Discord's UI anyways so that's definitely useless - depending on what time you show

#

If it's something like a reminder etc. then yes, it may be useful by showing who has set the reminder and the time when they have set the reminder

#

ah okay thanks

drifting arrow
#

Hey, I'm using a discordapp, not a discordbot. and I am querying the discordapi so I can get my roles and all I am getting is the role id? How do I convert this to a role name?

slate swan
#

Not possible, use a bot token

drifting arrow
#

;-;

#

But then my bot would have to be in the actual discord lol

slate swan
#

Yes

drifting arrow
#

What's the point in being able to "read" your roles if you cant actually read the roles? lol

slate swan
#

You can

#

The role ID

drifting arrow
#

And how do I convert that to a role name without actually having a bot in the server? lol

slate swan
#

You don't

drifting arrow
#

Then again - What's the point? lol

slate swan
#

Because IDs are useful comapred to a name

#

So it only returns the ID

drifting arrow
#

What can I do with an ID?
My account owns the server I am querying. the app has the above perms.
I dont want to invite a discord bot to the server just to convert a role id to a role name. So what can I use a role id for?

slate swan
#

Everything related to the API that uses role IDs

drifting arrow
#

I appreciate how you're replying without actually giving anything useful

slate swan
#

Because I've already told you

#

Use a bot to get specific data about the roles in a guild

wispy pasture
#

sooo the cmd WITHOUT the buttons is working perfectly, but WITH the buttons the cmd just stops...i added different logs, here is the result:

  1. the bot IS making the file, but not sending it

code: https://srcb.in/MkSszD7kme

fallen imp
#

help .-.

slate swan
#

Enable the message content intent in the developer portal, as the error says - if you'd read it

naive briar
#

Because you should

wispy pasture
naive briar
#

Do you have any error handlers

#
discord.ui.View(select)

Is not how you add items to views

#

!d discord.ui.View.add_item you need to use this method

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

This function returns the class instance to allow for fluent-style chaining.
wispy pasture
naive briar
#

Then it's probably eating the tracebacks

wispy pasture
#

the file is being made, everything is working except the sending of the message/embed

naive briar
#

Show the code of the error handler

slate swan
#

can we set title color for embed in discord

naive briar
#

No

slate swan
naive briar
#

Show screenshot

slate swan
#

see the title is blue

#

also how can i make those small description

naive briar
slate swan
#

oh yea its ahyperlin

#

how do u make hyperlinks

naive briar
naive briar
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

i think its footer

naive briar
naive briar
slate swan
#

iii fogot how u set footer

#

was it like embed.set_footer

naive briar
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
lethal drift
#

I get this error every time I try to import app_commands

vocal snow
#

make sure discord.py is up to date and uninstall any other dapi wrappers you have (eg, py-cord)

slate swan
#

What i need to install to use cogs ?

buoyant quail
#

Nothing extra

#

discord.py or the other library you are using

slate swan
#

Ok

#

Cogs does not work

meager chasm
#

oof

turbid condor
naive briar
#

And your on_select is unused, also that's not how you set select callbacks

slate swan
#

what is the problem ?

naive briar
#

What is the library you're using

slate swan
naive briar
#

Then you need to await the load_extension

slate swan
#

It doesn't work

naive briar
#

What doesn't work? Be specific

slate swan
#

Cogs

slate swan
naive briar
#

That doesn't explain anything

slate swan
#

Print

#

Cogs not loaded

naive briar
#

And I already told you to await the load_extension

alpine oar
#

can yall help me? I cant download easy_pill ive already tested pip install eas_pill just says it didnt find the file even tho i reinstalled the whole python

slate swan
naive briar
#

And?

slate swan
#

Still doesn't work

naive briar
#

Show your current code

#

Or it's probably just you didn't call the load coroutine

slate swan
#

1m

naive briar
alpine oar
#

it says it doesnt find the file

#

its sooooo weird

naive briar
#

Find the file?

alpine oar
#

Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" install easy_pill': Det gÕr inte att hitta filen.

#

That

#

the last bit is swedish

slate swan
naive briar
alpine oar
#

do this:
from discord.ext import commands

alpine oar
naive briar
slate swan
alpine oar
naive briar
alpine oar
#

bruh i need this fr fr

naive briar
#

I don't know windows stuff

buoyant quail
alpine oar
#

oh mb i saw wrong lol

slate swan
buoyant quail
#

Also anyways better to check if you do have pip in C:\Program Files\Python310\Scripts\

#

maybe you have pip for some another python version and for that you don't

alpine oar
#

i got the version

#

3.10.9

slate swan
#

Thx cog file loaded but the command is not responding

buoyant quail
#

Move it from the __init__ function

#

It should be just a method of the class

alpine oar
#

now i get this ERROR: Could not find a version that satisfies the requirement easy_pill (from versions: none)
ERROR: No matching distribution found for easy_pill

naive briar
#

!pip easy-pil

unkempt canyonBOT
#

A Python library built on top of PIL to easily edit/modify images

alpine oar
#

By running the command python -m pip install easy_pill

naive briar
#

Try easy-pil instead of easy_pil

alpine oar
#

YES IT WORKED

#

AHHH FINALYYYYYYYY AFTER 1 MONTH LOL TYSM

#

wait.... it still didnt solve my problem

#

my code still says i got an error .........

alpine oar
# naive briar Try `easy-pil` instead of `easy_pil`

import discord
from discord import File
from discord.ext import commands
from easy_pill import Editor, load_image_async, Font

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.event
async def on_ready():
print("The Bot is officially online!")

@bot.event
async def on_member_join(member):
channel = member.guild.system_channel

background = Editor("pic2.jpg")
profile_image = await load_image_async(str(member.avatar.url))

profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")
poppins_small = Font.poppins(size=20, variant="light")

background.paste(profile, (325, 90))
background.ellipse((325, 90, 475, 240), outline="white", stroke_width=5)

background.text((400, 260), f"Welcome to {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")

image_bytes = background.image_bytes
file = File(fp=image_bytes, filename="pic1.jpg")

await channel.send(f"Hello {member.mention}! Welcome to **{member.guild.name}**. Have an great day!.**")
await channel.send(file=file
#

Mind cheking my code to see if i did anything wrong

#

bc it only says that easy_pill is wrong

buoyant quail
#

You have two l there

#

Should be one

#

easy_pill -> easy_pil

alpine oar
#

1 l?

#

yea still doesnt work

buoyant quail
#

What does it say?

alpine oar
#

Traceback (most recent call last):
File "c:\Users\OneDrive\Dokument\Discord Bots\Learning.py", line 4, in <module>
from easy_pil import Editor, load_image_async, Font
ModuleNotFoundError: No module named 'easy_pil'

#

and when i do easy-pil it givs me even more errors

#

well i am afk ima go eat

buoyant quail
naive briar
#

Show your error handler code

wispy pasture
#

the bot stops here: Command execution started.

naive briar
#

That's no error handler

wispy pasture
naive briar
#

What what?

buoyant quail
wispy pasture
naive briar
#

!d discord.on_error - error handlers in discord.py are generally events, like this one

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is logged to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.11)").

Note

`on_error` will only be dispatched to [`Client.event()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.event "discord.Client.event").

It will not be received by [`Client.wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for"), or, if used, [Bots](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#ext-commands-api-bot) listeners such as [`listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen") or [`listener()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.listener "discord.ext.commands.Cog.listener").

Changed in version 2.0: The traceback is now logged rather than printed.
wispy pasture
#

ohh that thing

buoyant quail
#

What did you got when you used

pip install easy-pil

(when installed library in terminal. you can run it again and show, doesn't matters)

And what command are you using to run your code

alpine oar
alpine oar
#

but it did work before

wispy pasture
# naive briar !d discord.on_error - error handlers in discord.py are generally events, like th...

that worked... now i got new errors 😅

  1. this is the error i m getting:
[2023-06-21 22:24:09] [ERROR   ] discord.ui.view: Ignoring exception in view <PollinationsView timeout=180.0 children=1> for item <Select placeholder='Select an image to view' min_values=1 max_values=1 disabled=False options=[<SelectOption label='Image 1' value='0' description=None emoji=None default=False>, <SelectOption label='Image 2' value='1' description=None emoji=None default=False>, <SelectOption label='Image 3' value='2' description=None emoji=None default=False>, <SelectOption label='Image 4' value='3' description=None emoji=None default=False>]>
Traceback (most recent call last):
  File "D:\shayan\python installation files\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "D:\Raza\discord orders\gpt4- hugging face\new era\final 3\smit smit\smit dall-e\main.py", line 506, in on_select
    await interaction.response.edit_message(
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.edit_message() got an unexpected keyword argument 'files'```

2. the bot is not showing the 4 images, it is showing nothing

code https://srcb.in/IhlMhBLqiZ
buoyant quail
alpine oar
#

ik

#

i saw wrong lol

buoyant quail
unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by editing the original message of a component or modal interaction.
buoyant quail
#

there is no files

#

attachments maybe?

alpine oar
#

what should i do now?

buoyant quail
wispy pasture
wispy pasture
alpine oar
buoyant quail
#

ok, i guess it was so. and second question?

alpine oar
#

dont get it

buoyant quail
#

With which command are you running the file
Like usually it is

python main.py
alpine oar
#

how do i chek that

#

💀

vocal snow
#

how are you running your program?

alpine oar
#

using vsc

#

what my file name is?

#

ik i am dumb asf

buoyant quail
#

What's the first line of output when you run it?
Something that looks like path

alpine oar
#

from easy-pil import Editor, load_image_async, Font'

buoyant quail
#

the yellow + blue text

lofty lance
#

hey i do have a question regarding a currnt project just simpple querry

#

if anyone can clear the doubt

alpine oar
#

S C:\Users> & C:/Users//AppData/Local/Programs/Python/Python310/python.exe

#

that

buoyant quail
#

ok
show the output of doing pip -V in terminal

lofty lance
alpine oar
#

Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" -V': Det gÕr inte att hitta filen.

alpine oar
lofty lance
vocal snow
lofty lance
buoyant quail
buoyant quail
alpine oar
#

so i did pip install easy-pil just like catlover said and that was succesful

#

i used pip install easy-pil

buoyant quail
#

huh

main fiber
#

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
print('We have logged in as {0.user'.format(client))

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

if message.content.startswith($hello):
await message.channel.send('Hello')

client.run(os.geten('TOKEN'))
alpine oar
#

but now i get this Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" install easy-pil': Det gÕr inte att hitta filen.

buoyant quail
#

do
python -m pip -V
or just
python --version

main fiber
#

🔼 I don't know why it doesn't work

alpine oar
lofty lance
#

so i am making a discord game bot
so when user type command start i fetch server details like guid id and etc and store it in mongo db to be userd in future

the game use a map like stuff
so i assgin a x and y cooridnate to a server

i want to make sure that one server gets only one value
and if user type start comand agian it should not work
any way to detect that and make it work only once per server
i know i can compare the guid id and chekc if currnt id exists or not
but wont it take to log if there are many guid ids?
i want the code to be fast
any other way for that sir ?
@vocal snow

vocal snow
alpine oar
#

pip 23.1.2 from C:\Users\AppData\Local\Programs\Python\Python310\lib\site-packages\pip (python 3.10)

lofty lance
alpine oar
vocal snow
buoyant quail
# alpine oar what is that even?

I was checking that you have pip corresponding to the python you are running

try

python -m pip install --upgrade --force-reinstall easy-pil

and running the code again idk

slate swan
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

slate swan
#

decorator must be indented the same as the function it is assigned to

main fiber
lofty lance
lofty lance
main fiber
#

how do I fix indentation line?

slate swan
#

and only use client

slate swan
main fiber
lofty lance
sick birch
#

What's different between them?

lofty lance
slate swan
alpine oar
sick birch
#

I'm aware, that was directed at OP

lofty lance
#

@main fiber u can use indent-rainbow extention too
if u get confused in that sometimes

main fiber
#

I mean I fixed it but on line 17 it has a syntax error

lofty lance
sick birch
main fiber
#

I'm getting so much pings lol

buoyant quail
unkempt canyonBOT
#

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

001 |   File "/home/main.py", line 1
002 |     $hello
003 |     ^
004 | SyntaxError: invalid syntax
alpine oar
#

vitness i sent in dms bc i couldnt send here

sick birch
#

I would highly recommend going over the Python tutorial I linked above, discord bots are not beginner-friendly and are an advanced topic

main fiber
#

ok

lofty lance
# slate swan you are not supposed to answer

ohh btw can u review my code of so far pls
its a simple code that fecht server info and
assign it X and Y cooridnatess to be used in map and i have some doutbs if u can clear to ?

slate swan
#

you cant just put random characters if you want to check for strings you need to say that it is a string by puting it in "

#

(or ')

#

like you did line below

#

@main fiber

main fiber
#

ok

slate swan
lofty lance
# main fiber ok

and replce that ; with : and give return funtion some indentation

lofty lance
slate swan
lofty lance
#

shall i share live share extention of it

#

vs code live share i mean

#

or lets just pass that i will explain my code to u here

slate swan
#

never used it maybe you have it on github?

lofty lance
#

alr i will upload it when its bit funtunabel
currnty it just do one thing

#

when u type start command

slate swan
#

if its not too long you can upload it here

lofty lance
#

btw how to use that python ext of discord to decorate your code in discord msg

slate swan
#

!code

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

lofty lance
#

ahh wiat got it

#

this thing

slate swan
#

yeah but can be just py in short

lofty lance
#
  import discord
from discord.ext import commands
from pymongo import MongoClient
from serverinfo import ServerInfo
from location import LocationManager
from datainfo import MONGO_CONNECTION_STRING, MONGO_DATABASE_NAME , SERVER_INFO

import setting
logger = setting.logging.getLogger("bot")

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)


# Set up your bot

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name} ({bot.user.id})")
    print("Bot is ready")

@bot.command()
async def start(ctx):
    # Create an instance of the ServerInfo class
    server_info = ServerInfo(ctx.guild)

    # Assign a location to the server using LocationManager
    location_manager = LocationManager()
    location_manager.assign_location(ctx.guild)
    server_info.x_coordinate = location_manager.x_coordinate
    server_info.y_coordinate = location_manager.y_coordinate

    # Store server info in MongoDB collection
    client = MongoClient(MONGO_CONNECTION_STRING)
    db = client[MONGO_DATABASE_NAME]
    collection = db[SERVER_INFO]
    server_data = {
        "_id": server_info.guild_id,
        "guild_id": server_info.guild_id,
        "guild_name": server_info.guild_name,
        "guild_pfp": server_info.guild_pfp,
        "region": server_info.region,
        "member_count": server_info.member_count,
        "owner_id": server_info.owner_id,
        "x_coordinate": server_info.x_coordinate,
        "y_coordinate": server_info.y_coordinate
    }
    collection.insert_one(server_data)
    client.close()

    await ctx.send(f"Location assigned to {ctx.guild.name}: ({server_info.x_coordinate}, {server_info.y_coordinate})")

# Add more commands or event handlers as needed


bot.run(setting.Discord_api , root_logger=True)
#

its main.py file as i have stored the private info in other file

#

wont be a issue

#
 from location import assigned_x , assigned_y
class ServerInfo:
    def __init__(self, guild):
        self.guild_id = guild.id
        self.guild_name = guild.name
        self.guild_pfp = str(guild.icon.url) if guild.icon else None
        self.region = self.get_region(guild)
        self.member_count = guild.member_count
        self.owner_id = guild.owner_id
        self.x_coordinate = assigned_x
        self.y_coordinate = assigned_y

    def get_region(self, guild):
        try:
            return str(guild.region)
        except AttributeError:
            return None

this is serverinfo.py

#
import random
from pymongo import MongoClient
from datainfo import MONGO_CONNECTION_STRING, MONGO_DATABASE_NAME, RESERVERD_COLLECTION

class LocationManager:
    def __init__(self, connection_string=MONGO_CONNECTION_STRING, database_name=MONGO_DATABASE_NAME, collection_name=RESERVERD_COLLECTION):
        self.client = MongoClient(connection_string)
        self.db = self.client[database_name]
        self.collection = self.db[collection_name]
        self.x_coordinate = None
        self.y_coordinate = None

    def assign_location(self, guild):
        x, y = self.generate_random_location()

        while self.is_location_reserved(x, y):
            x, y = self.generate_random_location()

        self.x_coordinate = x
        self.y_coordinate = y

        self.store_location(guild.id, x, y)
        print(f"Assigned location ({x}, {y}) to server {guild.name}")

    def generate_random_location(self):
        return random.randint(0, 1000), random.randint(0, 1000)

    def is_location_reserved(self, x, y):
        query = {"Data": "Server_coordinates"}
        reserved_data = self.collection.find_one(query)

        if reserved_data:
            reserved_locations = reserved_data.get("Locations", [])
            return any(location.get("X") == x and location.get("Y") == y for location in reserved_locations)
        
        return False

    def store_location(self, server_id, x, y):
        query = {"Data": "Server_coordinates"}
        reserved_data = self.collection.find_one(query)

        if reserved_data:
            reserved_locations = reserved_data.get("Locations", [])
            reserved_locations.append({"ServerId": server_id, "X": x, "Y": y})
            update = {"$set": {"Locations": reserved_locations}}
            self.collection.update_one(query, update)
        else:
            reserved_locations = [{"ServerId": server_id, "X": x, "Y": y}]
            data = {"Data": "Server_coordinates", "Locations": reserved_locations}
            self.collection.insert_one(data)

    def close_connection(self):
        self.client.close()

# Create an instance of LocationManager
location_manager = LocationManager()

# Access the X and Y coordinates after assigning the location
assigned_x = location_manager.x_coordinate
assigned_y = location_manager.y_coordinate

this is location_manager.py

#

want me to explain the code in short as i didnt added any comments at moment

#

?

slate swan
lofty lance
#

i am noob ig

slate swan
#

you should establish connection when you start the bot store this connection in a varriable

#

and then use it

#

something like:

#
bot.db = MongoClient(...)
lofty lance
#

so shall i put that in on_ready funtion ?

slate swan
#

can be

lofty lance
#

so i should put it in on_ready will be a grt idea

#

i didnt even though of it

lofty lance
#

let me do it

lofty lance
slate swan
#

wdym

#

if you are thinking of using global keyword

#

no never do that

#

assign it to bot

#

!botvar

unkempt canyonBOT
#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

why it sent twice huh

lofty lance
slate swan
#

no

#

its just example with simple string

#

you are supposed to put MongoClient instance here

slate swan
lofty lance
#

yaa insted of tesst

#

let me try it

#

here comes a error

slate swan
#

show it

lofty lance
#

last one

#

was kidding about error btw
programming jock
if something works dont touch it

#

idk what just i did btu it workd

slate swan
#

do you use it tho?

lofty lance
#

it and workd well
want me to show whole code?

#

btw i do have a doubt if can clear ?

slate swan
lofty lance
# slate swan ?

as u can see in location_manager
not only there but for start command to
i want to add a error hander
in which if person types that start button in a server whose data already exists with my database
then it should throw a error saying that u are registerd

#

so i was thinking to store all guids id in a document in mongodb
and compare it when person type that command but it feels like it will increase load on my machin only
and if there are a lot of server it will take time for it to chekc
so any way to just do it fastly

slate swan
#

hm no idea

lofty lance
#

or brad

slate swan
#

What's the prob

slate swan
#

Just store the registered guilds in mongo db, and when the user makes the command you can easily check

formal basin
#
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "/Users/zagzag/vscode/zagzag.py", line 501, in verify_setup
    await channel1.send("type !verify to verify")
AttributeError: 'NoneType' object has no attribute 'send'

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

Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'verify-setup' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
slate swan
#

channel1 is None

formal basin
slate swan
#

Errors don't lie, it is.

thin raft
formal basin
# slate swan Errors don't lie, it is.
@client.tree.command(name="verify-setup", description="sets up a verification system")
@app_commands.default_permissions(manage_guild=True)
async def verify_setup(interaction: discord.Interaction, verify_channel: discord.TextChannel, verified_role: discord.Role):
    r.set(f"vchannelid {str(interaction.guild.id)}",verify_channel.id)
    r.set(f"vrole {str(interaction.guild.id)}",verified_role.id)
    channel = r.get(f"vchannelid {str(interaction.guild.id)}")
    channel1 = client.get_channel(channel)
    await channel1.send("type !verify to verify")
    await interaction.response.send_message("verification system setup")
    channel2 = client.get_channel(1112053260879147130)
    await channel2.send(f"verify-setup command used by {interaction.user}")
#

i set it up

thin raft
#

what's r