#Basic Pycord Help (Quick Questions Only)

1 messages · Page 34 of 1

fervent cradle
#

How do I know which button the user clicked though, sorry for my ignorance. I've been using discord.ui with 'view's, but I have no idea how to simply know which button the user clicked and store it in a variable for later use.

e.g.:

button = Button(label="Yes!", style=discord.ButtonStyle.green, emoji="✅")
view = View()
view.add_item(button)
await ctx.respond(embed=embed, view=view)
limber urchin
fervent cradle
#

Hmm that's interesting, thanks. But my question remains though... say in this example, how to see whether the user actually clicked the "Press!" button? And how would I store that information to use later (in the "counter" command decorator itself) e.g.

if button_clicked:
  #do this
else:
  #do this
limber urchin
#

Set an attribute of self on your View class and store your information in that

cold hamlet
#

Is pyenv 3.11 compatable?

#

not pyenv

#

pycord

#

I reset my raspi and I've had to install so many pixyz and pyxyz things today my mind is completely scrambled lol

cyan quail
#

on master branch yes

cold hamlet
#

ok awesome thanks

cyan quail
#

unless you're using commands.Flags

#

otherwise yeah

cold hamlet
#

I didn't even know that was a thing tbh

harsh dust
#
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import discord
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\__init__.py", line 22, in <module>
    from . import abc, opus, sinks, ui, utils
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 57, in <module>
    from .voice_client import VoiceClient, VoiceProtocol
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\voice_client.py", line 54, in <module>
    from .gateway import *
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\gateway.py", line 37, in <module>
    import aiohttp
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\__init__.py", line 6, in <module>
    from .client import (
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 35, in <module>
    from . import hdrs, http, payload
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\http.py", line 7, in <module>
    from .http_parser import (
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\http_parser.py", line 15, in <module>
    from .helpers import NO_EXTENSIONS, BaseTimerContext
  File "C:\Users\Gloryness\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 667, in <module>
    class CeilTimeout(async_timeout.timeout):
TypeError: function() argument 'code' must be code, not str
#

I seem to be getting this error

#

I have no clue why. I updated py-cord to latest version and its still producing the same error

young bone
#

How can I count the messages of a channel? I was trying to get the channel with fetch_channel() and other stuff but I get this error everytime

TypeError: 'HistoryIterator' object is not iterable
#
channel = await interaction.client.fetch_channel(interaction.channel_id)
for message in channel.history(limit=None):
    await message.delete()
cold hamlet
#

async for

cyan quail
#

it's async for

young bone
#

oh

#

thx!

harsh dust
foggy mortar
#

how can you make a code run each second?

#

or do u have to just use an asyncio loop?

fervent cradle
plush meadow
#

Is there a proper way to edit an ephemeral message?

#

particularly one that is sent like so

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

editing this message throws a 404

plush meadow
#

you can't edit it at all? son of a gun

#

i'd assume there's no deleting it either then

limber urchin
#

Discord did implement deleting of ephemeral messages in their API, so it should be possible

foggy mortar
#

inside the __init__ function or just outside?

young bone
foggy mortar
#

ok um i will try

young bone
foggy mortar
#

yes i forgot to use the function.start() lol

#

i used user=await discord.utils.get(self.bot.get_all_members(),id=i) and it says TypeError: object NoneType can't be used in 'await' expression,isnt client.get_all_members() a generator object

rare ice
#

So I’ve had an idea of a leveling system that where the XP required for each level up increases, what is the best way for the bot to calculate this when calculating someone’s level? Or should I just make a data dictionary manually with all the required XP for each level, which is a lot to do since I wanted a max level of 100, which is 100 keys and values to do.

full basin
#

Some math equation?

#

If you're looking for increased XP for every level, you could use a linear function

harsh dust
#

how do I go by deleting a channel?

#

nvm found out

fervent cradle
#

Traceback (most recent call last):
File "C:\Users\Wacky\Documents\FoolishBot\main.py", line 22, in <module>
bot.load_extension(f"{directory[2:]}.{filename[:-3]}")
File "C:\Users\Wacky\Documents\FoolishBot.venv\Lib\site-packages\discord\cog.py", line 886, in load_extension
elif (spec := importlib.util.find_spec(name)) is None:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib.util>", line 94, in find_spec
ModuleNotFoundError: No module named 'n commands'

#
import discord
import os

from dotenv import load_dotenv
load_dotenv()
from discord.ext import commands


bot = commands.Bot(intents = discord.Intents.all(),command_prefix='!', activity = discord.Activity(type=discord.ActivityType.playing, name="BennixMC"))
@bot.event
async def on_ready():
    print('I am online')
@bot.event
async def on_application_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.respond(f'This command is on cooldown, Try again in {round(error.retry_after)} seconds')
directories = ["Fun commands", "./Utility Commands","./Embeds"]
for directory in directories:
    for filename in os.listdir(directory):
        if filename.endswith(".py"):
            
          bot.load_extension(f"{directory[2:]}.{filename[:-3]}")

bot.run(os.getenv("TOKEN"))```
#

Whats giving me this error?

winter condorBOT
#

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.")
round rivet
foggy mortar
limber urchin
#

Do you have any conflicting libraries installed? Such as discord.py?

foggy mortar
#

nope

#

it worked 2 minutes ago with exact same libraries installed

#

i just added a few lines of code

meager heron
#

Is anyone having trouble with being rate-limited today?

thorn reef
#

Is there a way to make a slash command interaction last longer?

fervent cradle
#

or am i blind

fervent cradle
limber urchin
meager heron
limber urchin
meager heron
#

I'll ask on their official server. Thanks

round rivet
fervent cradle
limber urchin
#

You're removing the first two characters of the directory for some reason

#

Which means you end up with 'n commands'

fervent cradle
limber urchin
#

In your code, you're removing the first two letters of the directory you are trying to load the cog from

#

Is there a reason for this?

fervent cradle
limber urchin
#

I'm assuming this was copied from the internet then?

fervent cradle
#

Nope the main file was old code from a previous bot i had made (to prevent re typing the same code)

#

it was from a wehile ago

#

while*

fervent cradle
limber urchin
#

Try it and see

fervent cradle
#

thanks it works, weird as it loaded the other command i had in another directory.

fervent cradle
# limber urchin Try it and see

I am trying to connect to github with my project.
I get to push it then get this error.
error: failed to push some refs to github link

#

Is there a way to use send_modal() to a specific channel, rather than the channel of ctx? I tried this, but it didn't work.

await self.bot.get_channel(int(1041456824894890064)).send_modal(modal)
young bone
#

channel = ...
await channel.send_modal()?

fervent cradle
fervent cradle
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'TextChannel' object has no attribute 'send_modal'

fervent cradle
#

hmm, that's a shame

#

I guess i'll have to store the output myself and create a new embed to send to another channel

fervent cradle
#

Oh i found an easier way, say add the line in the callback function in the Modal class instead. Works like a charm.

await self.bot.get_channel(int(1041456824894890064)).send(embeds=[embed])
fervent cradle
#

I found something that you may find useful, im not sure if its exactly what your looking for

#

but i thought id try help

#

Its just my code from a suggestions command

#
from pymongo import MongoClient
from discord.ext.commands import slash_command
from discord.ext import commands
from discord.ext.commands import Cog
import datetime

class Suggestions(discord.ui.Modal):
    def __init__(self,bot,*args, **kwargs) -> None:
        self.bot = bot
        super().__init__(*args, **kwargs)
        self.add_item(discord.ui.InputText(label="Your Suggestion: ", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        m = await interaction.response.send_message("Suggestion send!", ephemeral=True)
        suggest = discord.Embed(title=f"Suggestion by {interaction.user} Under Review ",color=discord.Color.blue())
        suggest.add_field(name="Your Suggestion: ", value=self.children[0].value)
        suggest.timestamp = datetime.datetime.now()
        suggest.set_footer(text=f"Message id: {m.id}  ")
        channel = self.bot.get_channel(987396375069224960)
        embed = await channel.send('Suggestions Ping: <@&988496229229002792>',embed=suggest)
        await embed.add_reaction('☑')
        await embed.add_reaction('❌')
     

class Suggest(commands.Cog):
    def __init__(self,bot):
        self.bot = bot


    @slash_command(name="suggest", description="suggestions",guild_ids=[964126154774679582,965533467557371944])
    @commands.cooldown(1,7200, commands.BucketType.user)
    async def modal_slash(self,ctx: discord.ApplicationContext):
        await ctx.send_modal(Suggestions(self.bot, title="Suggestion"))



def setup(bot):
   bot.add_cog(Suggest(bot))```
fervent cradle
#

this is close to what I did! Thanks though.

fervent cradle
#

Google is your friend.

#

thanks, didn't expect Google to help with that specific error lol

limber urchin
#

As per #help-rules you should always try to google yourself before asking here

fervent cradle
#

sorry

fervent cradle
#

fatal: couldn't find remote ref main

#

did you use git pull origin master?

mortal junco
#

Guys I know this is kinda stupid but how do I make my bot run by just opening the py file
I paid for a bot hosting just for them to tell me they don’t support the way I open it

limber urchin
#

what?

#

that is literally how you run your bot, by running it's script

#

sounds like a really shitty host if they don't allow you to run python files

fierce hazel
#

Hi, can I fetch the a Guild object from a discord.Cog.listener?

limber urchin
#

depends on what listener it is

full basin
#

You can, whatever listener it is

fierce hazel
#

Thanks!

plush meadow
#

there must be some sort of sauce to it that i can't figure out, because i keep getting a 404

limber urchin
plush meadow
#

oh that would make sense, damn

harsh canyon
#

how would i go about saving audio from start_recording to a mp3 file?

long torrent
#

How do I catch and respond to a "Forbidden" error when using paginator.respond? My page is being defined in a view class and I'm sending it with a slash command by responding with the view.

mortal junco
#

are you avaliable still

#

i run the bot in cmd using python test.py

#

and they said they dont support that

#

i have a cfg file so i cant just run it like that

harsh canyon
harsh canyon
mortal junco
#

if yk what i mean

harsh canyon
#

hmm

#

weird

#

what os is this on?

#

on windows you should be able to right click open with and then python

harsh canyon
#

if your host is using windows i would get a new host if you are trying to do this on your computer i cant help since i dont use windows

#

but probably google will help

full basin
#

?tag tias

obtuse juncoBOT
neon raven
#

Trying to create a /warn command that takes a member as input and warns the user. is this the right way to do so?

  @commands.slash_command()
    async def warn(self, ctx, member : discord.Option(input_type= discord.SlashCommandOptionType.user, description= "Member to be warned", required = True),  reason : discord.Option(type = str , description= "Reason for warning", required = True)):
        await ctx.defer()
        channel = await member.create_dm()
        embed = discord.Embed(title='Warning', description=reason, color=0xff0000)
        embed = embed.add_field(name='Moderator', value=ctx.author.mention)
        embed = embed.add_field(name='Reason', value=reason)
        embed = embed.set_footer(text=f'You have been warned by {ctx.author.name}')
        await channel.send(embed=embed)
        await ctx.respond(f'Warned user {member} for reason {reason}', ephemeral=True)
        channel = discord.utils.get(ctx.guild.channels, id = self.config.get('log_channel'))
        await channel.send(f'Warned user {member} for reason {reason} by <@{ctx.author.id}>')

I am having error at line 3 channel = await member.create_dm() because it is of type str. what is the error here?

harsh canyon
#

assuming you have a vps is it linux or windows?

proud mason
fervent cradle
#

how do add the url to the discord.ButtonStyle.link

proud mason
proud mason
fervent cradle
long torrent
#

Does paginator have support for message defering? When i defer the interaction response I cant respond with my Paginator object

proud mason
#

Show your code

fervent cradle
#

class MyView(discord.ui.View):
@discord.ui.button(label="Something", url="https://discord.com/users/444255651397632001/")
async def button_callback(self, button, interaction, urk):
await interaction.response.send_message("You clicked the button!")

@discord.ui.button(label="Link2", url="https://3itx.live/")
async def second_button_callback(self, button, interaction, url):
    await interaction.response.send_message("You clicked the button!")
Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

fervent cradle
proud mason
long torrent
#

Yea

proud mason
#

What error is raised?

proud mason
#

"text"

long torrent
fervent cradle
proud mason
#

You only out it on 1 side

fervent cradle
proud mason
#

You can also use a codeblock

proud mason
long torrent
# proud mason Hmm

i'm just trying to add a check to tell the user to enable their dm's if the paginator can't be sent but I get that same error if I try and update the message sent without defering it

fervent cradle
#

now?

proud mason
#

Use the self.add_item(discord.ui.Button(label="hi" , url = "url"))

In the init of the view

proud mason
long torrent
#

yea

proud mason
#

Ah so

#

You might have multiple instances of the bot running

long torrent
#

I don't, the bot goes offline and stop responding to commands as soon as I ctrl+c in my terminal

proud mason
#

Hmm

fervent cradle
#

oh there

long torrent
#

it would give me that error when I tried to catch the 403 forbidden error with

 try:
     await paginator.respond(interaction, ephemeral=True, target=interaction.user, target_message="Please check your DMs")
 except discord.errors.Forbidden:
     await interaction.response.send_message("Please enable DMs from server members", ephemeral=True)```
#

indents are all wrong but you get the picture

proud mason
proud mason
#

In the except part

#

Do interaction.followup.send

#

Cuz you have deferred earlier

#

Ig

long torrent
#

That was when I wasn't deferring, now that I am I did do that and I still get the same error.

#
    paginator = Paginator(pages=AppPages, show_indicator=True, use_default_buttons=False, custom_buttons=buttons)
    try:
        await paginator.respond(interaction, ephemeral=True, target=interaction.user, target_message="Please check your DMs!")
    except discord.errors.Forbidden as e:
         print(e)
         await interaction.followup.send(content="Please enable DMs from server members!", ephemeral=True, delete_after=10)
    except Exception as e:
         print(e)
         await interaction.followup.send(content="Something went wrong!", ephemeral=True, delete_after=10)```
#

this is what i'm doing now

long torrent
#

Wait does defering mark the response as done?

#

thats probably why

fervent cradle
#

i got it working

#

:D\

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: ApplicationCommand.call() missing 1 required positional argument: 'ctx'

long torrent
dry cove
#

Perms for group slash command is not working?

proud mason
cobalt tangle
#

help me, im trying to make a dynamic help command with Paginator

mortal junco
#

@worldly tendon please

#

Can you help me with something not involving coding

worldly tendon
#

i have ben summoned

mortal junco
#

I’m trying to host my bot on spark hosting but they don’t support the way I run my bot

#

I do python Test.py to get it to run in cmd

#

But they only support launching the py file

#

But when I try to do it it don’t find other directory’s

#

Don’t know if you understand what I’m sayingdanceYeet

mortal junco
worldly tendon
#

not really

mortal junco
#

So my bot, the way I run it is opening cmd and typing in “python Filename.py

#

But I paid for hosting and they only support the way you run it by running the py file directly which means it can’t find the directory’s with the account info

#

Is that better?

worldly tendon
#

i dont understand what "running the py file directly" means

mortal junco
#

Opening the .py file with python

#

Or running it in visual studio terminal

#

Instead of doing it through the directory cmd

worldly tendon
#

that shouldnt matter tho

mortal junco
#

Well when I launch it with python it says it can’t find the config file

worldly tendon
#

probably because of absolute and relative paths

mortal junco
#

I didn’t import them would that be the issue

#

They are ina. Different folder though so I don’t think you can

mortal junco
#

I need my bot hosted :/

worldly tendon
#
import pathlib
pathlib.Path().resolve()

this gets the path the current file that is being ran is in.
you can then get whatever you need by appending your own path

import pathlib
currpath = pathlib.Path().resolve()
pathOfSomeFile = currpath.joinpath('somefolder', 'somefile.txt')
#

untested

#

let me see if this actuall works

#

yes

#

and then you load pathOfSomeFile

#

@mortal junco

mortal junco
#

I have to do that twice

#

Since I have two txts

#

@worldly tendon wait don’t think that would work because I can’t put that in a txt, I need the path that the two txts are in

#

Or I’m mentally I’ll and confused lnfao

worldly tendon
#

??

#

I need the path that the two txts are in

import pathlib
currpath = pathlib.Path().resolve()
pathOfSomeFile = currpath.joinpath('the', 'path', 'to', 'your' 'textfile.txt')
#

from where that script is executed.

eg

/ bot.py
/ files / mytextfile.txt

then it would be

import pathlib
currpath = pathlib.Path().resolve()
pathOfSomeFile = currpath.joinpath('files', 'mytextfile.txt')
#

I can’t put that in a txt
if you need to put a path in a textfile, you are doing something super wrong

cobalt tangle
#

why does role.id return wrong ID

limber urchin
#

Elaborate

cobalt tangle
cobalt tangle
cobalt tangle
raw gust
#

and generators dont have a length

cobalt tangle
raw gust
cobalt tangle
#

I give cog.walk_commands()

#

I call it in an interaction's callback

#

in dropdown to be exact*

#

I sent the whole code

raw gust
#

ah cog.walk_commands() gives an generator. simply use list(cog.walk_commands())

peak chasm
#

How do I select 2 in my view? Selecting 1 sends it to me automatically. (sample image attached)

peak chasm
#

thanks *** <3

#

i love u :'v

#

💋

raw gust
#

no problem 😉

harsh canyon
steel fjord
#

How can I make a role select type?

proud mason
foggy mortar
#
Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 550, in _inject
    bot.add_command(command)
    ^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 775, in _load_from_module_spec
    setup(self)
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\cog.py", line 129, in setup
    bot.add_cog(cog(bot))
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 645, in add_cog
    cog = cog._inject(self)
          ^^^^^^^^^^^^^^^^^
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 555, in _inject
    bot.remove_command(to_undo.name)
    ^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'remove_command'. Did you mean: 'message_command'?

why this happen

grizzled sentinel
foggy mortar
#

its in the library

#

what u expect me to do

grizzled sentinel
#

The one you used is if your bot was set up for message commands. I assume becouse you are getting an error it is you are not trying to remove a message command

foggy mortar
#

File "F:\fun\Desktop\coding practice\python practice\bot_pycord\cog.py", line 129, in setup
bot.add_cog(cog(bot))
this is the only code i typed in

#

all else is the library

grizzled sentinel
#

Ohhh

#

Can you try renaming the file to something other than cog

foggy mortar
#

ok

#
Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 550, in _inject
    bot.add_command(command)
    ^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 775, in _load_from_module_spec
    setup(self)
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\e.py", line 132, in setup
    bot.add_cog(cog(bot))
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 645, in add_cog
    cog = cog._inject(self)
          ^^^^^^^^^^^^^^^^^
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 555, in _inject
    bot.remove_command(to_undo.name)
    ^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'remove_command'. Did you mean: 'message_command'?

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

Traceback (most recent call last):
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\main.py", line 11, in <module>
    bot.load_extension("e")
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 899, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\cog.py", line 780, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'e' raised an error: AttributeError: 'Bot' object has no attribute 'remove_command'
#

looks the same

#

and i didnt install discord py

grizzled sentinel
#

Can you show your code for the subclass of cog and the whole setup function

foggy mortar
#

so the whole cog file?

grizzled sentinel
#

Yeah you can take out the commands to make it shorter

foggy mortar
grizzled sentinel
#

Do you want slash commands or normal commands or both?

foggy mortar
#

slash commands

#

ah lol 😂

#

so its the line 63

#

yes its working now

#

ty

grizzled sentinel
#

👍

merry briar
#

Is it possible to skip the button somehow, so that it would turn out to be 2 buttons in 3 rows?

view.add_item()

foggy mortar
#

when i do this```py
@commands.Cog.listener()
async def on_application_command(ctx):

how can i make it so it will stop the command running?
kindred moon
#

Does someone have a concise way to have a @tasks.loop-decorator simultaneously loop through a list of input-variables?

#

Say I have a list of four possible values for the input-variable, I want it to use the first parameter in its first run-through, second in the second, etc., and then loop once the list is completed; [1, 2, 3, 4] becomes a run with input = 1, input = 2, input = 3, input = 4, input = 1, input = 2, etc.

neon raven
#

How do i give someone a timeout?

fervent cradle
#

When trying to launch my bot in heroku
I get this error

2022-11-14T17:23:40.513439+00:00 app[web.1]: File "/app/main.py", line 1, in <module>
2022-11-14T17:23:40.513488+00:00 app[web.1]: import discord
2022-11-14T17:23:40.513502+00:00 app[web.1]: ModuleNotFoundError: No module named 'discord'
2022-11-14T17:23:40.655735+00:00 heroku[web.1]: Process exited with status 1
2022-11-14T17:23:40.712509+00:00 heroku[web.1]: State changed from starting to crashed```
I have the github link in requirments.txt file (but spelt right)
fervent cradle
#

Hey

mortal junco
#

@worldly tendon

#

yoooo i did what you asked correctly

#
import discord
import os
import platform
import pathlib

currpath = pathlib.Path().resolve()
pathOfSomeFile = currpath.joinpath('accounts', 'ranked.txt')
pathOfSomeFile = currpath.joinpath('accounts', 'skinned.txt')
client = discord.Bot()```
#

But its saying its missing the config file

#

thats in the same file as the .py

worldly tendon
mortal junco
#

i need to make a different variable

#

i see

#
import discord
import os
import platform
import pathlib

currpath = pathlib.Path().resolve()
AccountPath = currpath.joinpath('accounts', 'ranked.txt')
SkinnedPath = currpath.joinpath('accounts', 'skinned.txt')
currpath.joinpath('config.json')
client = discord.Bot()
worldly tendon
mortal junco
#

why am i defining a variable

worldly tendon
#
import json
import discord
import os
import platform
import pathlib

currpath = pathlib.Path().resolve()
accounts_rankedPath = currpath.joinpath('accounts', 'ranked.txt')
accounts_skinnedPath = currpath.joinpath('accounts', 'skinned.txt')
configPath = currpath.joinpath('config.json')
client = discord.Bot()
mortal junco
#

when would i use that

worldly tendon
#

what?

mortal junco
#

yuh same issue

worldly tendon
#

where is that error in the code

mortal junco
#
    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()```
worldly tendon
#

like, where does it print "[ERROR] ..."

#

json.loads(open("config.json", "r").read())

#
json.loads(open("config.json", "r").read())
# needs to be
json.loads(open(configPath , "r").read())
mortal junco
#

and same for the others?

worldly tendon
#

yes

mortal junco
worldly tendon
#

also, i told you 5 times now that you should not
open("config.json", "r").read())["token"]
do this over and over

mortal junco
#

same thing

worldly tendon
#

you are loading the file again and again

#

just load it once and save it in a variable

mortal junco
# worldly tendon just load it once and save it in a variable
 
try:
    jsonConfig = json.loads(open("config.json", "r").read())
except Exception:
    print("[ERROR] Config File missing")
    input()
 
if "token" not in jsonConfig:
    print("[ERROR] Discord Token not set")
    input()
 
if "guild_id" not in jsonConfig:
    print("[ERROR] Guild ID not set")
    input()```
#

ik u helped me do that

worldly tendon
mortal junco
#

Im working on old code rn just to see if it is hosted

#

code u rewrite dont work os

worldly tendon
#

what do you mean it doesnt work?

mortal junco
#

we never fixed it ive tried for hours

worldly tendon
#

dude

#
import os, json
import pathlib

currpath = pathlib.Path().resolve()
configPath = currpath.joinpath('config.json')
jsonConfig = None

os.system('cls' if os.name == 'nt' else 'clear')
 
try:
    jsonConfig = json.loads(open(configPath, "r").read())
except Exception as e:
    print("[ERROR] Config File missing")
    print(configPath)
    print(e)

if "token" not in jsonConfig:
    print("[ERROR] Discord Token not set")
    input()
 
if "guild_id" not in jsonConfig:
    print("[ERROR] Guild ID not set")
    input()

this works, i just tested it

#

@mortal junco

mortal junco
#

the role part of the code

#

dont work we tried to fix it

worldly tendon
#

i just tested it

#

it works

worldly tendon
#

and change it so you have your other variables in it too

mortal junco
#

@worldly tendon done exactly as you said

worldly tendon
#

NO YOU DID NOT

#

i can see it in the error message

#

@mortal junco

#

bro come on

#

use your eyes

mortal junco
#

DUDE im not using that code you wrote me

#

it does not work

#

im reffering to the rest of the code

#

not the top part

#

when i give myself the role

#

it just dont see that

worldly tendon
#

it would work if you did it correctly

#

¯_(ツ)_/¯

mortal junco
#

i did do it correctly..

#

im not fucking worried abt your code that involves opening a config, i could care less if it corrupts it has 2k lines in it that is stored on a backup, i just want to be able to host it

#

:/

worldly tendon
#

oh my god

#

you are not able to host it because the paths are messed up.
using the code i gave you at the top, will fix the paths, however you need to use those variables everywhere

#

i have told you before that cleaner code helps you to resolve issues and this is the exact same thing here

#

i cant help you any more if you are completly resistent

mortal junco
#

The bottom part of your code dont work i cant use your variable if im not using it like thast...

worldly tendon
#

even if my code doesnt work, i told you the reason and how you can avoid the relative and absolute path issues

#

then you need to do it yourself

mortal junco
#

guess im hosting formyself forver since there is no good hostings

#

that provide windows support

limber urchin
#

Why do you need to host on Windows?

mortal junco
#

the file dont work

#

because some kinda path issue

#

that slluxx is trying to make me rewrite my whole code

limber urchin
#

It looks to me like they're doing their best to help you but you aren't understanding their solution

#

which is not their fault

#

if you aren't happy with their suggestions then don't use them, but in that case all that's left is for you to figure it out on your own

worldly tendon
#

I dont care if you rewrite your code or not. But if you did write your code in an organized way in the first place, the question "why something doesnt work" is almost never come up. You will almost always know whats going wrong because you can see and easily debug it.

#

Thats the secret

mortal junco
worldly tendon
#

before you restart, you should read about code design, you should read about cog's in pycord and in general watch some videos about tipps & tricks in python

#

especially classes

mortal junco
#

omfg dude

#

i fixed this and now its doing it again when i restarted from default code and there is no loops this tme

loud holly
mortal junco
#

whihc has nothing to do with that

worldly tendon
#

thats not true

loud holly
worldly tendon
#

i was informing you that a)
loading a json file 4 times instead of writing it into a variable is inefficient
and b) that if you read and write to json files, they can become corrupted due to race conditions

loud holly
#

that's why we're suggesting you from early on to use a good database

limber urchin
#

?tag nojson

obtuse juncoBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

  • SQLite3 (File based, no need for a server setup, SQLite is the most used database engine in the world)
  • MongoDB (Stores data in documents a similar manner to JSON format, easy for beginners)
  • PostgreSQL (Very popular and robust SQL based database management system)
  • MySQL (Another popular SQL based system, good start for learning SQL)
loud holly
#

it's a good practice, then later on you won't have to complain to urself on you transferring data over since that is a hassle on its own if you want to keep ur users happy

worldly tendon
#

^

#

even if you dont care, you should still do good/best practices so you dont develop a habbit of doing it the lazy, inefficient and borderline dangerous (as in race conditions and file corruption) way

mortal junco
#

Okay, well i was just asking about hosting it you told me how

#

but then you start asking me to change my variables to the same way

#

it was before where it didnt open them

worldly tendon
#

i am not going to argue with you anymore.
ive been developing for over 15 years, a lot of that time professional.

When i started i knew jack shit and asked for help too. I definitely wouldnt be as good without all the awesome tips and tricks from other people. Listeneing to them is a must to get better and learn more.

I am showing you a lot of code for how you should go about things, just for you to see how its done and you are not understanding that you need to research the things on your own too and that you cant just copy paste them into your code - you will never learn this way

#

and because you think i am missunderstanding or ignoreing your questions, then you didnt understand the things i told you.

mortal junco
worldly tendon
#

but thats the wrong mentality

#

and i will not support that

mortal junco
#

I WILL Get it to work after i get my money working bro...

worldly tendon
#

good luck

mortal junco
#

being rude for no reason wont help because i wont use a shitty sqllite

#

because im not spending hours reading doccumentation

limber urchin
#

then you probably shouldn't be a developer

worldly tendon
#

thats not the reason whatsoever, you are still not understanding

limber urchin
#

if you want to get good at programming you'll have to read documentation, there's no getting around that

mortal junco
#

and then you bring up the json

#

and gave up on helping me

worldly tendon
mortal junco
#

and just keep bitching about the json

#

i dont care right now i want to get my money working...

#

i can fix it later

#

did exactly what you asked and asked how i would do it

#

and then u just ignore me and bitch about my json file

worldly tendon
#

i didnt advice you to buy anything. its not my fault that your code is crap
i am telling you how to fix your own things but all you want is working code

mortal junco
#

i just want to be able to host

worldly tendon
#

if it would work fine, you would be able to host it

mortal junco
#

But your not helping me your just complaining abt my json files

worldly tendon
#

advice =/= complaining

mortal junco
#

okay bro you gave me this advice days ago

#

i wanna know how to fix this

#

not deal with this json file shit again

worldly tendon
#

then print the exception and use google

cyan quail
#

maybe

  1. don't just copy full codeblocks and expect everything to go flawlessly without reading into it
  2. don't provide full blocks of code for people to yoink and micromanage everything they're doing
    this channel isn't for spoonfeeding, it's for assistance. If what you're doing is beyond return, try to take it from the top and maybe find other people to talk to
limber urchin
#

Are you actually expecting an explanation, or are you just waiting for someone to write you a code block that you can copy and paste?

mortal junco
cyan quail
#

and what i'm saying is you don't just throw around finished code, it's better to guide people to resources so they can figure it out themselves

worldly tendon
#

#998272089343668364 message

mortal junco
#

YES AND I APPENDED my path

worldly tendon
#

based on the code, and if you have a brain, you can understand what it does

mortal junco
#

and its the same shit

worldly tendon
#

oh my

cyan quail
#

ok look

#

or rather, stop

#

let's take it from the top; what's the issue?

mortal junco
#
import discord
import os
import platform
import pathlib

currpath = pathlib.Path().resolve()
accounts_rankedPath = currpath.joinpath('accounts', 'ranked.txt')
accounts_skinnedPath = currpath.joinpath('accounts', 'skinned.txt')
configPath = currpath.joinpath('config.json')
client = discord.Bot()```
mortal junco
cyan quail
#

so what exactly is the issue with the host? most are inclined to be running on linux

#

but they typically make the setup not too difficult

worldly tendon
#

the issue is that his config.json is not being recognized

#

i thought it might be absolute / relative issue based on the hoster / os

cyan quail
#

that probably is the issue, but instead of using pathlib you can use typical path notation

cyan quail
mortal junco
mortal junco
worldly tendon
#

that has some issues in certain cases. pathlib is a good lib

his issue is that he doesnt apply the variables to the places where the config files are loaded

cyan quail
#

so let's say

#

you have a main file in the root folder?

mortal junco
#

yes,

cyan quail
#

and where is the json located

mortal junco
#

i only have one .py

#

and the json is located in the same folder

#

as the main file

cyan quail
#

just in case, what about /home/container/config.json"

mortal junco
#

huh?

cyan quail
#

as the path

#

don't bother with pathlib, just use strings for your path

mortal junco
#

well im testing it on my pc

mortal junco
cyan quail
#

you should test on the server...

#

python takes regular strings as paths perfectly fine

worldly tendon
#

btw because he is testing on windows and has his server, using pathlib saves you a lot of trouble, as you never have to deal with os dependent slashes or absolute/relative paths

cyan quail
#

sure you might be developing on windows on your pc, but if you're hosting on a server then ideally all your testing should be done there to avoid conflicts with your environment

#

i mean in this scenario you don't have to care because python accepts / on both windows and linux

worldly tendon
#

true but this way i could also teach him about a lib which he would have otherwise not known. that was kind of the point for me. and the lib is really handy not just for paths

mortal junco
#

I have no clue how to use paths :/

#

as u can tel

cyan quail
#

pathlib is indeed useful, but instead of jumping right into it it'd be better to go with the basics so that it at the very least works

worldly tendon
#

i was under the assumption he at least knows how to write "/some/path/file.ext"

mortal junco
#

i know how to write a directoryu

#

but no clue the use of it

#

/
home
/
container
/
accounts
/
Ranked.txt

#

would be the directory for the host

cyan quail
#

also note that linux file paths are case sensitive

#

for the config, just do "config.json"

worldly tendon
#

im just gonna tune out now, i have to get control over the aneurysm back

cyan quail
#

havefun

mortal junco
#
import discord
import os
import platform

accounts_rankedPath = /home/container/accounts/Ranked.txt
accounts_skinnedPath = /home/container/accounts/Skinned.txt
configPath = "config.json"
client = discord.Bot()```
@cyan quail
#

this what ur syaing

cyan quail
#

remember to use quotes for strings

mortal junco
#

'

#

that instead of "

#

?

#

Why jw

cyan quail
#

no either works, but you forgot them on your first two variables

mortal junco
#

Yeah i just realized

#

File "/home/container/LightStore.py", line 10, in <module>
client = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'

cyan quail
#

reinstall py-cord on your server

mortal junco
#

yeah

#

this servers so fucking annoying bro

#

it has a startup command that i legit cant change

#

and i cant run the server

cyan quail
#

? what's the issue

mortal junco
#

if [[ -d .git ]]; then git pull; fi; if [[ ! -z ${PY_PACKAGES} ]]; then pip3 install -U --prefix .local ${PY_PACKAGES}; fi; if [[ -f /home/container/requirements.txt ]]; then pip3 install -U --prefix .local -r requirements.txt; fi; python3 /home/container/${STARTUP_FILE}

#

startup command that i cant change bruh

cyan quail
#

so is it erroring?

mortal junco
#

yeah same error

#

i cant install pycord

cyan quail
#

have you perhaps tried

mortal junco
#

i cant change it

#

wait

fervent cradle
cyan quail
#

yeah

mortal junco
#
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 788, in process_application_commands
    command = self._application_commands[interaction.data["id"]]  # type: ignore
KeyError: '1041781046313762947'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1141, in on_interaction
    await self.process_application_commands(interaction)
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 811, in process_application_commands
    await self.sync_commands(check_guilds=[guild_id])
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 711, in sync_commands
    app_cmds = await self.register_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 513, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
cyan quail
limber urchin
mortal junco
#

i might need to on the hosting aswell

cyan quail
#

do you have the applications.commands scope for your bot in the listed servers?

mortal junco
#

yeah

cyan quail
#

hm

fervent cradle
cyan quail
#

your issue is in get_guild_commands which indicates your bot isn't in one of the servers

#

yeah

mortal junco
#
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 711, in sync_commands
    app_cmds = await self.register_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 513, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
#

immeditaly after hitting start

#

thats what happens

#

ill kick it and reinvite it

cyan quail
#

quite literally, "Missing Access" - triple check all your guild ids

#

or if you want you can remove them to register to all guilds

mortal junco
#

these two righttt

cyan quail
#

yes, it has to be invited with them

#

note you don't have to kick

#

you can just use the url again

mortal junco
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1138, in on_connect
    await self.sync_commands()
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 711, in sync_commands
    app_cmds = await self.register_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 513, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
  File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 353, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
#

same issue

cyan quail
#

how many guild ids do you have

mortal junco
#

One

cyan quail
#

are you sure it's the right token?

mortal junco
#

100%

cyan quail
#

and the guild id is an integer right

mortal junco
#

Yes

cyan quail
#

what if you remove the guild_ids parameter completely

mortal junco
#

i fixed it

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 974, in _invoke
    await self.callback(ctx, **kwargs)
  File "/home/container/LightStore.py", line 108, in stock
    await ctx.respond(embed=embed)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/context.py", line 282, in respond
    return await self.interaction.response.send_message(
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 825, in send_message
    await self._locked_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 1090, in _locked_response
    await coro
  File "/home/container/.local/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.embeds.0.fields.0.value: This field is required

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

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1088, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 374, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.fields.0.value: This field is required``` 
An error that happens when running /stock, but dont do it when im hosting on my pc
cyan quail
#

how did you define the embed

#

and all its fields

#

your first field has value=None some way or another, perhaps you forgot to check a variable

mortal junco
#
async def stock(ctx):
    services = ["Ranked", "Skinned"]
    stocklist = []
    for service in services:
        if os.path.exists(f"accounts/{service.lower()}.txt"):
            stocklist.append(f"{service} stock: {len(open(f'accounts/{service}.txt', 'r').readlines())} accounts")
    embed = discord.Embed(title="LightStore Stock", description="Display's stock of all services", color=0x46a9f0)
    embed.add_field(name="Account Stocks", value="\n".join(stocklist))
    await ctx.respond(embed=embed)```
#

the \n is purposeful

cyan quail
#

so assentially, your stocklist list is empty because those paths are wrong

mortal junco
#

its empty on purpose

#

it never has beenb filled

cyan quail
#

then that's always gonna error

mortal junco
#

why does it not error on windows

cyan quail
#

because it was filled

#

remember that paths in linux are case sensitive

mortal junco
#

what are u talking abt im so confused

#

this has nothing to do with a path?>?

cyan quail
#

what did the embed visually look like on windows

#

when you sent it

mortal junco
cyan quail
#

so obviously it had values in it

mortal junco
#

thats account stock

cyan quail
#

yes

mortal junco
#

not stocklists

#

stlocklist has been empty ever since i coded it

cyan quail
#

my guy

#

read your code

#
    embed.add_field(name="Account Stocks", value="\n".join(stocklist))```
mortal junco
#

yes????

peak chasm
#

Is there a way to put spaces in the embeds?

cyan quail
#

your "Account Stocks" field uses stocklist

mortal junco
#
async def stock(ctx):
    services = ["Ranked", "Skinned"]
    stocklist = []
    for service in services:
        if os.path.exists(f"accounts/{service.lower()}.txt"):
            stocklist.append(f"{service} stock: {len(open(f'accounts/{service}.txt', 'r').readlines())} accounts")
    embed = discord.Embed(title="RadiantStore Stock", description="Display's stock of all services", color=0x46a9f0)
    embed.add_field(name="Account Stocks", value="\n".join(stocklist))
    await ctx.respond(embed=embed)```
limber urchin
mortal junco
#

this is windows host code

cyan quail
#

the for loop above it fills it

#
            stocklist.append(f"{service} stock: {len(open(f'accounts/{service}.txt', 'r').readlines())} accounts")
#

the reason this doesn't work on linux is because of this ```py
if os.path.exists(f"accounts/{service.lower()}.txt"):

#

your text files start with a capital letter, but you're using .lower()

fervent cradle
mortal junco
#

no they dont

cyan quail
#

but they do....

mortal junco
#

wait

limber urchin
mortal junco
#

NEVERMIND ILL SHUT UP

cyan quail
mortal junco
#

yes yes yes

#

ik im slow

peak chasm
cyan quail
#

look i don't mind helping you but it's rather worrying that i know your code more than you do

mortal junco
#

wheres the ()lower at?

fervent cradle
cyan quail
#

in the os.path.exists

#

you can ctrl+f that to find

mortal junco
#

And on linux i change it to Lower right

cyan quail
#

no, it should be removed

cyan quail
#

on linux the file names should match the case

mortal junco
#

just completely delete that line>?

cyan quail
#

no, remove the .lower()

#

because you don't want to convert it

mortal junco
#

oh okay how do u know all this abt linux?

cyan quail
#

i mean most bots are hosted on linux

fervent cradle
cyan quail
#

if you develop for a while, even if you don't use the os you pick up some stuff

mortal junco
#

Thank youuuuu ❤️ s

cyan quail
#

havefun

#

do feel free to return for help, but also giving your own go at problems and figuring out solutions yourself will improve you in the long run

mortal junco
#

@cyan quail one second if you dont mind

#

do i fr have to keep this page open

#

24/7 ?

cyan quail
#

the server page? no lol

#

it's a host for a reason

mortal junco
#

lmao i was confused

cyan quail
#

but you should check the console for any errors

mortal junco
#

okay,

cyan quail
#

i recommend keeping it bookmarked or as a shortcut

tender seal
cyan quail
#

hover over it with your mouse

tender seal
#

this is the error

#

'str' has no attribute 'id'

cyan quail
#

your error looks like it's coming from somewhere else

tender seal
#

hm

cyan quail
#

can you post the full traceback?

#

oh wait im blind

#

add_roles takes a discord.Role object

tender seal
#

o

cyan quail
#

if you have a role id, you can use ctx.guild.get_role

tender seal
#

how would I add a role to a user then

cyan quail
tender seal
#

I'm using discord.bot

#

does get_role grant a user a role?

#

(member)

cyan quail
#

get_role gets the Role object

#

then you can use it in add_roles

tender seal
#

oh

#

ok thanks, I'll try that

#

this?

cyan quail
#

yeah that works

tender seal
#

k

cyan quail
#

though

#

note you have to respond to slash commands

proud mason
cyan quail
#

true

tender seal
#

is the bot missing perms?

cyan quail
#

your bot can't add the role

proud mason
#

Yea

tender seal
#

alr

lost lodge
#

How can i filter the member update event to only the role update

cyan quail
#

compare before.roles and after.roles

fervent cradle
#

anyone have an example for an chat clear bot in cogs

cyan quail
#

i mean

#

not an entire bot, you only really need purge

fervent cradle
#

kk ty

lost lodge
#

after.nick ?

cyan quail
#

well, yeah

#

the same goes for every attribute

lost lodge
#

but now the users name is like...

limber urchin
#

The attribute isn't literally called "nick"

#

look up the docs and you'll see all available attributes of the event parameters

limber urchin
#

Oh really? Wow

cyan quail
#

i'd say it probably should be called nickname but the official api also uses nick

lost lodge
#

with nickname it don't works

limber urchin
cyan quail
#

yeah it doesn't exist

limber urchin
lost lodge
#

but the user have a nickname

#

ah now it works

#

don't know why

exotic holly
#

My inputs were 4 and 4.4, although the type is an int, the float is getting accepted and converted to an int by removing the decimal point. Any solutions?

limber urchin
#

You're type hinting amount to int, which means it's going to convert the parameter to int

#

You could make it accept float and do your own check inside of the command

exotic holly
#

my inputs were 3 and 3.3, same problem now with float

peak chasm
#

how to put emoji?

full basin
#

Author, footers and field names don't render markdown or emotes.

peak chasm
#

:'v

#

I didn't say anything it was emoji="id"

exotic holly
limber urchin
peak chasm
#

Is it possible to leave value blank?

full basin
#

Try it and see

limber urchin
#

Pretty sure you can't, you'd have to use some sort of whitespace/zero-width character

raw gust
#

Jup zero width character

limber urchin
#

You could add a handler for it in your on_application_command_error

woeful spindle
#

since I may use other checks and I want the errors for those

woeful spindle
#

no?

#

there is on_message

#

if your intention is to count a user’s message, that’s the event you’d use

limber urchin
young bone
#

you have to do it on your own

young bone
#

if you google it you will find something

#

For Threads yes

limber urchin
#

Then use the on_message event and increment a number on each event received

harsh canyon
#

how would i go about saving audio from start_recording to a mp3 file?

#

.wav

#

doesnt really matter

#

whatever

#

messed around trying to save it using wave but im out of my depth and dk what im doing

twilit valley
#

I'm having some issues with embeds being edited

    async def select_callback(self, select, interaction):
        await interaction.edit_original_response(content=None, embed=self.crh_info_embed_maker(select.values[0]))

returns a 404 error. However,

    async def select_callback(self, select, interaction):
        await interaction.message.edit(content=None, embed=self.crh_info_embed_maker(select.values[0]))

does actually edit the message and replace it with the correct embed. The problem is that it returns a "embed failed" error... and I have no idea how to get rid of it

fervent cradle
#

Is there an event like "on_respond" or something that only triggers if people respond to a message of the bot? (on_interaction also calls whenever a message is written anywhere which seems quite inefficient)

fervent cradle
kindred moon
#

Quick Q; can one have a clickable hyperlink in an Embed-footer?

fervent cradle
#

Is there a way to reload a slash command? I've tried bot.reload_extension(cog.x), but the parameter discord.Option(choices=list) does not update, only a bot restart seems to reload the parameter.

kindred moon
lost cypress
#

is there a way of getting the value of a modal without inheriting?

#

nvm i wasnt thinking

twilit valley
# fervent cradle Can you show the error message?
  File "C:\Users\generaldarian\Desktop\EUROBOT\EuroBot_Dev\venv\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\generaldarian\Desktop\EUROBOT\EuroBot_Dev\EuroBot\src\commands\infoCrh.py", line 64, in select_callback
    await interaction.message.edit_original_response(content=None, embed=self.crh_info_embed_maker(select.values[0]))
AttributeError: 'Message' object has no attribute 'edit_original_response'

the version is 2.2.2

#

and yeah replacing it with py interaction.message.edit(...) works but it keeps sending the "interaction failed" message even though it successfully edits..

wanton wedge
#

i cant seem to figure out how to make my bot wish someone automatically on their birthday can anyone help me?

limber urchin
limber urchin
twilit valley
# limber urchin Try `interaction.edit_original_response`. Remove the `.message` part
Traceback (most recent call last):
  File "C:\Users\generaldarian\Desktop\EUROBOT\EuroBot_Dev\venv\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\generaldarian\Desktop\EUROBOT\EuroBot_Dev\EuroBot\src\commands\infoCrh.py", line 64, in select_callback
    await interaction.edit_original_response(content=None, embed=self.crh_info_embed_maker(select.values[0]))
  File "C:\Users\generaldarian\Desktop\EUROBOT\EuroBot_Dev\venv\lib\site-packages\discord\interactions.py", line 428, in edit_original_response
    data = await adapter.edit_original_interaction_response(
  File "C:\Users\generaldarian\Desktop\EUROBOT\EuroBot_Dev\venv\lib\site-packages\discord\webhook\async_.py", line 213, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
foggy mortar
meager heron
foggy mortar
meager heron
#

Check the documentation. It explains

foggy mortar
#

but i cant find one that is what i want to do

#

wait if you do return in a event will it stop the command running?

silver moat
#

yes

foggy mortar
#

oh

silver moat
#

at least for app. commands

foggy mortar
#

async def on_interaction(self,ctx:discord.Interaction): is not called when i run a slash command

#
    @commands.Cog.listener()
    async def on_interaction(self,ctx:discord.Interaction):
twilit valley
#

ty!

cobalt tangle
#

oki

prime steppe
#

how do I get the guild id from the slash command

(like when someone sends it I need to find which guild it was send it)

limber urchin
foggy mortar
foggy mortar
#
    @commands.Cog.listener()
    async def on_application_command(self,ctx:discord.ApplicationContext):
limber urchin
#

Is there a reason you're defining it in a cog?

foggy mortar
#

cuz im writing a cog 🤷‍♂️

young bone
#

for what do you need that?

limber urchin
#

just define the event listener in your main file once, there's no reason to have that event in a cog

foggy mortar
#

ok

fervent cradle
#

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction im confused how i got this error

limber urchin
#

hard to say without seeing the code that caused the error

fervent cradle
#

sure

#
@bot.slash_command(description="Get the account id of a epic games username!")
@option("display", str ,description='Epic Games display name')
async def gay(ctx, display):
    await ctx.respond(f"{lp(display)}")```
#

need the function code too?

foggy mortar
#

or maybe you clicked a button that is generated before the bot restart and you pressed that button after the bot restart

fervent cradle
#

theres no buttons

fervent cradle
#

a function

#
def lp(display):
    x = requests.get("https://account-public-service-prod.ol.epicgames.com/account/api/public/account/displayName/"+str(display), headers=token).json()
    if "links" in x:
        y = requests.get(f"https://account-public-service-prod.ol.epicgames.com/account/api/public/account?accountId="+x['id'], headers=token).json()[0]
        z = y['externalAuths']
        try: # Nintendo
            nintendo_id = z['nintendo']['externalAuthId']
        except:
            nintendo_id = "N/A"
        try: # Steam
            steam_display = z['steam']['externalDisplayName']
            steam_id = int(z['steam']['externalAuthId'])
        except:
            steam_display = "N/A"
            steam_id = "N/A"
        try: # PSN
            psn_display = z['psn']['externalDisplayName']
            psn_id = int(z['psn']['externalAuthId'])
        except:
            psn_display = "N/A"
            psn_id = "N/A"
        try: # Xbox
            pass
        except:
            pass
        return json.loads("""{
            "nintendo": {
                "id": "%s"
            },
            "steam": {
                "display": "%s",
                "id": %d
            },
            "psn": {
                "display": "%s",
                "id": %d
            },
            "xbl": {
                "display": "placeholder",
                "id": "placeholder"
            }
        }""" % (nintendo_id, steam_display, steam_id, psn_display, psn_id))
    else:
        return x```
limber urchin
#

Alright, first of all don't use the requests library for Discord bots

#

and you probably need to do a ctx.defer before running the function because it takes too long

limber urchin
#

?tag requests

obtuse juncoBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

amber shale
#

thanks

foggy mortar
amber shale
#

i was making small bot using only requests

fervent cradle
limber urchin
fervent cradle
#

works fine now, idk what was up with it

amber shale
#

yeah i will change it (just made first successful communication with discord 🙂 )

limber urchin
fervent cradle
#

ill see about switching to another lib and using defer

foggy mortar
#

can any of you answer that?

fervent cradle
#

im not too smart lol

limber urchin
fervent cradle
#

gotcha

#

might just use httpx seems like the syntax is just like requests

alpine helm
#

how do you add emotes in embed titles

young bone
alpine helm
#

yeah

young bone
#

<emoji name:emoji id>

alpine helm
#

doesn't work

#

emoji exists

#

When i send <:emote:id>

#

it shows up

#

but not in embed

limber urchin
#

Where in the embed are you trying to use the emoji?=

alpine helm
#

title

limber urchin
#

You can not use emojis in the title of an embed

#

other than unicode emojis

alpine helm
#

this is custom?

#

animated

#

Any Idea?

limber urchin
#

Isn't that just in the description, but in bold and underlined?

round rivet
#

You can use emojis in titles I though

peak chasm
#

How do I make it so that when I turn on the bot, it continues to recognize the classes "my View"

glossy socket
#

hey, im getting this weird error thats in the txt when i try to move my discord bot to my rdp. it works fine on my laptop

#

anyone know whats causing this? it seems to be something within the py-cord package

young bone
#

you use python 3.11

glossy socket
#

huh im pretty sure i use python 3.10

young bone
#

no?

glossy socket
#

nvm

#

youre right

young bone
#

^^

young bone
glossy socket
#

ahh yeah i see it, ive never tried 3.11 yet myself until now

fervent cradle
#
 @bridge.bridge_command(name='8ball',description='Predict any question.')
  async def _8ball(self,ctx,question):
    options = ["Nope",
          "Correct",
          "Yes.",
          "I think so",
          "No",
          "Incorrect",
          "Perhaps",
          "I am unsure", 
          "From my POV, I say yes.",
          "Im struggling to predict right now",
          "Im not going to give you an awnser right now, try again."
          "Not convinced"]
    await ctx.respond(f"{random.choice([options])}")``` Why is my bot sending all the strings instead of just one?
meager heron
fervent cradle
#

Oh okay thanks

fervent cradle
# meager heron `random.choice(options)`, not `random.choice([options])`
  @commands.command(name='8ball',description='Predict any question.')
  async def _8ball(self,ctx,question):
    options = ["Nope",
          "Correct",
          "Yes.",
          "I think so",
          "No",
          "Incorrect",
          "Perhaps",
          "I am unsure", 
          "From my POV, I say yes.",
          "Im struggling to predict right now",
          "Im not going to give you an awnser right now, try again."
          "Not convinced"]
    await ctx.send(random.choice(options))```
Invalid interaction application command
#

I changed my code, so its only prefix & this happened?

#

It could be something to do with the first line although im not sure

meager heron
#

I don't use bridge commands, but doesn't that require a special bot instance?

#

Assuming you have that, don't you want to do the bridge decorator?

fervent cradle
#

Im no longer having it bridge, just prefix alone (as bridge wouldnt work with empheral)

meager heron
#

Message commands can't do ephemeral, either

fervent cradle
#

I am just struggling making it into a prefix command

meager heron
#

Are you still using discord.ext.bridge.Bot?

fervent cradle
meager heron
#

Check?

young bone
meager heron
#

Because that might be your issue

fervent cradle
meager heron
#

Where you're initializing your bot

young bone
#

do you know basic python?

fervent cradle
#

Sorry i checked, im not using it

meager heron
#
bot = discord.Bot(...)

or

bot = discord.ext.bridge.Bot(...)
young bone
#

that is for slash_commands/app_commands

meager heron
#

Use discord.ext.commands.Bot

fervent cradle
#

Works now, appreciated

woeful spindle
woeful spindle
woeful spindle
#

that’s why :)

alpine helm
# alpine helm

But I have this bot in my server but not that ezgif emote

woeful spindle
#

as long as your bot is in x server which is where the emoji is, you can use the emojis

alpine helm
#

Thats a yes

#

Okay so let me explain

#

I have two servers, one is support server and the other is dev server. I want to have all the emojis I need in the dev server so that support server is not flooeded with trash emojis. So the dev server has <x:id> and the support server doens't. But when i use the embed in support server , it doesnt' appear in the title

woeful spindle
#

is your emoji in that format in your code?

alpine helm
woeful spindle
#

strange, does your bot have external emoji perms?

alpine helm
#

if i just paste that emote code then it appears in teh support server

alpine helm
woeful spindle
#

I’m unsure then, sorry

alpine helm
#

its fien

foggy mortar
#

how can you stop a command running in an on_application_command event?

meager heron
#

You stop it in on_interaction

#

on_application_command happens after it runs

foggy mortar
meager heron
#

do your check
if check passes, run process_application_commands(interaction)
if not, pass

foggy mortar
#

ok

#
Ignoring exception in on_interaction
Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\e.py", line 80, in on_interaection
    await ctx.response.send_message(f'you need to use /play command first')
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\interactions.py", line 825, in send_message
    await self._locked_response(
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\interactions.py", line 1089, in _locked_response
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
#

this is it

meager heron
#

on_interaection

foggy mortar
#

yes cuz i had defined that in the decorator

meager heron
#

What decorator? Stack trace isn't really helpful here

foggy mortar
#

@discord.Cog.listener(name='on_interaction')

#

i tried commands.Cog.listener and its still the same

meager heron
#

But you need to check if an interaction has been responded to before interaction.response.send_message

#

And use followup.send if it has

foggy mortar
#

ok

#

but what if i want to response before the command

#

and stops the command from running

meager heron
#

Code?

foggy mortar
#
@discord.Cog.listener(name='on_interaction')
    async def on_interaection(self,ctx:discord.Interaction):
        print('e')
        if str(ctx.user.id) not in self.data:
            await ctx.response.send_message('you need to use /play command first')
            await self.bot.process_application_commands(ctx)
#

the e did print

young bone
#

why do you use name=""?

meager heron
#

Just give the function the correct name and get rid of the name bit, yeah?

#

If you don't want the command to run, process shouldn't be in that if block

#

Put it in an else

foggy mortar
young bone
#

?

foggy mortar
#

classmethod listener(name=...)

limber urchin
foggy mortar
#

yes but i have multiple on_interactions

limber urchin
#

You shouldn't

#

Realistically you only need one of each event handler

foggy mortar
# meager heron Just give the function the correct name and get rid of the name bit, yeah?

still same error

Ignoring exception in on_interaction
Traceback (most recent call last):
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "F:\fun\Desktop\coding practice\python practice\bot_pycord\e.py", line 80, in on_interaction
    await ctx.response.send_message('you need to use /play command first')
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\interactions.py", line 825, in send_message
    await self._locked_response(
  File "C:\Users\fun\AppData\Roaming\Python\Python311\site-packages\discord\interactions.py", line 1089, in _locked_response
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
meager heron
#

And if true, use ctx.followup.send

#

But I think you are going to run into some serious problems with multiple on_interactions

#

You'll need the check in each one, because if only one refuses the command, the others will still pass it

foggy mortar
meager heron
#

It will still work

foggy mortar
#

but it does this

meager heron
#
if ctx.response.is_done():
    await ctx.followup.send(...)
else:
    await ctx.response.send_message(...)
await self.bot.process_application_commands(ctx)
meager heron
#

They all get called

foggy mortar
#

so i ran a command called /getid
and it sent the response of that command
then it send the response of the on_interaction event

meager heron
#

I've never run on_interaction in a cog. I'm not sure if it behaves differently than just using a bot listener

foggy mortar
#

i solved it by adding a method that takes in the ctx and run it in every command

fervent cradle
#

What would i have to do to have it like this?
so for eg
You send !ban instead of !ban (member)

Like i want it to send an embed saying wrong args, ect

#

But im unsure of what event would activate this, or error

limber urchin
#

You could default the parameter to None, and add a check in your command executor to make sure the parameter is not None, if it is, send an embed saying there are missing arguments

fervent cradle
limber urchin
#

No, that is not how you add defaults to a parameter in Python

fervent cradle
#

Thank you

foggy mortar
fervent cradle
#

Oh i understand that easier lol

limber urchin
#

You should never just use except, always add the type of error you want to catch

foggy mortar
#

i forgot what it called

#

is it ListIndexOutOfRange?

fervent cradle
foggy mortar
#

IndexError

#

got it

loud holly
fervent cradle
limber urchin
#

I recommend you to read this

#

It's pretty basic python, which is expected to know when going into bot development

fervent cradle
limber urchin
#

They told you, it's IndexError

fervent cradle
#

yup, thats all i asked for i just wanted to double check

#

thanks

quick temple
#

How can I set the cooldown for every command in a SlashCommandGroup? (without having a decorator for every command)

foggy mortar
#

is there even a way to set cooldown(?

limber urchin
#

Yes, with the commands.cooldown decorator

meager heron
opaque glacier
#

how do i set a custom color for an embed

young bone
woeful spindle
winter condorBOT
opaque glacier
#

thanks

woeful spindle
#

I don’t think the one sent by the bot works

rare ice
#

Having highlight in there doesn’t do anything

#

Wait

#

The docs don’t have an attribute color for embeds but you can use color

#

.jsk py

embed = discord.Embed(color=discord.Colour.embed_background(), description="_ _")
#

yeah

peak chasm
#

How do I make it so that no one can use the commands from the priv with the bot?

full basin
#

guild_only decorator

fervent cradle
#

How can i use a default emoji with role.edit(icon=...)

#

Nevermind, figured it out

loud holly
#

is there a way to add channel_selects without a decorator aka with View (in class self)

#
self.add_item(
            discord.ui.Select.channel_types(
                placeholder=f"Select the {self.channel_type} Channel",
                min_values=1,
                max_values=1,
                channel_types=[ discord.ChannelType.text ]
            )
        )
#

this is my current one and it says property, I'm not sure if I'm doing in incorrectly

full basin
cobalt tangle
#

why does this happen

young bone
cobalt tangle
#

nvm fixed

#

indentation issue :(

kindred moon
#

Can the @slash_command-decorator from discord.commands be tuned to be checked at runtime instead of Class definition time? Or could someone outline the steps said decorator goes through to register an application command? Long story short: I wanna use a variable from self which can't be done because decorating happens before __init__.

limber urchin
#

Setting dynamic values in a decorator is generally pretty unusual, what's your usecase?

kindred moon
#

So wanting to dynamically fetch the guild_ids-list to parse into the decorator.

limber urchin
#

For prod you probably don't want to pass any guilds at all

kindred moon
#

How would that affect the decorator? Registers to all guilds it's present in?

limber urchin
#

Not passing any guilds means the command is registered globally, so yes, it would register to every guild

kindred moon
#

Interesting, thanks for that info. But then I'm still searching for a way to be able to limit the guilds it gets registered to dynamically.

limber urchin
#

I guess you could try doing something with global variables, not sure since I've never had to do it myself

kindred moon
#

That will be my last resort, yeah. Was hoping to steer clear of globals but if there's no other way it be like that sometimes.