#Basic Pycord Help (Quick Questions Only)

1 messages · Page 32 of 1

clear parrot
#

the guide tells me to do what im doing

loud holly
#

Then it should work

clear parrot
#

it doesnt

#

thats why im here

loud holly
#

You didn't include the __init__

#

In the guide it should be there

clear parrot
# loud holly You didn't include the `__init__`
class MyView(discord.ui.View):
    async def on_timeout(self):
        for child in self.children:
            child.disabled = True
        await self.message.edit(content="You took too long! Disabled all the components.", view=self)

    @discord.ui.button()
    async def button_callback(self, button, interaction):
        ...

@bot.command()
async def button(ctx):
    await ctx.send("Press the button!", view=MyView(timeout=30))```
#

dont see it there

loud holly
#

Send the links pls

clear parrot
#

and I already tried it with it

    @slash_command(name="support", description="Get a link to our support server.",)
    async def support(self, ctx: AppContext):
        embed = Embed(title="Official Server", description="🔗 Click the button below to join the Official Server to get help and have access to some cool features!")
        await ctx.respond(embed=embed, view=SupportButton())

class SupportButton(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Official Server!", style=discord.ButtonStyle.url)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You clicked the button!")```
loud holly
#

Send in ur pip list

#

And are there any errors or such?

clear parrot
#
[CRITICAL: 16:45:22 | EXT]     @discord.ui.button(label="Official Server!", style=discord.ButtonStyle.url, url="https://discord.gg/")
[CRITICAL: 16:45:22 | EXT]      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[CRITICAL: 16:45:22 | EXT] TypeError: button() got an unexpected keyword argument 'url'```
clear parrot
# loud holly And are there any errors or such?

when I dont put the url= it literally says

An unhandled error occured. This has been reported.

HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.url: A url is required```
#

makes no sense

neon bramble
#

url buttons can't have callbacks

#

so the decorator probs doesn't support them

#

you'd have to construct a ui.Button class and add it with add_item

#

cc @clear parrot

clear parrot
# neon bramble you'd have to construct a ui.Button class and add it with add_item

so like

    @slash_command(name="support", description="Get a link to our support server.",)
    async def support(self, ctx: AppContext):
        embed = Embed(title="Official Server", description="🔗 Click the button below to join the Official Server to get help and have access to some cool features!")
        await ctx.respond(embed=embed, view=helpView())

class helpView():
  def __init__(self):
    super().__init__(timeout=None)
    supportServerButton = discord.ui.Button(label='Support Server', style=discord.ButtonStyle.gray, url='https://discord.com')
    self.add_item(supportServerButton)```
neon bramble
#

the only style a url button can have is ButtonStyle.url

clear parrot
#

so change the .gray to .url?

neon bramble
#

yeah

clear parrot
#
An unhandled error occured. This has been reported.

TypeError: object.init() takes exactly one argument (the instance to initialize)```
💀
neon bramble
#

lol what

#

what have you done

clear parrot
#

just with .url

clear parrot
#

because this is dumb af

neon bramble
#

umm i dunno

#

i usually just do what you have done (unless i am blind)

#

p sure that there's an example for this though

gleaming falcon
#

(Not claiming that's the extent of your issues, but that is definitely an issue)

worldly tendon
#

Is it possible to split a subcommand group across multiple files?

worldly tendon
mortal junco
#

Hey guys

#

Dont really need help just need suggestions

#

im working on a discord subcription bot for if you boost with nitro that dms you a account in your dms of something like a gamepass code or a account for a game from our database right but we have alot of different options in our stock and i want to figure out how to limit only the account type and how many times it can be genorated

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f"{round(error.retry_after, 2)} seconds left")

@client.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def command(ctx):
    await ctx.send("command output")```
is the only way  i know how to limit commands
#

could i send u my code?

#

and u give me a way to do it

worldly tendon
#

your text doesnt make sense to me, there is no . or ,
however the account type you can check if someone has nitro, if thats what you want

mortal junco
#
@client.slash_command(name="generate", guild_ids=[json.loads(open("config.json", "r").read())["guild_id"]])
async def generate(ctx, service_name):
    if str(ctx.channel.id) != json.loads(open("config.json", "r").read())["gen_channel"]:
        await ctx.respond(f"You can only gen in: <#{json.loads(open('config.json', 'r').read())['gen_channel']}>", ephemeral=True)
    else:
        week_services = ["None"]
        for service in week_services:
            if service_name.lower() == service.lower():
                if str(json.loads(open("config.json", "r").read())["week_role"]) in str(ctx.author.roles):
                    if os.path.exists(f"accounts/{service}.txt"):
                        with open(f"accounts/{service}.txt", "r+") as accounts:
                            data = accounts.readlines()
                            accounts.seek(0)
                            accounts.truncate()
                            accounts.writelines(data[1:])
                            try:
                                embed = discord.Embed(title=f"{service} Account Generated", description="Lightstore Account Generator", color=0x46a9f0)
                                embed.add_field(name="Login Credentials", value=f"```{data[0]}```", inline=True)
                                embed.set_thumbnail(url="https://media.giphy.com/media/3o7bufVwr3qbu9qYX6/giphy.gif")
                                embed.set_footer(text="Made By Fqlx#2760")
                                user = await client.fetch_user(int(ctx.author.id))
                                await user.send(embed=embed)
                                await ctx.respond("Account Generated, check your DM")
                            except Exception:
                                await ctx.respond(f"We are currently out of {service}!", ephemeral=True)
                    else:
                        await ctx.respond(f"We are currently out of {service}!", ephemeral=True)
                else:
                    await ctx.respond(f"You cannot gen {service}!", ephemeral=True)
        month_services = ["NFA","Ranked","Skinned"]
        for service in month_services:
            if service_name.lower() == service.lower():
                if str(json.loads(open("config.json", "r").read())["month_role"]) in str(ctx.author.roles):
                    if os.path.exists(f"accounts/{service}.txt"):
                        with open(f"accounts/{service}.txt", "r+") as accounts:
                            data = accounts.readlines()
                            accounts.seek(0)
                            accounts.truncate()
                            accounts.writelines(data[1:])
                            try:
                                embed = discord.Embed(title=f"{service} Account Generated", description="LightStore Account Generator", color=0x46a9f0)
                                embed.add_field(name="Login Credentials", value=f"```{data[0]}```", inline=True)
                                embed.set_thumbnail(url="https://media.giphy.com/media/C9x8gX02SnMIoAClXa/giphy-downsized-large.gif")
                                embed.set_footer(text="Made By Fqlx#2760")
                                user = await client.fetch_user(int(ctx.author.id))
                                await user.send(embed=embed)
                                await ctx.respond("Account Generated, check your DM")
                            except Exception:
                                await ctx.respond(f"We are currently out of {service}!", ephemeral=True)
                    else:
                        await ctx.respond(f"We are currently out of {service}!", ephemeral=True)
                else:
                    await ctx.respond(f"You cannot gen {service}!", ephemeral=True)```
#

idk why tis splitting like thast

#

its not nitro , but once they pay or nitro boost we give them access to a r ole that lets them use the bot

steel wedge
#

am i just very stupid or why does it keep replacing the same line?
f.write(f"Name : {message.author} Date : {date.today()} Quote : {message.content}\n")

#

my brain

#

is mush

#

when i looked it up it says to put the \n at the end

#

but it just doesnt work

worldly tendon
steel wedge
#

ok thanks

worldly tendon
mortal junco
worldly tendon
#

all your nested if statements for example

mortal junco
#

thats just how i code i guess i cant really explain i

worldly tendon
#

instead of nesting it like that, use if not and return

mortal junco
#

well do u know a way i can limit a specific value of a command instead of the entire command

worldly tendon
mortal junco
#

so say i can /generate NFA, /generate Skinned, /generate Ranked

#

i wanna limit /generate Skinned

#

instead of the entire /generate command

steel wedge
worldly tendon
# mortal junco Here look

here is an example of your nesting btw

if service_name.lower() == service.lower():
    if str(json.loads(open("config.json", "r").read())["week_role"]) in str(ctx.author.roles):
        if os.path.exists(f"accounts/{service}.txt"):
  1. save json.loads(open("config.json", "r").read() into a variable that you can reuse.
    loading it again and again is not performant. it can also cause a race condition if you write to the file, where it wants to read and write at the same time. this can corrupt them.
    use something like this:
jsondata = None
with open('strings.json') as json_data:
    jsondata = json.loads(json_data)
  1. dont nest your if statements like above, use something like this:
if service_name.lower() != service.lower():
    return
if not str(jsondata["week_role"]) in str(ctx.author.roles):
    return
if not os.path.exists(f"accounts/{service}.txt"):
    return

with open(f"accounts/{service}.txt", "r+") as accounts:
    data = accounts.readlines()
    # ...

this is much more readable and then people might understand what your actual issue is ^^

mortal junco
#

Oh okay, 😛 ill update soon

#

i just really need to figure this out

worldly tendon
# mortal junco so say i can /generate NFA, /generate Skinned, /generate Ranked

instead of /generate <nfa/skinned/ranked>, id use subcommands.

/generate nfa
/generate skinned
/generate ranked

without arguments. that will split your code into more chunks, make it more readable and you can easily limit them to whatever you want. You could do the same with one command and arguments but that will look messy fast.

I still dont get how you want to limit them. per day of week?

mortal junco
#

and i really dont want to do subcommands i did them all together for a reason

#

if i did subcommands id have to redo my entire sql

worldly tendon
#

gives you 0-6

mortal junco
#

huh

#

im sorry ive never seen that

worldly tendon
#

all good

#

you need to import datetime

mortal junco
#

i refuse to redo sql

#

"This isnt for public use so idc abt readablility aslong as i understand it

worldly tendon
mortal junco
#

got it

#

your the best,

#

do i fill in the datetime.datetime.today thats only part confusing me as ive never worked with datetime import

worldly tendon
#

do i fill in the datetime.datetime.today
i dont understand

young bone
#

.now()

worldly tendon
#

you dont need to
it gets the current time by default, so no need for now

worldly tendon
mortal junco
#

i dont understand what the is doing i mean i kinda do but how do i set the time i want

loud holly
mortal junco
#

no ive never used it

loud holly
loud holly
mortal junco
#

such as /generate NFA /generate Skinned

#

i only want to limit /generate Skinne

loud holly
# mortal junco i only want to limit /generate Skinne

so why not put it in a subcommand since it'll save you a lot of hassle, like right now you're going into a complicated way which will get rlly messy and burn you out.

Since generate is the keywork use that as a main command name and work on that. Sure you'll have to rewrite the SQL DB and stuff but like surely one day you'll have to rewrite the entire bot and trying to work out complicated steps and make it efficient is time consuming and quick in burning out. I did it this way and trust me, it's better to build something nice and easy at the start than leaving it at the last moment where it's a lot messy

#

if you rlly want to go into the complicated and inefficient, make it so that you configure preferably via UTC (3.11)

#

and then check if a day or so has passed

mortal junco
#

Ughhhh

#

im not good at sub commands either

loud holly
mortal junco
#

but ill try

loud holly
#

Variable = discord.SlashCommandGroup("main keyword", description="if you want")

@Variable.command()
async def first_command(...):
  # DO STUFF
#

@mortal junco ^^

mortal junco
#

Ugh ill do some research ig and rewrite

#

Can i please get one example from my line of code and then ill do rest

#

i am a very visual learner xD

errant craneBOT
rare ice
#

Don’t ask for code

mortal junco
#

uhm wtf happened

#

i have all the requirements installed pylance and everything

rare ice
mortal junco
#

pip install discord?

mortal junco
meager heron
#

Are you using a venv? I've found VS Code randomly hates that

mortal junco
#

why tf is it not working

#

bro this is so annoying

full basin
#

It's py-cord

#

Not discord

#

It gets imported as discord but the library name is py-cord

#

@mortal junco Uninstall pycord

#

You have pycord and py-cord

mortal junco
#

pip uninstall pycord

mortal junco
silver moat
#

restart vsc if you haven't already

#

also if you have multiple python versions, please use the correct one.

loud holly
#
@discord.ui.channel_select(
        placeholder="Select a Channel",
        min_values=1,
        max_values=1,
        channel_types=[discord.TextChannel]
)

so basically I'm getting an error which I'm guessing I'm using the channel_types incorrectly

type object 'TextChannel' has no attribute 'value' <-- Error

#

Currently trying out other ways of getting that to work

#

nvm found a fix for it

mortal junco
#

im having troubles it was working until i changed the directory the file was in adn then i change it back and it dont work

#

i really need it fixed

#

brooo

mortal junco
#

Pleasee

#

i need it fixed idk what to do ive looked all over google

silver moat
mortal junco
#

:c

silver moat
#

type where pip and where python and send their output

mortal junco
silver moat
#

that really did not help

#

python -m pip list and send output

mortal junco
#

@silver moat 🙂

#

i reallly need it running

silver moat
#

idk how to explain this, but your visual studio code should have a python setting.

#

It will tell you the path of the python you are using

mortal junco
#

@silver moat uhm tgis?

lilac citrus
#

control shift p and then select interpreter or something

silver moat
#

what if you just typed python main.py or whatever you named your file

mortal junco
#

thats what i do

#

it dont work

silver moat
#

what did you name your file

mortal junco
#

@silver moat

silver moat
#

I have no clue why it wouldn't work

mortal junco
#

like 10 minutes of your time

#

pleasee i need this running its for my shop

silver moat
#

nope

mortal junco
#

i actually need this to work

#

Please tell me smthing to do

silver moat
#

reinstall python could work

gleaming falcon
#

Is anyone else having issues with scheduling events now that DST has ended in the US? I don't think it's my code, as the datetime object I'm passing is both correct and explicitly in UTC

round rivet
#

id imagine a restart would be needed to correct the offset at least

#

if your machine is affected by dst

#

not exactly sure how python actually handles that

gleaming falcon
#

Restart of the machine or of the bot? The machine time is accurate, and the bot has been restarted several times. Besides, create_scheduled_event just turns it into isoformat() anyway

round rivet
#

well what does utcnow return

#

If it's not the current utc time something is wrong

gleaming falcon
#

utcnow() shows the correct offset

#

Actually I'm stupid as hell

opal flax
#

the bottom one why not like this py reactionrole enable emoji <channel> <message> <emoji>

errant craneBOT
undone parcel
#

Is there a debug tool dedicated to py-cord?

#

py-cord is not debug tool....

undone mulch
#
08.11 07:11:40 [Bot] Ignoring exception in on_connect
08.11 07:11:40 [Bot] Traceback (most recent call last):
08.11 07:11:40 [Bot] File "/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
08.11 07:11:40 [Bot] await coro(*args, **kwargs)
08.11 07:11:40 [Bot] File "/.local/lib/python3.9/site-packages/discord/bot.py", line 1025, in on_connect
08.11 07:11:40 [Bot] await self.sync_commands()
08.11 07:11:40 [Bot] File "/.local/lib/python3.9/site-packages/discord/bot.py", line 685, in sync_commands
08.11 07:11:40 [Bot] await self.http.bulk_upsert_command_permissions(self.user.id, guild_id, guild_cmd_perms)
08.11 07:11:40 [Bot] File "/.local/lib/python3.9/site-packages/discord/http.py", line 357, in request
08.11 07:11:40 [Bot] raise HTTPException(response, data)
08.11 07:11:40 [Bot] discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed```
#

How do I fix this error? It's annoying.

copper dew
#

i remember having this issue a bit ago, just to find out that i had 2 /help commands being loaded

#

check your commands, and check your cogs

fervent cradle
#

My extension fails to load, and I don't get any errors. Any ideas why?

fervent cradle
#

Problem solved

obtuse juncoBOT
#

dynoError No tag codeblocks found.

fringe socket
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
fringe socket
#

@fervent cradle

cobalt tangle
#

sourcebin

#

pastebin

#

its very hard to understand ur code via image

#

just take a part of it

#

if a button is causing error, send the class of the button

#

ok

#

is channel a message?

vale heath
#

can we restrict a bridge command to only slash command ? thenking

cobalt tangle
cobalt tangle
#

Guys how can we get the person who created a channel and who edited an user's nickname

cobalt tangle
vale heath
vale heath
#

yes

cobalt tangle
#

alr

#

i thought in normal stuff 💀

vale heath
#

np 😅

jovial shoal
#

What would be a reason why a defer might fail?
Sometimes I have to use a command 2 or 3 times for it to get to the the "bot is thinking..." stage
On the backend, I get the error:
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The pycord docs imply this is a defer failure

zenith pecan
#

how to write in callback output condition for each of my buttons in dropdown?
Maybe silly question

zenith pecan
# vale heath np 😅

Дарова, думал тут русскоговорящих нету, сможешь помочь? Я на английском толком объяснить нормально не могу

cobalt tangle
#

how can u edit a channel with an embed

#

u did channel.edit() with ur code

rough path
#

How to create embed

#

Welcome message

#

How to get welcome message when new player join

#

How

#

I used this

bot.event
async def on_member_join(member: discord.Member):
guild = member.guild
if (
guild.system_channel is not None
): # For this to work, System Messages Channel should be set in guild settings.
await guild.system_channel.send(f"Welcome {member.mention} to {guild.name}!")

#

No

#

But when new player joins no message

young bone
#

do you have Intents?

rough path
#

No

young bone
#

you need Intents

#

?tag intents

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

rough path
#

For slash commands

#

Not working

viral bay
#

henlo, i created a module with variable embeds and i want to use it in a cog, i did
from emcard import Mopt
then my command look like

    @option("name", description = "Choose or Input Card Name",
        choices = ["Mopt"], required = True)
    
    async def card(self, ctx: discord.ApplicationCommand, name):
        await ctx.send(embed = {name})```
but i get this error `embed = embed.to_dict()
AttributeError: 'str' object has no attribute 'to_dict'`
#

help is very appreciated , thank you

rough path
#

Yes

#

Intents. members=true

lost lodge
#

Hello, i need to get mutes of a member in the audit log, but i only found member update (return also nicks) how can i let it print only the mutes:

        async for thing in ctx.guild.audit_logs(user=member, action=discord.AuditLogAction.member_update):
            print("xx")```
blissful sonnet
#

How do I request buttons by the custom_id in a on_interaction event?

meager heron
#

You want message.edit, not channel.edit

nocturne canopy
#

googletrans is still broken right?

grim tangle
#

Getting this don't know what it's saying

young bone
grim tangle
#

oh ok

young bone
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

young bone
#
pip install -U git+https://github.com/Pycord-Development/pycord```
#

this one

grim tangle
#

?tag git

obtuse juncoBOT
#

dynoError No tag git found.

grim tangle
worldly tendon
#

is there a way to list the currently loaded cogs?

mortal junco
#

Someone tryna help me reformat this

worldly tendon
#

sorry but i have my own projects

mortal junco
#

i havent done anything wrong i dont think

worldly tendon
#

show the code

mortal junco
#

sorry abt not formatting it for readability

#

ill upload to pastebin

mortal junco
errant craneBOT
mortal junco
worldly tendon
#

oh dude. my eyes

mortal junco
#

it says you cannot gen rnaked no matter what

mortal junco
worldly tendon
#

its absolutly horrible. i am not kidding

mortal junco
#

i read it perfectly

#

but do u know why its sending that message no wonder what

#

Crying i really need to know i dont see why

worldly tendon
#

you need to give me a few minutes to refactor everything

mortal junco
#

yes sir

#

/ mam

#

@worldly tendon I plan to rewrite it soon I’m sorry for the hassle

#

I just really need this part fixed as I don’t see a problem

mortal junco
worldly tendon
#

i am fixing your thingy. give me some time

mortal junco
worldly tendon
#

i cant read shit in your code and need to untangle this mess. then i will see what your problem is.
you said you can read this code perfectly fine, but you cant - otherwise you would see the issue yourself.
so give me a few minutes to refactor everything

worldly tendon
mortal junco
#

what is it

worldly tendon
#

your code simply checks week and month after another. you can generate one but since you cant generate the other, it sends that message

mortal junco
worldly tendon
#

thats because some elf went to your pc at night and changed something

mortal junco
#

how exactly do i fix this

silver moat
mortal junco
#

but i swear to god it wasnt doing this before

silver moat
#

then revert changes

mortal junco
#

Whats the fix to this exactly im so confused

silver moat
#

this is why people should use git.

worldly tendon
#

how to fix it depends on how you want to proceed

mortal junco
#

i dont wanna update bot until im ready for version 2

#

where i implement json data and shit

silver moat
#

?tag nojson

obtuse juncoBOT
#

Why you should not use json files for storing data
Using json files on a smaller scale is fine, however it is would be very beneficial to switch to a real database management system;

  • JSON is a data format, not a database.
  • It is easily corrupted as it does not come with any data integrity checks when writing to the file.
  • It is not good at defining or utilizing relationships, making it very hard to store relational data.
  • When the JSON file becomes too large, you will run into performance issues since your program has to read the entire file into memory every time you want to query the data.
  • It does not include any security features that you may get when using a database management system.
worldly tendon
#

1st, dont use json
2nd, do it right the first time

#

use sqlite if you dont want to have a real database

#

peewee is an excellent tool to help you manage it

silver moat
#

^

mortal junco
#

so its not a big deal

#

it will only be reading and writing ten userids

worldly tendon
#

well, its a big deal to fix the issue you have

mortal junco
#

how was this not happening yesterday im so confused

silver moat
worldly tendon
#

im gonna upload my code to pastebin. it wont work because i cant test your code on my machine but it will give you a good tip on how to better code

worldly tendon
errant craneBOT
worldly tendon
#

its missing things, it wont work but at least you get the idea about how to actually format your code in a way that readable and debuggable

#

check from line 40. all your nested if statements and loops are gone, because they were absolutely unnessesary

#

you were loading the json file like 5 times which was also unnessesary

#

load it once, save it into a variable and only reload it if you need (or better stop using json alltogether)

#

for loops are your enemy. avoid them if you can

mortal junco
#

????/

worldly tendon
#

and? like i said, if you have to - load it once

#

also, break your code up into readable chunks that belong together
even better would be to create more functions that you can place those chunks into

#

usually you dont want your functions to be larger than 10-15 lines of code max

mortal junco
worldly tendon
#

make a plan before you start coding. think about what you need to archive your goal

mortal junco
#

Well im just really upset

#

it was working justtt fine before

worldly tendon
#

thats why you use git/github or make backups

mortal junco
#

Okay let me get this straight,

worldly tendon
#

here, let me show you some of my production code:

mortal junco
#

the reason its sending a message twice is because its generating twice at once?

worldly tendon
#

no, because its going through 2 loops

mortal junco
#

would that not fix my issue

worldly tendon
#

you will fix your issue if you dont use loops at all

#

you can keep it in one command

mortal junco
#

I dontk now how to code like u wrote

#

i didnt learn that way

#

ur example dont really show me anything

full basin
worldly tendon
worldly tendon
#

its not hard

mortal junco
#

hard with only a month of practing

round rivet
#

what's the actual issue here

mortal junco
#

theres a reason my code looks so shit

round rivet
mortal junco
#

and i really need this fixed

worldly tendon
#

well, i cant test the code. i assume its sending a message twice because there are 2 loops going on with basically the same code

mortal junco
#

it worked perfect yesterday

round rivet
#

yeah that's the exact same code twice

worldly tendon
#

not exact. but loops can be completly avoided in his code

mortal junco
worldly tendon
mortal junco
#

So when i have Month services role, and go to generate an account it says i cant

round rivet
mortal junco
#

Ugh this is the part im so bad at

#

i dont know how to fix my shit if its not erroring after i wrote it

worldly tendon
#

the quick and absolutly disgusting fix would be to give the command another parameter if you want month or week role and then only loop for what was given. the good way is to clean the code, stop the if nesting, remove all loops and fix it with brainpower

round rivet
#

also what is this for

mortal junco
#

that can generate various accounts

mortal junco
#

im just trying my best to make smthing work

worldly tendon
#

what if you can create both a weekly and a monthly loop? in your code, you would generate both at the same time

mortal junco
#

it wouldnt work like that

#

it shouldnt loop because you cant run those commands

#

if you dont have the role

#

if i only have Month role

#

it will not allow it to loop

worldly tendon
#

but you send error messages if you are not allowed to. both for week and for month

#

thats your issue isnt it?

mortal junco
#

it does the same thing

#

i honestly dont think its a loop issue in the sense ur talking abt

#

Yesterday i uploaded a video of me shwocasing the bot for my store and it didnt do that

round rivet
#

if you only have month role i'd expect it to respond with We are currently out of {service}! from the week loop as well as whatever the month loop does

worldly tendon
#

^

mortal junco
#

its completely different

worldly tendon
#

delete one loop and see if you still have the issue

round rivet
#

you have no condition that stops a loop so both will always run and produce a result unless the service isn't listed

#

in which case nothing happens

worldly tendon
#

this man (or whatever) talks my language

mortal junco
#

yep i removed a loop and problems fixed

worldly tendon
#

NO WAY. its not like thats what we said 😄

mortal junco
#

Would it not be a simple break

round rivet
#

since they both do the same thing you could condense them into one loop

worldly tendon
#

you dont need loops for this. i checked the code

round rivet
#

well i'm not going to recommend they refactor their entire command

worldly tendon
#

thats what i said too - oh nvm

mortal junco
#

And like second month of python

worldly tendon
#

again, take a look at the code i gave you already

mortal junco
#

Dude

worldly tendon
#

you dont need to use it, but at least try to understand

mortal junco
#

I DONT WRITE LIKE U I DONT KNOW HOW TO DO THAT

round rivet
mortal junco
#

i wrote it how i know how to write

full basin
#

Beginners shouldn't get into pycord

#

You don't even know how a for loop with if clauses work

mortal junco
round rivet
#

@trim blaze

worldly tendon
mortal junco
#

i realistcally dont know how to write like that

worldly tendon
#

i am but it makes no sense. learn it - thats the answer

#

without looking at how its done, you will never learn

mortal junco
#

well i only sent u half the code

#

so what u refractored really dont make sense

#

since its not the entire thing

#

what i sent u dont have the defining of the command or anything

round rivet
#

ignore this

#

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

worldly tendon
#

like i told you 4 times now, its not about the code, its about the code style.
dont nest if statements, dont use foor loops if you can, put your code in blocks that are readable

#

i guess "try to make your code indent as little as possible"

full basin
#

And actually understand your code lol

mortal junco
#

it was working PERFECTLY FIne yesterday

#

and now its broke

worldly tendon
#

:harold:

#

cause some elf went onto your pc at night and messed it up

worldly tendon
mortal junco
#

theres litteral a showcase on the bot

#

of it working

worldly tendon
#

i told you the very basics of how to write better code. accept it and learn or ignore it and keep being unable to fix the issues you have

mortal junco
#

and i dont not know how to use one

worldly tendon
#

and i dont not know how to use one
you used 2 in your code

#

for x in y:
is a loop

#

its 3 am, why am i dealing with this

mortal junco
#

yep

worldly tendon
mortal junco
#

I’ll look into it

#

Thank you for your time

round rivet
#

die

worldly tendon
#

😂

round rivet
#

why do user made bots have access to this

#

it shouldn't be like that

worldly tendon
#

wdym with "this"?

round rivet
#

this channel

worldly tendon
#

ah

#

well, you can restrict access on a per channel basis

#

as long as the bot doesnt have admin rights

waxen whale
mortal junco
#

But im really slow and im having the stupidest issue of my lfie

mortal junco
#

Please dont get mad 💀

#

i cant figure out how i would run the bot i see ur using cog for something involivng the bto

#

but what that is idk what cog is

#

Do i not just do client.run{json.config["token"]

mortal junco
worldly tendon
#

a cog is basically just a way to split your code into multiple files to make it more readable. you dont need to use a cog, i was just working in a cog file and placed your code in there.

mortal junco
#

is there a different way i should be doing it

worldly tendon
#

read the config file and write it to a variable, then use that variable instead of loading the config file

mortal junco
#

client.run{jsonConfig['token']}

#

wold this not work or am i doing it totally wrong

worldly tendon
#
jsonConfig = json.load(open('config.json', 'r'))
# ...
client.run{jsonConfig['token']}
#

yes

mortal junco
#

oh i kinda had it

#

syntax error :0 im slow xD

#

im so confused

#

hows that a syntax error

silver moat
#

...

round rivet
#

come on

mortal junco
round rivet
#

that wouldn't even work in JavaScript

mortal junco
round rivet
#

() instead of {}

silver moat
round rivet
#

just the curly braces

#

made me think of js

mortal junco
#

Im so slow

silver moat
#

}

#

)

mortal junco
#

yeh ik

#

i fixed it now i gotta workout my other problems

#

in this whole thing i only open the json twice

#

but i gotta figure out why my startup isnt working

worldly tendon
#

i just copied your code, and it had brackets instead of () lol
i didnt even notice

#

how the fuck did you even start your bot previously

mortal junco
#

and reading "token"

#
client = discord.Bot()
 
if os.path.exists("accounts"):
    pass
else:
    os.mkdir("accounts")
 
if platform.system() == "Windows":
    os.system("cls")
else:
    os.system("clear")
 
try:
    json.loads(open("config.json", "r").read())
except Exception:
    print("[ERROR] Config File missing")
    input()
try:
    json.loads(open("config.json", "r").read())["token"]
except Exception:
    print("[ERROR] Discord Token not set")
    input()
try:
    json.loads(open("config.json", "r").read())["guild_id"]
except Exception:
    print("[ERROR] Guild ID not set")
    input()

jsonConfig = json.load(open('config.json', 'r'))```
#

is it ok to do this

worldly tendon
#

one sec

mortal junco
errant craneBOT
mortal junco
#

i think i did it properly

#

if i didnt imma just heda to bed

#

💀

worldly tendon
#
import discord
import os, json

client = discord.Bot()
jsonConfig = None

os.system('cls' if os.name == 'nt' else 'clear')
os.makedirs("accounts", exist_ok=False)

try:
    jsonConfig = json.loads(open("config.json", "r").read())
except Exception:
    print("[ERROR] Config File missing")
    input()

if "token" not in jsonConfig:
    print("[ERROR] Token missing")
    input()

if "guild_id" not in jsonConfig:
    print("[ERROR] Token missing")
    input()
mortal junco
#

like = none and then a second time jw

worldly tendon
#

because it makes sure that the variable exists outside the scope of the try except block

mortal junco
#

Your code helped me understand a lot more

#

Only issue now is ctx and self are being blurred grey and the command isn’t being shown in the app but I’ll try my best tot trouble shoot before bothering anyone

#

I’m trying my best 💀 I just hope I did the help command right if so I understand

worldly tendon
mortal junco
worldly tendon
#

sure

mortal junco
#

my problem rn is this tis say its not accesible by pylance

#

never seen that

mortal junco
# worldly tendon sure
def helpEmbed(ctx):
    embed = discord.Embed(title= "Light Store help command", description="Usage: /generate <service name>, /stock", color=0x46a9f0)
    embed.add_field(name="Week Plan", value="``Ranked``, ``Skinned``")
    embed.add_field(name="Month Plan", value="``Ranked``, ``Skinned``")
    return embed
@commands.slash_command(name="help", guilds_ids=[jsonConfig["guild_id"]])
async def help(self, ctx):
    await ctx.respond(embed=self.helpEmbed)
worldly tendon
#

why are you wrapping ranked and skinned in 2 backticks?

this looks acceptable. You dont reuse the "helpEmbed" code somewhere else so you can put it directly into help command. but otherwise it looks good (and its not really a problem )

mortal junco
mortal junco
#

u said it looks good but its not picking up the / command

worldly tendon
# mortal junco okay, i thought it looks cooler making it a value ngl

no its fine, but one backtick is enough.

@commands.slash_command(name="help", guilds_ids=[jsonConfig["guild_id"]])
async def help(self, ctx):
    embed = discord.Embed(title= "Light Store help command", description="Usage: /generate <service name>, /stock", color=0x46a9f0)
    embed.add_field(name="Week Plan", value="`Ranked`, `Skinned`")
    embed.add_field(name="Month Plan", value="`Ranked`, `Skinned`")
    await ctx.respond(embed=embed )

any idea whats cuasing this?
the popup says whats wrong. "url" is not accessed.
you are not using url inside the function (and you are also not passing a url parameter).
just remove that url argument

#

the def __init__ function is for when you are in a class. since you are not, it wont be executed.

#

just saying

mortal junco
#

so i need to move it

#

i wasnt really sure what it was fure

#

never had to use it

#

Like everything works fine no errors

#

no slash command pops up

worldly tendon
#

i dont know where your slash command code is in the file. thats something you have to figure out on your own

#

its 4:30 am and ill go to bed now

mortal junco
#

Last thing if anyone is avaliable

peak chasm
#

how to modify the /help command

mortal junco
peak chasm
#

I tried to create the /help command but it tells me that I cannot modify it

mortal junco
#

@waxen whale i almost have it finished ikkkk u want ot help me with one last thing then bots rewritttten!

#

its asking for weird ass paramaters

waxen whale
#

Who tf are you

mortal junco
#

U where helping me ealier

mortal junco
waxen whale
#

I’m in bed…. And plun and squid seems to be away too. Try tmrw

mortal junco
#

i just really wish i could fix this rn and id be good

peak chasm
mortal junco
peak chasm
#

:/ <3

fringe socket
#

I think I know what's wrong

fringe socket
#

How do they do this with the bots?

proven ferry
#

pls help me

fervent cradle
#

Is there any alternative to process_commands?

#

Ping me if you have an answer

full basin
fervent cradle
full basin
#

You're overriding on_interaction?

fervent cradle
full basin
#

I don't see why you'd need to process a command then

undone mulch
#

Dumb Python question but if I created a database like this how do I use dbb["key"] instead of db["key"]. I have two databases via json in my code.

#

And the db[""] is getting mixed up with the dbb[""]

full basin
#

Or use an actual database

fluid tusk
#

that

cobalt tangle
#

Send me ur Bot() code and ur on_message

mortal junco
#

Does anyone know a way to fix my error

cobalt tangle
mortal junco
#

I rewrote the bot like I was told, and now I’m having this issue

cobalt tangle
#

send ur error first

mortal junco
cobalt tangle
#

and code

cobalt tangle
mortal junco
#

It’s not an error it’s just giving unneeeded parameters

mortal junco
#

I don’t got rn 💀

cobalt tangle
#

then cant help u

#

#help-rules

undone mulch
#

Json database works I don't know why people preach get a real database

#

I've personally stored over 500k game IDS in json and never once had an issue

cobalt tangle
cobalt tangle
undone mulch
mortal junco
#

commands.slash_command(name="generate", guild_ids=[jsonConfig["guild_id"]])
async def generate(self, ctx, service_name):
if str(ctx.channel.id) != jsonConfig["gen_channel"]:
await ctx.respond(f"You can only gen in: <#{jsonConfig['gen_channel']}>", ephemeral=True)
return

    service_name = service_name.lower()
    if service_name not in self.week_services and service_name not in self.month_services:
        await ctx.respond("Invalid service name", ephemeral=True)
        return

    if str(jsonConfig["week_role"]) not in str(ctx.author.roles):
        await ctx.respond(f"You cannot gen {service_name}!", ephemeral=True)
        return

    
    if not os.path.exists(f"accounts/{service_name}.txt"):
        await ctx.respond(f"We are currently out of {service_name}!", ephemeral=False)
        return


    data = None
    with open(f"accounts/{service_name}.txt", "r+") as accounts:
        data = accounts.readlines()
        accounts.seek(0)
        accounts.truncate()
        accounts.writelines(data[1:])
    try:
        user = await self.client.fetch_user(int(ctx.author.id))
        await user.send(embed=self.generateEmbed(service_name, data, "https://media.giphy.com/media/3o7bufVwr3qbu9qYX6/giphy.gif"))
        await ctx.respond("Account Generated, check your DM")
    except Exception:
        await ctx.respond(f"We are currently out of {service_name}!", ephemeral=True)
undone mulch
cobalt tangle
undone mulch
#

Works for db

mortal junco
cobalt tangle
#
commands.slash_command(name="generate", guild_ids=[jsonConfig["guild_id"]])
    async def generate(self, ctx, service_name):
        if str(ctx.channel.id) != jsonConfig["gen_channel"]:
            await ctx.respond(f"You can only gen in: <#{jsonConfig['gen_channel']}>", ephemeral=True)
            return

        service_name = service_name.lower()
        if service_name not in self.week_services and service_name not in self.month_services:
            await ctx.respond("Invalid service name", ephemeral=True)
            return

        if str(jsonConfig["week_role"]) not in str(ctx.author.roles):
            await ctx.respond(f"You cannot gen {service_name}!", ephemeral=True)
            return


        if not os.path.exists(f"accounts/{service_name}.txt"):
            await ctx.respond(f"We are currently out of {service_name}!", ephemeral=False)
            return


        data = None
        with open(f"accounts/{service_name}.txt", "r+") as accounts:
            data = accounts.readlines()
            accounts.seek(0)
            accounts.truncate()
            accounts.writelines(data[1:])
        try:
            user = await self.client.fetch_user(int(ctx.author.id))
            await user.send(embed=self.generateEmbed(service_name, data, "https://media.giphy.com/media/3o7bufVwr3qbu9qYX6/giphy.gif%22))
            await ctx.respond("Account Generated, check your DM")
        except Exception:
            await ctx.respond(f"We are currently out of {service_name}!", ephemeral=True)
#

i did it myself

#

why is there an indent

#

below commands.slash_command

mortal junco
#

It’s just copied like that

#

It’s not actually written like that

cobalt tangle
#

and send ur Class

#

ok

mortal junco
#

I don’t have the whole code

cobalt tangle
cobalt tangle
mortal junco
#

I removed that in my real code

#

I don’t use commands.cog

cobalt tangle
#

what do u use

mortal junco
#

def init

cobalt tangle
#

def __init__(commands.Cog)

#

if u dont add that, it wont work

mortal junco
#

It has to be like that

cobalt tangle
#

if u didnt add it, now u know whats ur issue

mortal junco
#

Okay, I removed it because I didn’t know how to use it

cobalt tangle
#

u need commands.Cog or it doesnt work

#

now thats ur issue

cobalt tangle
#

Pycord is a complex library that requires you to know Python concepts like OOP, async-await, etc. Run ?tag lp to find resources where you can learn Python.

mortal junco
#

I’m sorry,

cobalt tangle
undone mulch
#
09.11 13:29:33 [Bot] /syst.py:11: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
09.11 13:29:33 [Bot] client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
09.11 13:29:33 [Bot] RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

I'm getting this error.

def load(client, path, filename):
    import os
    if os.path.isdir(f"{path}/{filename}"):
        for file in os.listdir(f"{path}/{filename}"): load(client, f"{path}/{filename}", file)
    else:
        if filename.endswith(".py"):
            try:
                client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
                print(f"{w}{brt}Loaded {filename} from {path}{rst}")
            except Exception as e:
                print(f"{w}{brt}Failed to load {filename} from {path}{rst}:\n{e}\n")```
#

Why?'

mortal junco
undone mulch
#

This error makes no sense..

loud holly
#

I'm guessing this means that when the user is verifying via the Rule Screen right?

full basin
#

Yes.

loud holly
#

is there an event to register the user agreeing the Rule Screen?

#

actually

#

I probably might be able to get it via bot.wait_for

#

and wait for the interaction I think

round rivet
loud holly
peak chasm
#

How do I make "category" optional?

#

when I test the bot I get that the field is required

proud mason
peak chasm
#

thanks, i did a test with "category=false" but it didn't return "none" now it does, thanks!!
<3 <3 <3 <3 <3

proud mason
#

Np!

silent meadow
#

Hey yo!

jovial shoal
#

I'm getting so many failed defers lately, leading to 404 Not Found (error code: 10062): Unknown interaction errors
Is anyone else noticing an increase in response problems?

silent meadow
#

Real quick, how do I get the profile picture of any user?

jovial shoal
#

user or member class, avatar attribute

silent meadow
#

alr thianks

#

i can use member.avatar_url correct+

jovial shoal
#

I believe its member.avatar.url

#

but yeah

#

Is there a different between ctx.defer() and ctx.interaction.response.defer() should I be using one over the other?

grizzled sentinel
#

No the first one is just a shortcut (alias) of the second one.

silent meadow
#

why cant I access bot object in cogs?

grizzled sentinel
#

You will need to receive the bot object in the init.

def __init__(bot):
    self.bot = bot
meager mica
#

then when you refer to bot do self.bot whatever u want

#

so memeber = self.bot.owner

indigo badger
#

So I was working on a new thing in my command and I was trying to store a member object but when I went to run the command it popped up this:

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 127, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 911, in _invoke
    await self.callback(ctx, **kwargs)
  File "/home/container/Bot.py", line 457, in warn
    await addwarn(ctx, reason, member)
  File "/home/container/Bot.py", line 125, in addwarn
    await cursor.execute('''INSERT INTO warns(user_id, reason, time, mod guild_id, warnID) VALUES(?,?,?,?,?,?)''', (user.id, reason, int(datetime.now().timestamp()), ctx.member.name, ctx.guild.id, x))
AttributeError: 'BridgeApplicationContext' object has no attribute 'member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 1008, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 359, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'BridgeApplicationContext' object has no attribute 'member'
#

Anyone know a fix to this?

#

As I did the same format as I did for store the guild in the DB and it worked.

#

Anyone know or is having the same problem as me?

indigo badger
indigo badger
#
async def addwarn(ctx, reason, user):
    x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16))
    async with Client.db.cursor() as cursor:
        await cursor.execute('''INSERT INTO warns(user_id, reason, time, mod guild_id, warnID) VALUES(?,?,?,?,?,?)''', (user.id, reason, int(datetime.now().timestamp()), ctx.member.name, ctx.guild.id, x))
    await Client.db.commit()
#

That is the code it is erroring on.

simple canopy
#

no its not?

#

it's ctx.author if you want to access member who used the command

#

and just user if you want to access the user that was warned

#

@indigo badger

fallow hawk
#

anyone know why i would get ModuleNotFoundError: No module named 'dotenv' even thought i have it installed?

#

ok i figured out why i get that but now i need to change my interpreter

meager heron
loud holly
meager heron
# loud holly wdym?

return by itself returns an implicit None. ctx.respond returns either an Interaction or a WebhookMessage. It doesn't matter in this particular function, but you should be mindful of your return types

young bone
#

lol

loud holly
#

and it works fine for me

#

isn't the point though that they "exist out" if a condition isn't met?

meager heron
#

I said it doesn't matter in this particular instance. But your code should reflect your intent. If you're returning some object, it suggests you expect/intend that object to be used somewhere. If that's not the case, then you shouldn't return the object

#

There's also nothing gained by reducing line count here

loud holly
#

ohhh that's what u meant yeah

loud holly
meager heron
#

Why

loud holly
#

it just seems cleaner

meager heron
#

If your calling function cares about the return value, you could be shooting yourself in the foot

#

And your intent is less clear. My first question on reading this code is "what are you doing with that return value?"

loud holly
#

if I was going to return a value that was needed I'd have used to approach that you were discussing

fallen cove
#

are multi member select option coming to slash commands?

simple canopy
#

if it doesn't, it won't do anything

meager heron
#

It's pretty trivial to come up with examples that will cause problems

simple canopy
meager heron
#

Most people aren't using annotations, TBH

simple canopy
#

bad for them smh

young bone
loud holly
meager heron
#

You're coding, not playing golf. You gain nothing by saving that one line, and you lose clarity

loud holly
#

it's how I program ¯_(ツ)_/¯

gleaming falcon
#

Is there a way of live-registering slash commands? Like you can use reload_extension() to reload a Cog, but it doesn't

I tried using sync_commands(), but getting an error that "names should be unique", despite the fact that they are (and this error doesn't happen when I restart the bot, so there must be something else that needs to be done)

loud holly
peak chasm
#

how to i add description and options?

#

i try this

loud holly
#
category: discord.Option(discord.CategoryChannel, description="")
#

this is how I'd do it

mortal junco
#

Ugh ive fixed everything but i have my last issue i need to fix

#

@worldly tendon told me and gave me a instructed guide to fix it ive done everything to fix the loop but i dont understand how slash commands work exactly so im having paramter issues

worldly tendon
#

what do you not understand about them?

mortal junco
worldly tendon
#

explain "weird paramaters"

mortal junco
#

idk how to edit that as i have to implement self

full basin
#

Are you in a class?

worldly tendon
#

remove "self"

mortal junco
#

i have to have self

full basin
#

You dont

mortal junco
mortal junco
peak chasm
loud holly
mortal junco
full basin
#

Then why are you using self?

#

You're not a in class

worldly tendon
#

again, thats from the code i did for you while being in a cog. since you are not in a class, you need to edit that

full basin
#

This is basic python

loud holly
full basin
mortal junco
#

@full basin asking sullix not you

#

your a dickhead

#

couldnt care less abt ur help

worldly tendon
#

remove self. everywhere and it should work

full basin
#

I'm whatever you want honey. You shouldn't be developing a bot if you don't know what a class is

mortal junco
worldly tendon
worldly tendon
mortal junco
#

what am i supposed to be doing making a basic print command , i really just am using this to practice

young bone
full basin
#

Basic Python knowledge is a requirement to ask for help.

worldly tendon
#

ah so people without knowledge are not allowed to ask and learn?

full basin
#

People with no knowledge shouldn't be getting into OOP if don't know how a class works

mortal junco
#

i know how a class works..

worldly tendon
#

you are really annoying dude

#

go hate somewhere else

#

@mortal junco send me the code in a pastebin

full basin
#

¯_(ツ)_/¯

loud holly
mortal junco
worldly tendon
mortal junco
#

it was ugly

#

but it worked, and i was happy

worldly tendon
#

no it didnt work, thats why you asked for help lol

loud holly
#

it was the date time thing

#

iirc

mortal junco
#

bro i have a video of it working

worldly tendon
#

no

mortal junco
#

i promise u a elf came

worldly tendon
#

send me the code dude

mortal junco
worldly tendon
#

i want to get over this

mortal junco
peak chasm
loud holly
worldly tendon
#

why would you do that?

peak chasm
#

that worked for me xd

loud holly
#

ohhhh

worldly tendon
loud holly
mortal junco
errant craneBOT
loud holly
mortal junco
worldly tendon
errant craneBOT
worldly tendon
#

please compare both files so you see the differences

mortal junco
worldly tendon
mortal junco
#

now that youve done this i can actually do what i wanted to do as well

worldly tendon
#

i dont think they are in the right. no one starts as a master and learning by doing is the way to go. Even if its a discord bot. Asking for help if you dont know something isnt bad, as long as you tried to fix it on your own.

python has so many different modules and tricks that one person simply can not learn everything without someone elses input.

#

And even they had to ask for help when they started coding, so pretending that you have to be a fucking 2 billion iq mastermind before asking for help is just plain stupid.

mortal junco
waxen whale
worldly tendon
#

no worries, hope you manage to get your stuff done

mortal junco
worldly tendon
#

nice. but make sure to read about how databases work. its easy to mess up and really hard to make actually good.
i dont think you need to aim for peak performance, however thats what i usually like to do

#

take you time with that

loud holly
#

not even sure if it's called async library or something else

gleaming falcon
meager heron
#

Is there any benefit to using it if your queries are only in single-digit milliseconds?

true root
#

I hope someone can answer my python question, thanks a lot!

worldly tendon
meager heron
#

I think the answer is no, but I may as well ask: Is there any way of setting profile information for a webhook?

waxen whale
#

nice automod block Kek

mortal junco
#

still having issues that i have no way to debug.. it looks like its perfect but idk why 🙂

mortal junco
worldly tendon
#

sorry, cant talk. pokemon scarlet leaked early for the switch and i am installing it rn

waxen whale
mortal junco
#

issue is

#

even though i have proper roles

waxen whale
#

it might be worth opening a own thread for your questions. General help is normally for small things 😅

gleaming falcon
#

🎶 All the ... small things

mortal junco
#

@worldly tendon well i found a fix to all my problems thats so simple

#

idk why i didnt do it

#

to begin with

worldly tendon
#

?

mortal junco
#

yk how i wanted it for a month

#

and for a week

#

i can just use dyno, and name the role one role and use dyno to add the time

worldly tendon
#

Uh

mortal junco
worldly tendon
mortal junco
#

i havent played the new gens

worldly tendon
#

It's not even out yet

#

Release is in a little over a week

round rivet
#

chat in #general please

worldly tendon
waxen whale
meager mica
#

this is more python help but i just cant figure out how to make this variable global without being in a function py class TicketView(discord.ui.View): def __init__(self, moderators, db, button_color=None): super().__init__(timeout=None) self.modertators = db.moderators self.db = db self.button_color = button_color # self.title = title # self.description = description # self.color = color global button_color button_color = button_color global button_colorr @discord.ui.button( label="Open a ticket", style=button_color, custom_id="persistent_view:green", )

limber urchin
meager mica
#

I think it has to be but I'm not sure a better way

limber urchin
#

customizable from the code, or by users?

#

also button colors can't be fully custom., the only options are Primary (blurple), Secondary (gray), Success (green) and Destructive (red)

#

and since you're already setting the property in your init function, you can just reference self.button_color from any method in your class

#

no need for a global

meager mica
#

That's why all functions in classes have self as first arg

limber urchin
#

Yeah, I know

#

I don't see why you would need those variables outside of a function though

fluid tusk
#
import logging

import discord

intents = discord.Intents.default()
bot = discord.Bot(intents=intents)

logger = logging.getLogger("test")
logger.setLevel(logging.INFO)

logger.info("log")

@bot.event
async def on_ready():
    print("---- bot ----")
    print("name:", bot.user.name)
    print("id:", bot.user.id)
    print("-------------")

bot.run(token)``` why doesnt this log anything
silver moat
limber urchin
# meager mica To set the button color

You could just do

@discord.ui.button(label='...', style=discord.enums.ButtonStyle.secondary, ...)
async def my_button(self, button: discord.ui.Button, interaction: discord.Interaction):
    button.style = self.button_color

and then update the view

meager mica
#

Ohhhh

#

Icic I think

#

So basically it's possible to change button color in the function itself

limber urchin
#

Yes, pretty sure that's the only way. It's possible that it might cause the button to have a default style for a brief moment before the view gets updated though

#

But in that case I'd just temporarily make the button label something like "Loading..."

meager mica
#

So this is persistent view will it somehow reset itself restart or any other bugs

#

Cuz function only ones when they click doesn't it?

fluid tusk
#

instead of setting it to global

limber urchin
# meager mica Cuz function only ones when they click doesn't it?

Yeah, that would only update the style on click. You can always access the buttons from the created view with the .children property. So something like

view = MyView()
for button in view.children:
    button.style = discord.enums.ButtonStyle.primary

Would change all buttons to the primary style

#

Or just access a specific index, if it's one specific button you want to update

meager mica
fervent cradle
#

does pycord work with python 11

silver moat
#

only on master branch

meager mica
fervent cradle
#

Ok update to python 11

meager mica
#

I've been using it since day 1

fervent cradle
silver moat
#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

fervent cradle
#

i did read the docs, and it isnt homework lmao

#

anyways, i have it solved

oak elm
#

Does discord not support modal with select menu?

#

class FeedbackModel(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(
            discord.ui.Select(
                options=[
                    discord.SelectOption(label="Inner", value="inner"),
                    discord.SelectOption(label="Outter", value="outter")
                ]
            ),
            discord.ui.InputText(
                label="Short Input",
                placeholder="Placeholder Test",
            ),
            discord.ui.InputText(
                label="Longer Input",
                value="Longer Value\nSuper Long Value",
                style=discord.InputTextStyle.long,
            ),
            *args,
            **kwargs,
        )
#

It raised error following

#
Ignoring exception in view <FeedBackView timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Submit a feedback' emoji=None row=None>:
Traceback (most recent call last):
  ...
"/Users/maoxiandaozhenhaowan/Desktop/Code/discord-bot-feedback/.venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 215, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (4,).
fringe socket
young bone
oak elm
#

So just pycord not support it?

fringe socket
#

No.

#

it's a discord limitation

oak elm
#

So at the moment, discord does not support modal with select menu?

fringe socket
#

Yes

oak elm
fringe socket
#

yes thank my hearts

#

i have two

#

im a time lrod

fervent cradle
#

Does anyone know a good way to host my bot with no down time?

full basin
#

Pay for one?

oblique river
#

I want to open "MyModal" but it dont work and it show no errors

    @commands.user_command(name="Modal")
    async def modal(self, ctx: discord.ApplicationContext, member: discord.Member):
        modal = MyModal(title="Review")
        await ctx.send_modal(modal)```
proud mason
#

It will always mess up stuff

#

Rename the function to smth like modal_cmd

#

The command name is alright

oblique river
#

Ah ok thats maybe the problem thank you

oblique river
cyan quail
#

what does your MyModal class look like

thin sierra
#

do user_commands have cooldown?

cyan quail
#

uhh discord has a ratelimit on all application commands

#

but you have to be straight up spamming them to actually hit it

proud mason
oblique river
proud mason
oblique river
thin sierra
#

well yes but slash commands have cds, but user commands gives this error

cyan quail
proud mason
cyan quail
proud mason
cyan quail
#

perhaps that is your issue

oblique river
#

?

cyan quail
oblique river
#

No its because i put await in the front of "interaction.response.send_message(embed=embed, ephemeral=True)"

#

i remove it now ...

cyan quail
#

it's meant to be awaited...

#

for the 3rd time, you've showed us Select while your command uses MyModal

#

we still don't know what MyModal looks like, or maybe you're meant to be using Select in the command instead

oblique river
#

Select is only the name of the class that is not important

cyan quail
#

it quite literally is in this case

thin sierra
cyan quail
thin sierra
#

is this a common issue?

oblique river
#

I can call it something else if Select is so bad

cyan quail
#

do you have a command or function named discord

cyan quail
#

but you showed us the code for Select and not MyModal, so we still don't know if anything is wrong

oblique river
#

I know and the modal he gets yes from the class "MyModal"

cyan quail
#

we need to see the code of MyModal

oblique river
#
class Select(MyModal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(...)

    async def callback(self, interaction: discord.Interaction):
      ...

    @commands.user_command(name="Modal")
    async def modal(self, ctx: discord.ApplicationContext, member: discord.Member):
        modal = MyModal(title="Review")
        await ctx.send_modal(modal)```
cyan quail
#

that's not

oblique river
#

I have sent everything

cyan quail
#

my guy

oblique river
#

There is no more or less

cyan quail
#

somewhere you have done class MyModal

#

show us that instead

oblique river
#

That's the Select...

proud mason
cyan quail
#

wtf is MyModal then

#

it doesn't exist in the library, so it's a custom class you've made

proud mason
oblique river
#

Oh I sent the wrong code with MyModal it actually says Select un not MyModa

#
class Select(MyModal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(...)

    async def callback(self, interaction: discord.Interaction):
      ...

    @commands.user_command(name="Modal")
    async def modal(self, ctx: discord.ApplicationContext, member: discord.Member):
        modal = Select(title="Review")
        await ctx.send_modal(modal)```
#

This is my current code

proud mason
#

Is the command inside of the Select class?

oblique river
#

So the normal

cyan quail
#

you still aren't answering the question

#

MyModal is very likely where the error is

proud mason
cyan quail
#

and you aren't showing it

thin sierra
proud mason
oblique river
cyan quail
#

so it's working? fair enough

proud mason
#

Then what's the issue?

#

Lmao

oblique river
#

Sure just have the problem that if I do not submit the modal presses that the bot then in the chat has the here all the time stand

proud mason
cobalt tangle
#

@vivid plaza

vivid plaza
#

yes

#

Wait I will send the code. Let me just open VS Code

#
def check(message):
            c.execute("SELECT price FROM accounts WHERE type=?", (type,))
            price = c.fetchall()
            try:
                print(message.content.startswith)
                print(message.mentions[0].id)
                print(message.author.id)
                print(message.content)
                print(message.content.startswith(f"**💰 | {message.author.display_name}, has transferred "))
                print(message.mentions[0] == 994347081294684240)
                print(message.author.id == 282859044593598464)
                print(str(price[0][0]) in message.content)
            except IndexError:
                return False
            return message.content.startswith(f"**:moneybag: | {message.author.display_name}, has transferred ") and message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and price[0][0] in message.content
#

it returns False False True True

#

@cobalt tangle

cobalt tangle
#

hm

vivid plaza
#

Do you need to see the msg again ?

cobalt tangle
#

yes

#

and what is type

vivid plaza
#

I declared type here

cobalt tangle
#

what is type

#

like value

vivid plaza
#

value That will be given by the user

cobalt tangle
#

what avlue

#

example

#

and what does price = c.fetchall() give u

vivid plaza
#

it gives me the price of something from the database

#

(an int)